diff --git a/data/flags.json b/data/flags.json index 29964980..ef762e78 100644 --- a/data/flags.json +++ b/data/flags.json @@ -1,7 +1,7 @@ { "format":1, "source":"GameData/GameDataList.Product.110", -"counts":{"total":26654,"named":19838,"by_type":{"Binary":{"total":11,"named":2},"BinaryArray":{"total":2,"named":2},"Bool":{"total":11292,"named":10081},"Bool64bitKey":{"total":11657,"named":6496},"BoolArray":{"total":13,"named":7},"BoolExp":{"total":884,"named":866},"Enum":{"total":130,"named":107},"EnumArray":{"total":14,"named":13},"Float":{"total":89,"named":79},"FloatArray":{"total":4,"named":3},"Int":{"total":1259,"named":1153},"Int64":{"total":33,"named":0},"Int64Array":{"total":4,"named":0},"IntArray":{"total":156,"named":64},"String16":{"total":1,"named":1},"String32":{"total":2,"named":1},"String64":{"total":54,"named":40},"String64Array":{"total":5,"named":4},"Struct":{"total":874,"named":856},"UInt":{"total":97,"named":6},"UInt64":{"total":6,"named":1},"UInt64Array":{"total":4,"named":3},"UIntArray":{"total":33,"named":30},"Vector3":{"total":26,"named":21},"WString16":{"total":2,"named":0},"WString16Array":{"total":2,"named":2}},"by_method":{"exp":363,"placement":3686,"placement-near":2616,"recovered:single":18,"recovered:single+order":16,"recovered:struct+member":4027,"reference":194,"sibling":144,"string:ainb":1165,"string:aoc":55,"string:asb":1,"string:banc":540,"string:flow":2265,"string:other":1,"string:pack":337,"string:param":193,"string:rsdb":6,"string:text":22,"struct":4189}}, +"counts":{"total":26670,"named":19854,"by_type":{"Binary":{"total":11,"named":2},"BinaryArray":{"total":2,"named":2},"Bool":{"total":11308,"named":10097},"Bool64bitKey":{"total":11657,"named":6496},"BoolArray":{"total":13,"named":7},"BoolExp":{"total":884,"named":866},"Enum":{"total":130,"named":107},"EnumArray":{"total":14,"named":13},"Float":{"total":89,"named":79},"FloatArray":{"total":4,"named":3},"Int":{"total":1259,"named":1153},"Int64":{"total":33,"named":0},"Int64Array":{"total":4,"named":0},"IntArray":{"total":156,"named":64},"String16":{"total":1,"named":1},"String32":{"total":2,"named":1},"String64":{"total":54,"named":40},"String64Array":{"total":5,"named":4},"Struct":{"total":874,"named":856},"UInt":{"total":97,"named":6},"UInt64":{"total":6,"named":1},"UInt64Array":{"total":4,"named":3},"UIntArray":{"total":33,"named":30},"Vector3":{"total":26,"named":21},"WString16":{"total":2,"named":0},"WString16Array":{"total":2,"named":2}},"by_method":{"exp":363,"placement":3686,"placement-near":2616,"recovered:single":18,"recovered:single+order":16,"recovered:struct+member":4027,"reference":194,"sibling":144,"string:ainb":1165,"string:aoc":55,"string:asb":1,"string:banc":540,"string:flow":2265,"string:other":1,"string:pack":337,"string:param":193,"string:rsdb":6,"string:text":22,"struct":4205}}, "concepts":[{"id":"dungeon_boss_defeated","status":"VERIFIED","confidence":"medium","flags":["0xc866bdaa","0xe4e3fdb8","0x52c59ec3","0xe46a9e97","0x4c96eb50","0xa386fb13","0x4fe914e3","0x92cb86bb","0x0c3743b0","0xe84b960e","0xee850ad3","0x1da458d0","0x725379e3","0xf6bbb871","0x88461890","0xb4396bb4","0x76eb9d9e","0xc9175b2a","0xe349f29f","0x6d834709"],"missing":[]},{"id":"dungeon_reward_stones","status":"VERIFIED","confidence":"high","flags":["0x7d776b61","0x1002b466","0x5bca02a6","0xdc8d6e41","0x93064625","0x75b83388"],"missing":[]},{"id":"dungeon_reward_medallions","status":"VERIFIED","confidence":"high","flags":["0xa9632cca","0xeea87aec","0x560a64af","0x7a91dbd5","0x19189e9d","0x51c6ab41","0xacf493ff","0x8faedf45","0x6148ad2b","0xe98fb9f3","0x606c3207"],"missing":[]},{"id":"small_key_counts","status":"VERIFIED","confidence":"high","flags":["0x0914ba07","0x3fdbc3d0","0x1470a816","0x90237092","0x1df11487","0x877bdcee","0x5edda9e3","0x79eeec8e","0x7dd79d10","0xfa5d133d","0xea9786f5","0xfbfd2910","0x3a28b6a4","0xa04bfd48"],"missing":[]},{"id":"boss_keys","status":"VERIFIED","confidence":"high","flags":["0xf6995cee","0xfaabc084","0x656bd5ee","0x427333a0","0xb72d73df","0x79daf80a","0xc33c66cf","0x1984c03f","0x9402715c","0x275f4512","0x6d155841","0x2fd59293","0x95fbcb7c","0x6d0fea11"],"missing":[]},{"id":"dungeon_maps","status":"VERIFIED","confidence":"high","flags":["0x89787395","0xa52c3a19","0xfcadd210","0xe704f9b4","0x5b3ac0ba","0x4a4402ab","0xf6177b93","0xb85002ba","0x77c47ec9","0x322f2a94","0x4b36041e","0x9bbc0c4a","0xbcaad6ce","0xb3b65c1a"],"missing":[]},{"id":"dungeon_compasses","status":"VERIFIED","confidence":"high","flags":["0x06c51ff2","0x8b93edf9","0x9a2218db","0xf240eeb2","0x0aa068b6","0x2e82c8fe","0x1e2feec5","0x9bd1181c","0x9d6efaac","0xea1846e6","0x3d9a2750","0xc4d4734e","0x5eb80679","0x874493ce"],"missing":[]},{"id":"songs_known","status":"VERIFIED","confidence":"high","flags":["0x01c20002","0xb492ac33","0xd3f8bfcc","0x165dd1ad","0x03b3450e","0x2b39dd4f","0xdc0a0b54","0x49041ab9","0x3fa63986","0x802a36a8","0xc2fb95f4","0xd6320ba4","0x5e86fb4d"],"missing":[]},{"id":"medallions","status":"VERIFIED","confidence":"high","flags":["0xfcd8d653","0x103a0dc7","0xcf64e780","0x12d63ac6","0xe269df38","0x9026c187"],"missing":[]},{"id":"medallion_stock","status":"VERIFIED","confidence":"medium","flags":["0x692d57cb","0x5ce254a6","0x0151a68f","0x204d2063","0x0c7a5fd0","0x235c7d9a"],"missing":[]},{"id":"stones","status":"VERIFIED","confidence":"high","flags":["0x110b83ec","0x8908d6ad","0xeec383f5"],"missing":[]},{"id":"stone_stock","status":"VERIFIED","confidence":"medium","flags":["0xcbd1e58c","0x7d69ad47","0xb8e3bf45"],"missing":[]},{"id":"door_of_time","status":"VERIFIED","confidence":"high","flags":["0x378913ca","0x5f3ee76a","0xe59ca50f","0x4da23816","0xb2f32349","0xc946f350","0xb85ad172","0xb4e83eaf","0xff51775f","0x3895bf21","0xecef2d19"],"missing":[]},{"id":"forest_openness","status":"GUESS","confidence":"low","flags":["0x3372689b","0x1204c6cc","0x7d776b61","0xdc8d6e41","0x98ca7aab"],"missing":[]},{"id":"gate_openness","status":"GUESS","confidence":"low","flags":["0x19898d14","0xde3d7168","0x8d01c252","0x0d333dba","0x8f895a5c","0x223a2987","0x673fc08a","0x1a9e9201","0x19b25999"],"missing":[]},{"id":"bottle_contents","status":"VERIFIED","confidence":"medium","flags":["0xd8ffafd1","0x75abc14b","0xea0729fe","0x53db16a6","0xb46a0394","0x170b5df2","0x03463ab6","0xf2001cfd","0xcf2d3db4","0x124c4d3a","0xf1232980","0x21fe9ffa","0x1106b082","0xd53ce3a7","0xfca29a04","0x893216a1","0x5324f9d3","0xc92b16be","0x3f776fd3","0x301f7bb5"],"missing":[]},{"id":"trade_quest_steps","status":"VERIFIED","confidence":"high","flags":["0xf19393b5","0x44ab1487","0x14909166","0xec9c3136","0xe82e6413","0xfb4442de","0xcbd7852a","0xb75acaad","0x888d5059","0x645a8175","0xd8f1521e","0x8e02d1ca","0xb7bdd577","0x8b54e680","0x6be5c3b0","0x24596e8e","0xb6ca6093","0x07f10aaf","0x0165e7ca","0x51d89ef0","0x07de3e6f","0x58c9bc78","0xa862d276","0x2815c82a","0x897cf7eb","0x919ea324","0x5c41a6b1","0xded8e8d3","0x26a2e01c","0xf4d5d3b9"],"missing":[]},{"id":"keys_in_minigames","status":"GUESS","confidence":"low","flags":["0xe45fac21"],"missing":[]}], "flags":[ {"hash":"0x63696a32","name":"CaptionData.ScreenShot","how":"recovered:struct+member","type":"Binary","default":40960,"reset":0,"save":2}, @@ -8949,6 +8949,15 @@ {"hash":"0x21985b09","name":"IsGet.Item_Quiver_Large","how":"struct","type":"Bool","default":false,"reset":8,"save":0}, {"hash":"0x9d872202","name":"IsGet.Item_Quiver_Medium","how":"struct","type":"Bool","default":false,"reset":8,"save":0}, {"hash":"0x0a550531","name":"IsGet.Item_Quiver_Small","how":"string:flow","type":"Bool","default":false,"reset":8,"save":0}, +{"hash":"0x2299468c","name":"IsGet.Item_Ring_Forest","how":"struct","type":"Bool","default":false,"reset":8,"save":0}, +{"hash":"0x56844297","name":"IsGet.Item_Ring_Hideout","how":"struct","type":"Bool","default":false,"reset":8,"save":0}, +{"hash":"0x223b086e","name":"IsGet.Item_Ring_Fire","how":"struct","type":"Bool","default":false,"reset":8,"save":0}, +{"hash":"0xd8db874b","name":"IsGet.Item_Ring_Water","how":"struct","type":"Bool","default":false,"reset":8,"save":0}, +{"hash":"0x92d9860a","name":"IsGet.Item_Ring_Shadow","how":"struct","type":"Bool","default":false,"reset":8,"save":0}, +{"hash":"0xb28490ba","name":"IsGet.Item_Ring_Spirit","how":"struct","type":"Bool","default":false,"reset":8,"save":0}, +{"hash":"0xd5e3c18d","name":"IsGet.Item_Ring_Well","how":"struct","type":"Bool","default":false,"reset":8,"save":0}, +{"hash":"0x5f62ae19","name":"IsGet.Item_Ring_GTG","how":"struct","type":"Bool","default":false,"reset":8,"save":0}, +{"hash":"0x685bed59","name":"IsGet.Item_Ring_Ganon","how":"struct","type":"Bool","default":false,"reset":8,"save":0}, {"hash":"0xccc1909a","name":"IsGet.Item_Scale_Gold","how":"struct","type":"Bool","default":false,"reset":8,"save":0}, {"hash":"0x1208fb3e","name":"IsGet.Item_Scale_Silver","how":"struct","type":"Bool","default":false,"reset":8,"save":0}, {"hash":"0xcfbb16f6","name":"IsGet.Item_ScrubBusinessSeed","how":"string:flow","type":"Bool","default":false,"reset":8,"save":0}, @@ -10770,6 +10779,15 @@ {"hash":"0xbb11d937","name":"OptionData.IsUseGyro","how":"recovered:struct+member","type":"Bool","default":true,"reset":4,"save":1}, {"hash":"0xff5fe801","name":"OptionData.VoiceSubtitle","how":"struct","type":"Bool","default":true,"reset":4,"save":1}, {"hash":"0xa451159b","name":"OptionData.VoiceSubtitleSpeakerName","how":"recovered:struct+member","type":"Bool","default":false,"reset":4,"save":1}, +{"hash":"0x2cffcc4f","name":"OOTRR_KeyRing.ForestTemple","how":"struct","type":"Bool","default":false,"reset":8,"save":0}, +{"hash":"0x22c11c3d","name":"OOTRR_KeyRing.GerudoFortress","how":"struct","type":"Bool","default":false,"reset":8,"save":0}, +{"hash":"0x4e79f9b5","name":"OOTRR_KeyRing.FireTemple","how":"struct","type":"Bool","default":false,"reset":8,"save":0}, +{"hash":"0xeba9f19f","name":"OOTRR_KeyRing.WaterTemple","how":"struct","type":"Bool","default":false,"reset":8,"save":0}, +{"hash":"0xc8d7d030","name":"OOTRR_KeyRing.ShadowTemple","how":"struct","type":"Bool","default":false,"reset":8,"save":0}, +{"hash":"0x64576046","name":"OOTRR_KeyRing.SpiritTemple","how":"struct","type":"Bool","default":false,"reset":8,"save":0}, +{"hash":"0x0607308e","name":"OOTRR_KeyRing.BottomOfTheWell","how":"struct","type":"Bool","default":false,"reset":8,"save":0}, +{"hash":"0x26517f00","name":"OOTRR_KeyRing.GerudoTrainingGround","how":"struct","type":"Bool","default":false,"reset":8,"save":0}, +{"hash":"0x97150d07","name":"OOTRR_KeyRing.InsideGanonCastle","how":"struct","type":"Bool","default":false,"reset":8,"save":0}, {"hash":"0xc666d018","name":"PhantomGanonPaintings_TemporaryDelete","how":"string:flow","type":"Bool","default":false,"reset":9,"save":-1}, {"hash":"0xa1d6d31f","name":"Pierre_First","how":"string:flow","type":"Bool","default":false,"reset":8,"save":0}, {"hash":"0xc6767bd7","name":"Pierre_KeepAway","how":"string:flow","type":"Bool","default":false,"reset":8,"save":0}, diff --git a/data/logic/settings.json b/data/logic/settings.json index 8e52f940..f5fb210c 100644 --- a/data/logic/settings.json +++ b/data/logic/settings.json @@ -135,6 +135,16 @@ "logic_jabu_boss_hover": false, "logic_jabu_near_boss_explosives": false, "logic_jabu_near_boss_ranged": false, + "key_rings": false, + "key_ring_forest_temple": false, + "key_ring_fire_temple": false, + "key_ring_water_temple": false, + "key_ring_shadow_temple": false, + "key_ring_spirit_temple": false, + "key_ring_bottom_of_the_well": false, + "key_ring_gerudo_training_ground": false, + "key_ring_ganons_castle": false, + "hideout_key_rings": false, "logic_kakariko_rooftop_gs": false, "logic_kakariko_tower_gs": false, "logic_king_zora_skip": false, @@ -216,6 +226,7 @@ "shuffle_expensive_merchants": false, "shuffle_ganon_bosskey": "vanilla", "shuffle_gerudo_fortress_heart_piece": "vanilla", + "shuffle_hideoutkeys": "vanilla", "shuffle_hideout_entrances": false, "shuffle_individual_ocarina_notes": false, "shuffle_interior_entrances": false, diff --git a/data/pickup_packs.json b/data/pickup_packs.json index f09217f9..b86e2936 100644 --- a/data/pickup_packs.json +++ b/data/pickup_packs.json @@ -1185,6 +1185,366 @@ "status": "built", "identity": "Item_Arrow_Fire", "notes": "The shipped Obj_Arrow_Fire does not stay taken on the ground; this pack takes the pickup base. Built and read back in the placement sweep. Not yet tried in game." + }, + { + "group": "D", + "item": "Item_Ring_Forest", + "pack": "Item_Ring_Forest", + "args": [ + "--name", + "Item_Ring_Forest", + "--source", + "Item_Dungeon_SmallKey", + "--pouch-from", + "Item_Medal_Forest", + "--identity", + "Item_Ring_Forest", + "--ring", + "Item_Ring_Forest" + ], + "status": "built", + "identity": "Item_Ring_Forest", + "notes": "Key ring pickup. The small key model is kept, but the pouch and get event use the plain key-item template so the ring is saved and credited as itself instead of a small key." + }, + { + "group": "D", + "item": "Item_Ring_Hideout", + "pack": "Item_Ring_Hideout", + "args": [ + "--name", + "Item_Ring_Hideout", + "--source", + "Item_Dungeon_SmallKey", + "--pouch-from", + "Item_Medal_Forest", + "--identity", + "Item_Ring_Hideout", + "--ring", + "Item_Ring_Hideout" + ], + "status": "built", + "identity": "Item_Ring_Hideout", + "notes": "Hideout key ring pickup. The small key model is kept, but the pouch and get event use the plain key-item template so the manually enabled ring is saved and credited as itself." + }, + { + "group": "D", + "item": "Item_Ring_Fire", + "pack": "Item_Ring_Fire", + "args": [ + "--name", + "Item_Ring_Fire", + "--source", + "Item_Dungeon_SmallKey", + "--pouch-from", + "Item_Medal_Forest", + "--identity", + "Item_Ring_Fire", + "--ring", + "Item_Ring_Fire" + ], + "status": "built", + "identity": "Item_Ring_Fire", + "notes": "Key ring pickup. The small key model is kept, but the pouch and get event use the plain key-item template so the ring is saved and credited as itself instead of a small key." + }, + { + "group": "D", + "item": "Item_Ring_Water", + "pack": "Item_Ring_Water", + "args": [ + "--name", + "Item_Ring_Water", + "--source", + "Item_Dungeon_SmallKey", + "--pouch-from", + "Item_Medal_Forest", + "--identity", + "Item_Ring_Water", + "--ring", + "Item_Ring_Water" + ], + "status": "built", + "identity": "Item_Ring_Water", + "notes": "Key ring pickup. The small key model is kept, but the pouch and get event use the plain key-item template so the ring is saved and credited as itself instead of a small key." + }, + { + "group": "D", + "item": "Item_Ring_Shadow", + "pack": "Item_Ring_Shadow", + "args": [ + "--name", + "Item_Ring_Shadow", + "--source", + "Item_Dungeon_SmallKey", + "--pouch-from", + "Item_Medal_Forest", + "--identity", + "Item_Ring_Shadow", + "--ring", + "Item_Ring_Shadow" + ], + "status": "built", + "identity": "Item_Ring_Shadow", + "notes": "Key ring pickup. The small key model is kept, but the pouch and get event use the plain key-item template so the ring is saved and credited as itself instead of a small key." + }, + { + "group": "D", + "item": "Item_Ring_Spirit", + "pack": "Item_Ring_Spirit", + "args": [ + "--name", + "Item_Ring_Spirit", + "--source", + "Item_Dungeon_SmallKey", + "--pouch-from", + "Item_Medal_Forest", + "--identity", + "Item_Ring_Spirit", + "--ring", + "Item_Ring_Spirit" + ], + "status": "built", + "identity": "Item_Ring_Spirit", + "notes": "Key ring pickup. The small key model is kept, but the pouch and get event use the plain key-item template so the ring is saved and credited as itself instead of a small key." + }, + { + "group": "D", + "item": "Item_Ring_Well", + "pack": "Item_Ring_Well", + "args": [ + "--name", + "Item_Ring_Well", + "--source", + "Item_Dungeon_SmallKey", + "--pouch-from", + "Item_Medal_Forest", + "--identity", + "Item_Ring_Well", + "--ring", + "Item_Ring_Well" + ], + "status": "built", + "identity": "Item_Ring_Well", + "notes": "Key ring pickup. The small key model is kept, but the pouch and get event use the plain key-item template so the ring is saved and credited as itself instead of a small key." + }, + { + "group": "D", + "item": "Item_Ring_GTG", + "pack": "Item_Ring_GTG", + "args": [ + "--name", + "Item_Ring_GTG", + "--source", + "Item_Dungeon_SmallKey", + "--pouch-from", + "Item_Medal_Forest", + "--identity", + "Item_Ring_GTG", + "--ring", + "Item_Ring_GTG" + ], + "status": "built", + "identity": "Item_Ring_GTG", + "notes": "Key ring pickup. The small key model is kept, but the pouch and get event use the plain key-item template so the ring is saved and credited as itself instead of a small key." + }, + { + "group": "D", + "item": "Item_Ring_Ganon", + "pack": "Item_Ring_Ganon", + "args": [ + "--name", + "Item_Ring_Ganon", + "--source", + "Item_Dungeon_SmallKey", + "--pouch-from", + "Item_Medal_Forest", + "--identity", + "Item_Ring_Ganon", + "--ring", + "Item_Ring_Ganon" + ], + "status": "built", + "identity": "Item_Ring_Ganon", + "notes": "Key ring pickup. The small key model is kept, but the pouch and get event use the plain key-item template so the ring is saved and credited as itself instead of a small key." + }, + { + "group": "D", + "item": "Item_RingDrop_Forest", + "pack": "Obj_RingDrop_Forest", + "args": [ + "--name", + "Obj_RingDrop_Forest", + "--source", + "Item_Dungeon_SmallKey", + "--pouch-from", + "Item_Medal_Forest", + "--identity", + "Item_Ring_Forest", + "--drop-ring", + "Item_Ring_Forest" + ], + "status": "built", + "identity": "Item_Ring_Forest", + "notes": "Drop-form key ring. The small key model, saved identity and get event stay the same; the pickup body is the world drop so pots and other holders give a falling, touchable item." + }, + { + "group": "D", + "item": "Item_RingDrop_Hideout", + "pack": "Obj_RingDrop_Hideout", + "args": [ + "--name", + "Obj_RingDrop_Hideout", + "--source", + "Item_Dungeon_SmallKey", + "--pouch-from", + "Item_Medal_Forest", + "--identity", + "Item_Ring_Hideout", + "--drop-ring", + "Item_Ring_Hideout" + ], + "status": "built", + "identity": "Item_Ring_Hideout", + "notes": "Drop-form Hideout key ring. The small key model, saved identity and get event stay the same; the pickup body is the world drop so pots and the four native guard spots give a falling, touchable item." + }, + { + "group": "D", + "item": "Item_RingDrop_Fire", + "pack": "Obj_RingDrop_Fire", + "args": [ + "--name", + "Obj_RingDrop_Fire", + "--source", + "Item_Dungeon_SmallKey", + "--pouch-from", + "Item_Medal_Forest", + "--identity", + "Item_Ring_Fire", + "--drop-ring", + "Item_Ring_Fire" + ], + "status": "built", + "identity": "Item_Ring_Fire", + "notes": "Drop-form key ring. The small key model, saved identity and get event stay the same; the pickup body is the world drop so pots and other holders give a falling, touchable item." + }, + { + "group": "D", + "item": "Item_RingDrop_Water", + "pack": "Obj_RingDrop_Water", + "args": [ + "--name", + "Obj_RingDrop_Water", + "--source", + "Item_Dungeon_SmallKey", + "--pouch-from", + "Item_Medal_Forest", + "--identity", + "Item_Ring_Water", + "--drop-ring", + "Item_Ring_Water" + ], + "status": "built", + "identity": "Item_Ring_Water", + "notes": "Drop-form key ring. The small key model, saved identity and get event stay the same; the pickup body is the world drop so pots and other holders give a falling, touchable item." + }, + { + "group": "D", + "item": "Item_RingDrop_Shadow", + "pack": "Obj_RingDrop_Shadow", + "args": [ + "--name", + "Obj_RingDrop_Shadow", + "--source", + "Item_Dungeon_SmallKey", + "--pouch-from", + "Item_Medal_Forest", + "--identity", + "Item_Ring_Shadow", + "--drop-ring", + "Item_Ring_Shadow" + ], + "status": "built", + "identity": "Item_Ring_Shadow", + "notes": "Drop-form key ring. The small key model, saved identity and get event stay the same; the pickup body is the world drop so pots and other holders give a falling, touchable item." + }, + { + "group": "D", + "item": "Item_RingDrop_Spirit", + "pack": "Obj_RingDrop_Spirit", + "args": [ + "--name", + "Obj_RingDrop_Spirit", + "--source", + "Item_Dungeon_SmallKey", + "--pouch-from", + "Item_Medal_Forest", + "--identity", + "Item_Ring_Spirit", + "--drop-ring", + "Item_Ring_Spirit" + ], + "status": "built", + "identity": "Item_Ring_Spirit", + "notes": "Drop-form key ring. The small key model, saved identity and get event stay the same; the pickup body is the world drop so pots and other holders give a falling, touchable item." + }, + { + "group": "D", + "item": "Item_RingDrop_Well", + "pack": "Obj_RingDrop_Well", + "args": [ + "--name", + "Obj_RingDrop_Well", + "--source", + "Item_Dungeon_SmallKey", + "--pouch-from", + "Item_Medal_Forest", + "--identity", + "Item_Ring_Well", + "--drop-ring", + "Item_Ring_Well" + ], + "status": "built", + "identity": "Item_Ring_Well", + "notes": "Drop-form key ring. The small key model, saved identity and get event stay the same; the pickup body is the world drop so pots and other holders give a falling, touchable item." + }, + { + "group": "D", + "item": "Item_RingDrop_GTG", + "pack": "Obj_RingDrop_GTG", + "args": [ + "--name", + "Obj_RingDrop_GTG", + "--source", + "Item_Dungeon_SmallKey", + "--pouch-from", + "Item_Medal_Forest", + "--identity", + "Item_Ring_GTG", + "--drop-ring", + "Item_Ring_GTG" + ], + "status": "built", + "identity": "Item_Ring_GTG", + "notes": "Drop-form key ring. The small key model, saved identity and get event stay the same; the pickup body is the world drop so pots and other holders give a falling, touchable item." + }, + { + "group": "D", + "item": "Item_RingDrop_Ganon", + "pack": "Obj_RingDrop_Ganon", + "args": [ + "--name", + "Obj_RingDrop_Ganon", + "--source", + "Item_Dungeon_SmallKey", + "--pouch-from", + "Item_Medal_Forest", + "--identity", + "Item_Ring_Ganon", + "--drop-ring", + "Item_Ring_Ganon" + ], + "status": "built", + "identity": "Item_Ring_Ganon", + "notes": "Drop-form key ring. The small key model, saved identity and get event stay the same; the pickup body is the world drop so pots and other holders give a falling, touchable item." } ] } diff --git a/randomizer/cli/src/main.rs b/randomizer/cli/src/main.rs index c116f981..cdce2593 100644 --- a/randomizer/cli/src/main.rs +++ b/randomizer/cli/src/main.rs @@ -117,8 +117,8 @@ const USAGE: &str = "usage: ootrr pots-persist ootrr ap-test-mod ... ootrr ap-flag [on|off] - ootrr pack-add [--name ] [--press] [--heap N] [--host eden|hookshot|longshot|nx2navi] [--base ] [--rst-from ] [--place ]... [--tag ]... [--ammo] [--magic] [--own] [--model-from ] [--dry] - ootrr pack-kit [--name ] [--heap N] [--host eden|hookshot|longshot|nx2navi] [--base ] [--rst-from ] [--drop ]... [--model-from ] [--dry] + ootrr pack-add [--name ] [--press] [--heap N] [--host eden|hookshot|longshot|nx2navi] [--base ] [--rst-from ] [--place ]... [--tag ]... [--ammo] [--magic] [--own] [--model-from ] [--source ] [--identity ] [--dry] + ootrr pack-kit [--name ] [--heap N] [--host eden|hookshot|longshot|nx2navi] [--base ] [--rst-from ] [--drop ]... [--model-from ] [--identity ] [--dry] ootrr flags-build ootrr flags-lookup ... ootrr flags-check diff --git a/randomizer/cli/src/pack_add_cmd.rs b/randomizer/cli/src/pack_add_cmd.rs index b20d1914..2c1a1d50 100644 --- a/randomizer/cli/src/pack_add_cmd.rs +++ b/randomizer/cli/src/pack_add_cmd.rs @@ -11,7 +11,7 @@ fn arg<'a>(a: &'a [String], i: usize, what: &'static str) -> Res<&'a str> { pub fn parse(a: &[String]) -> Res<(Spec, Opts, Layers)> { let item: &str = arg(a, 3, "missing Item_Actor")?; - let mut s: Spec = Spec { item: item.to_string(), name: default_name(item), style: Style::Touch, heap: None }; + let mut s: Spec = Spec { item: item.to_string(), name: default_name(item), style: Style::Touch, heap: None, source: None, identity: None }; let mut o: Opts = Opts { host: Host::Eden, base: None, rst_from: None, places: Vec::new(), dry: false }; let mut l: Layers = Layers::default(); let mut i: usize = 4; @@ -52,6 +52,14 @@ pub fn parse(a: &[String]) -> Res<(Spec, Opts, Layers)> { l.model = Some(arg(a, i + 1, "missing model donor actor")?.to_string()); 2 } + "--source" => { + s.source = Some(arg(a, i + 1, "missing template actor")?.to_string()); + 2 + } + "--identity" => { + s.identity = Some(arg(a, i + 1, "missing pouch identity actor")?.to_string()); + 2 + } "--heap" => { let v: &str = arg(a, i + 1, "missing heap size")?; s.heap = Some(v.parse().map_err(|_| E::Msg(format!("{v} is not a heap size")))?); @@ -107,7 +115,7 @@ mod tests { #[test] fn the_defaults_are_a_touch_pickup_named_after_the_item() { let (s, o, l): (Spec, Opts, Layers) = parse(&args(&["r", "l", "m", "Item_Hookshot"])).unwrap(); - assert_eq!(s, Spec { item: "Item_Hookshot".to_string(), name: "Obj_Hookshot".to_string(), style: Style::Touch, heap: None }); + assert_eq!(s, Spec { item: "Item_Hookshot".to_string(), name: "Obj_Hookshot".to_string(), style: Style::Touch, heap: None, source: None, identity: None }); assert_eq!(l, Layers::default()); assert!(l.plain()); assert_eq!(o.host, Host::Eden); @@ -117,12 +125,14 @@ mod tests { #[test] fn every_option_is_read() { let a: Vec = args(&[ - "r", "l", "m", "Item_Hookshot", "--press", "--name", "Obj_Hook", "--heap", "200000", "--host", "hookshot", "--place", "11219803099333988363", "--place", "7", "--base", "x/romfs", "--rst-from", "t.zs", "--dry", + "r", "l", "m", "Item_Hookshot", "--press", "--name", "Obj_Hook", "--heap", "200000", "--host", "hookshot", "--place", "11219803099333988363", "--place", "7", "--base", "x/romfs", "--rst-from", "t.zs", "--source", "Item_Dungeon_SmallKey", "--identity", "Item_Ring_Forest", "--dry", ]); let (s, o, l): (Spec, Opts, Layers) = parse(&a).unwrap(); assert!(l.plain()); assert_eq!(s.name, "Obj_Hook"); assert_eq!(s.style, Style::Press); + assert_eq!(s.source(), "Item_Dungeon_SmallKey"); + assert_eq!(s.identity_override(), Some("Item_Ring_Forest")); assert_eq!(s.heap, Some(200000)); assert_eq!(o.host, Host::Hookshot); assert_eq!(o.places, vec![11219803099333988363, 7]); @@ -136,6 +146,8 @@ mod tests { assert!(parse(&args(&["r", "l", "m", "Item_Hookshot", "--host", "wii"])).is_err()); assert!(parse(&args(&["r", "l", "m", "Item_Hookshot", "--what"])).is_err()); assert!(parse(&args(&["r", "l", "m", "Item_Hookshot", "--tag"])).is_err()); + assert!(parse(&args(&["r", "l", "m", "Item_Hookshot", "--source"])).is_err()); + assert!(parse(&args(&["r", "l", "m", "Item_Hookshot", "--identity"])).is_err()); } #[test] @@ -143,10 +155,10 @@ mod tests { let a: Vec = args(&["r", "l", "m", "Item_Bottle_Letter", "--name", "Obj_Bottle_LetterLand", "--tag", "LetterBottle", "--tag", "LetterBottle"]); let (s, _, l): (Spec, Opts, Layers) = parse(&a).unwrap(); assert_eq!(s.name, "Obj_Bottle_LetterLand"); - assert_eq!(l, Layers { tags: vec!["LetterBottle".to_string()], ammo: false, magic: false, model: None, spin: false, lift: 0, own: false, pose: None }); + assert_eq!(l, Layers { tags: vec!["LetterBottle".to_string()], ammo: false, magic: false, model: None, pouch_from: None, ring: None, drop_ring: false, spin: false, lift: 0, own: false, pose: None }); let (_, _, l): (Spec, Opts, Layers) = parse(&args(&["r", "l", "m", "Item_Range_Bow", "--ammo"])).unwrap(); - assert_eq!(l, Layers { tags: Vec::new(), ammo: true, magic: false, model: None, spin: false, lift: 0, own: false, pose: None }); + assert_eq!(l, Layers { tags: Vec::new(), ammo: true, magic: false, model: None, pouch_from: None, ring: None, drop_ring: false, spin: false, lift: 0, own: false, pose: None }); let (_, _, l): (Spec, Opts, Layers) = parse(&args(&["r", "l", "m", "Item_FairyBless_MP", "--magic"])).unwrap(); - assert_eq!(l, Layers { tags: Vec::new(), ammo: false, magic: true, model: None, spin: false, lift: 0, own: false, pose: None }); + assert_eq!(l, Layers { tags: Vec::new(), ammo: false, magic: true, model: None, pouch_from: None, ring: None, drop_ring: false, spin: false, lift: 0, own: false, pose: None }); } } diff --git a/randomizer/cli/src/pack_kit_cmd.rs b/randomizer/cli/src/pack_kit_cmd.rs index a0360f43..5a2861c7 100644 --- a/randomizer/cli/src/pack_kit_cmd.rs +++ b/randomizer/cli/src/pack_kit_cmd.rs @@ -12,7 +12,7 @@ fn arg<'a>(a: &'a [String], i: usize, what: &'static str) -> Res<&'a str> { pub fn parse(a: &[String]) -> Res<(Spec, Opts, Vec, Layers)> { let item: &str = arg(a, 3, "missing Item_Actor or Obj_Actor")?; - let mut s: Spec = Spec { item: item.to_string(), name: default_kit(item), style: Style::Touch, heap: None }; + let mut s: Spec = Spec { item: item.to_string(), name: default_kit(item), style: Style::Touch, heap: None, source: None, identity: None }; let mut o: Opts = Opts { host: Host::Eden, base: None, rst_from: None, places: Vec::new(), dry: false }; let mut drops: Vec = Vec::new(); let mut l: Layers = Layers::default(); @@ -49,6 +49,10 @@ pub fn parse(a: &[String]) -> Res<(Spec, Opts, Vec, Layers)> { l.model = Some(arg(a, i + 1, "missing model donor actor")?.to_string()); 2 } + "--identity" => { + s.identity = Some(arg(a, i + 1, "missing pouch identity actor")?.to_string()); + 2 + } "--drop" => { let v: &str = arg(a, i + 1, "missing skulltula hash")?; drops.push(v.parse().map_err(|_| E::Msg(format!("{v} is not an actor hash")))?); @@ -95,10 +99,11 @@ mod tests { #[test] fn drops_and_the_shared_options_are_read() { - let a: Vec = args(&["r", "l", "m", "Item_Hookshot", "--drop", "2504273934093629549", "--drop", "7", "--name", "Obj_Hook_GS", "--heap", "200000", "--host", "hookshot", "--base", "x/romfs", "--rst-from", "t.zs", "--dry"]); + let a: Vec = args(&["r", "l", "m", "Item_Hookshot", "--drop", "2504273934093629549", "--drop", "7", "--name", "Obj_Hook_GS", "--heap", "200000", "--host", "hookshot", "--base", "x/romfs", "--rst-from", "t.zs", "--identity", "Item_Ring_Forest", "--dry"]); let (s, o, drops, _): (Spec, Opts, Vec, Layers) = parse(&a).unwrap(); assert_eq!(drops, vec![2504273934093629549, 7]); assert_eq!(s.name, "Obj_Hook_GS"); + assert_eq!(s.identity_override(), Some("Item_Ring_Forest")); assert_eq!(s.heap, Some(200000)); assert_eq!(o.host, Host::Hookshot); assert!(o.dry && o.base.is_some() && o.rst_from.is_some()); diff --git a/randomizer/core/src/ainb.rs b/randomizer/core/src/ainb.rs index c567b47a..0c2bad23 100644 --- a/randomizer/core/src/ainb.rs +++ b/randomizer/core/src/ainb.rs @@ -20,6 +20,7 @@ use tab::{INSZ, OUTSZ, PSZ}; pub use param::{Param, Plug}; pub use audit::audit; pub use graft::{graft, root, set_root}; +pub use node::{new_node, In}; pub use pool::Pool; pub use view::Input; diff --git a/randomizer/core/src/dungeon_credit.rs b/randomizer/core/src/dungeon_credit.rs index c9797685..0aab13e5 100644 --- a/randomizer/core/src/dungeon_credit.rs +++ b/randomizer/core/src/dungeon_credit.rs @@ -3,7 +3,7 @@ use std::fmt::Write as W; use std::path::{Path as P, PathBuf as PB}; use crate::bfevfl::flow::NONE; -use crate::bfevfl::{Actor, Bf, Cont, Entry, Event, Flow, Kind, Val}; +use crate::bfevfl::{Actor, Bf, Case, Cont, Entry, Event, Flow, Kind, Val}; use crate::byml::{Byml, Node}; use crate::dungeon_text; use crate::error::{Error, Res}; @@ -43,6 +43,8 @@ pub const NATIVE: [&str; 4] = ["EventGetDungeonMap", "EventGetDungeonCompass", " pub const PLAIN: &str = "None"; pub const SMALL_NATIVE: [&str; 1] = ["EventGetDungeonSmallKey"]; pub const EVENT_PREFIX: &str = "OOTRR_Key_"; +pub const RING_EVENT_PREFIX: &str = "OOTRR_KeyRing_"; +const RING_ENTRY_PREFIX: &str = "Success_KeyRing_"; pub const KEY_DUNGEONS: [&str; 8] = [ "ForestTemple", "FireTemple", @@ -56,6 +58,7 @@ pub const KEY_DUNGEONS: [&str; 8] = [ pub const DROP: &str = "Drop__DropActor"; pub const HOLDER: &str = "GameDataActor"; const ADD: &str = "EventTriggerAddOrSubGameDataInt"; +const ASK_BOOL: &str = "EventQueryIsGameDataBool"; pub const SET: &str = "EventTriggerSetGameDataBool"; const ROOT_ENTRY: &str = "Success_"; const PREFIX: &str = "Success_Key_"; @@ -85,6 +88,7 @@ pub fn key_dungeon(name: &str) -> Option<&'static str> { "Spirit Temple" => Some("SpiritTemple"), "Bottom of the Well" => Some("BottomOfTheWell"), "Gerudo Training Ground" => Some("GerudoTrainingGround"), + "Thieves Hideout" => Some("GerudoFortress"), "Ganons Castle" => Some("InsideGanonCastle"), _ => None, } @@ -107,6 +111,18 @@ pub fn event_name(d: &str, size: Size) -> String { format!("OOTRR_Key_{d}_{tag}") } +pub fn ring_entry_name(d: &str) -> String { + format!("{RING_ENTRY_PREFIX}{d}") +} + +pub fn ring_event_name(d: &str, size: Size) -> String { + let tag: &str = match size { + Size::Small => "Small", + Size::Big => "Big", + }; + format!("{RING_EVENT_PREFIX}{d}_{tag}") +} + pub fn flag(d: &str, member: &str) -> String { format!("DungeonInfo.{d}.{member}") } @@ -163,6 +179,16 @@ pub fn add_int(name: String) -> Cont { } } +fn add_count(name: String, count: u32) -> Cont { + Cont { + items: vec![ + ("Index".to_string(), Val::Int(-1)), + ("GameDataName".to_string(), Val::Str(name)), + ("Value".to_string(), Val::Int(count as i32)), + ], + } +} + pub fn set_bool(name: String) -> Cont { Cont { items: vec![ @@ -319,6 +345,7 @@ pub fn sound(f: &Flow) -> Vec { fn same_but_actions(a: &Actor, b: &Actor) -> bool { let mut x: Actor = b.clone(); x.actions.truncate(a.actions.len()); + x.queries.truncate(a.queries.len()); x == *a && ADDED.contains(&b.name.as_str()) } @@ -362,6 +389,9 @@ pub fn audit(a: &Flow, b: &Flow) -> Vec { _ => false, }), Kind::Sub { flow, entry, .. } => flow.is_empty() && entry == ROOT_ENTRY, + Kind::Switch { actor, query, .. } => b.actors.get(*actor as usize).is_some_and(|x| { + x.name == HOLDER && x.queries.get(*query as usize).is_some_and(|q| q == ASK_BOOL) + }), _ => false, }; if !fine { @@ -374,7 +404,9 @@ pub fn audit(a: &Flow, b: &Flow) -> Vec { } } for y in &b.entries[a.entries.len()..] { - if !y.name.strip_prefix(PREFIX).is_some_and(|d| DUNGEONS.contains(&d)) { + let key: bool = y.name.strip_prefix(PREFIX).is_some_and(|d| DUNGEONS.contains(&d)); + let ring: bool = y.name.strip_prefix(RING_ENTRY_PREFIX).is_some_and(|d| crate::key_rings::by_folder_any(d).is_some()); + if !key && !ring { bad.push(format!("entry {} was added", y.name)); } } @@ -392,6 +424,67 @@ pub fn credit_keys(f: &mut Flow, dungeons: &[&str], big: bool) -> Res { Ok(n) } +fn give_ring(next: u16, actor: &str) -> Kind { + let c: Cont = Cont { + items: vec![ + ("ContentName".to_string(), Val::Str(actor.to_string())), + ("IsMiniGame".to_string(), Val::Bool(0)), + ], + }; + Kind::Sub { next, params: Some(c), flow: String::new(), entry: ROOT_ENTRY.to_string() } +} + + + + + + +pub fn ring_credit(f: &mut Flow, r: &'static crate::key_rings::Ring) -> Res<()> { + let name: String = ring_entry_name(r.folder); + if f.entries.iter().any(|e| e.name == name) { + return Ok(()); + } + let pad: u16 = f + .entries + .iter() + .find(|e| e.name == ROOT_ENTRY) + .map(|e| e.pad) + .ok_or(Error::Format("dungeon credit: the chest flow has no Success_ entry"))?; + let (a, add): (u16, u16) = action_slot(f, HOLDER, ADD)?; + let (_, set): (u16, u16) = action_slot(f, HOLDER, SET)?; + let (t, say): (u16, u16) = action_slot(f, TALKER, TALK)?; + let (qowner, query): (u16, u16) = crate::start_state::query_slot(f, HOLDER, ASK_BOOL)?; + let applied: String = crate::key_rings::applied_flag(r.folder); + + let given: u16 = push(f, Kind::Action { next: NONE, actor: t, act: say, params: Some(talk(crate::dungeon_text::message_id(r.folder))) })?; + let marked: u16 = push(f, Kind::Action { next: given, actor: a, act: set, params: Some(set_bool(applied.clone())) })?; + let once: u16 = push(f, Kind::Action { next: marked, actor: a, act: set, params: Some(set_bool(flag(r.folder, "IsGetSmallKeyOnce"))) })?; + let total: u16 = push(f, Kind::Action { next: once, actor: a, act: add, params: Some(add_count(flag(r.folder, "SmallKeyTotalNum"), r.count)) })?; + let num: u16 = push(f, Kind::Action { next: total, actor: a, act: add, params: Some(add_count(flag(r.folder, "SmallKeyNum"), r.count)) })?; + let params: Cont = Cont { items: vec![("GameDataName".to_string(), Val::Str(applied)), ("Index".to_string(), Val::Int(-1))] }; + let asked: u16 = push(f, Kind::Switch { + actor: qowner, + query, + cases: vec![Case { val: 0, ev: NONE }, Case { val: 1, ev: num }], + params: Some(params), + })?; + let sub: u16 = push(f, give_ring(asked, r.actor))?; + f.entries.push(Entry { name, subs: vec![sub], vars: Vec::new(), main: sub, pad }); + Ok(()) +} + + +pub fn credit_rings(f: &mut Flow, folders: &[&'static str]) -> Res<()> { + for folder in folders { + let r: &'static crate::key_rings::Ring = crate::key_rings::by_folder_any(folder).ok_or_else(|| Error::Msg(format!("{folder} has no key ring")))?; + ring_credit(f, r)?; + } + if let Some(m) = sound(f).first() { + return Err(Error::Msg(format!("dungeon credit: the chest flow is broken after the ring entries, {m}"))); + } + Ok(()) +} + pub fn sweep(y: &mut Byml, file: &str) -> Res { sweep_except(y, file, &BS::new()) } @@ -410,11 +503,19 @@ pub fn sweep_except(y: &mut Byml, file: &str, skip: &BS) -> Res { let Some(d) = a.get_mut("Dynamic") else { continue; }; - if text(d, DROP) != KEY || text(d, "GetEventName").starts_with(EVENT_PREFIX) { + let drop: &str = text(d, DROP); + let ring: Option<&'static crate::key_rings::Ring> = crate::key_rings::by_actor_any(drop); + if (drop != KEY && ring.is_none()) || text(d, "GetEventName").starts_with(EVENT_PREFIX) || text(d, "GetEventName").starts_with(RING_EVENT_PREFIX) { continue; } - let dungeon: &str = scene.ok_or_else(|| Error::Msg(format!("{file} has a chest with a small key but is not a dungeon scene this build knows")))?; - d.set("GetEventName", Node::Str(event_name(dungeon, size))); + let event: String = match ring { + Some(r) => ring_event_name(r.folder, size), + None => { + let dungeon: &str = scene.ok_or_else(|| Error::Msg(format!("{file} has a chest with a small key but is not a dungeon scene this build knows")))?; + event_name(dungeon, size) + } + }; + d.set("GetEventName", Node::Str(event)); n += 1; } Ok(n) @@ -431,7 +532,7 @@ pub fn stage_pouch(rf: &mut Romfs, roam: bool) -> Res { }) } -pub fn edit_flow(raw: &[u8], dungeons: &[&str], native: bool) -> Res<(Vec, usize)> { +pub fn edit_flow(raw: &[u8], dungeons: &[&str], rings: &[&'static str], native: bool) -> Res<(Vec, usize)> { let orig: Bf = Bf::parse(raw)?; let mut b: Bf = orig.clone(); let before: &Flow = orig.flows.first().ok_or(Error::Format("dungeon credit: the flow file holds no flow"))?; @@ -440,6 +541,7 @@ pub fn edit_flow(raw: &[u8], dungeons: &[&str], native: bool) -> Res<(Vec, u for d in dungeons { credit(f, d)?; } + credit_rings(f, rings)?; let bad: Vec = audit(before, f); if let Some(m) = bad.first() { return Err(Error::Msg(format!("dungeon credit: the edited flow fails its audit, {m} ({} problems)", bad.len()))); @@ -501,13 +603,19 @@ pub fn place(y: &mut Byml, hash: u64, d: &str) -> Option { edit_chest(y, hash, KEY, &event_name(d, size)) } -pub fn stage(rf: &mut Romfs, dungeons: &BS<&'static str>, counted: &BS<&str>) -> Res<(Vec, usize)> { +pub fn stage(rf: &mut Romfs, dungeons: &BS<&'static str>, rings: &[&'static str], counted: &BS<&str>) -> Res<(Vec, usize)> { let ds: Vec<&str> = dungeons.iter().copied().collect(); + let mut text_ds: Vec<&str> = ds.clone(); + for d in rings { + if !text_ds.contains(d) { + text_ds.push(d); + } + } let mut outs: Vec = Vec::new(); let mut skipped: usize = 0; for (path, native) in [(BIG_FLOW, true), (SMALL_FLOW, false)] { outs.push(rewrite(rf, path, |raw: &[u8]| { - let (b, n): (Vec, usize) = edit_flow(raw, &ds, native)?; + let (b, n): (Vec, usize) = edit_flow(raw, &ds, rings, native)?; skipped += n; Ok(b) })?); @@ -517,8 +625,9 @@ pub fn stage(rf: &mut Romfs, dungeons: &BS<&'static str>, counted: &BS<&str>) -> outs.push(rewrite(rf, table, |raw: &[u8]| { let mut y: Byml = Byml::parse(raw)?; for size in [Size::Small, Size::Big] { - let rows: Vec<(String, Option)> = + let mut rows: Vec<(String, Option)> = ds.iter().map(|d| (event_name(d, size), if analyzed { None } else { Some(entry_name(d)) })).collect(); + rows.extend(rings.iter().map(|d| (ring_event_name(d, size), if analyzed { None } else { Some(ring_entry_name(d)) }))); add_rows(&mut y, size.template(), &rows)?; } y.write() @@ -531,7 +640,7 @@ pub fn stage(rf: &mut Romfs, dungeons: &BS<&'static str>, counted: &BS<&str>) -> })?); for l in languages(rf)? { let english: bool = dungeon_text::is_english(&l); - outs.push(rewrite(rf, &l, |raw: &[u8]| dungeon_text::apply(raw, &ds, counted, english))?); + outs.push(rewrite(rf, &l, |raw: &[u8]| dungeon_text::apply(raw, &text_ds, counted, english))?); } Ok((outs, skipped)) } @@ -593,7 +702,7 @@ pub fn build(romfs: &P, load: &P, name: &str, plans: &[(u64, Option)], o } counted.insert(d); } - let (staged, skipped): (Vec, usize) = stage(&mut rf, &used, &counted)?; + let (staged, skipped): (Vec, usize) = stage(&mut rf, &used, &[], &counted)?; outs.extend(staged); let c: Committed = commit(&mut rf, load, name, &outs, o.rst_from.as_ref())?; let mut report: String = c.report; @@ -734,6 +843,64 @@ mod tests { assert!(audit(&small(), &f).is_empty()); } + #[test] + fn a_ring_chest_gives_the_ring_before_it_credits_and_the_guard_runs_on_false() { + let r: &'static crate::key_rings::Ring = crate::key_rings::by_folder("ForestTemple").unwrap(); + let mut f: Flow = small(); + ring_credit(&mut f, r).unwrap(); + assert!(audit(&small(), &f).is_empty()); + + let e: &Entry = &f.entries[1]; + assert_eq!((e.name.as_str(), e.subs.clone()), (ring_entry_name(r.folder).as_str(), vec![e.main])); + let sub: usize = e.main as usize; + let Kind::Sub { next, flow, entry, .. } = &f.events[sub].kind else { panic!("expected the ring get sub") }; + assert_eq!((flow.as_str(), entry.as_str()), ("", ROOT_ENTRY)); + assert_eq!(param(&f.events[sub], "ContentName"), Some(&Val::Str(r.actor.to_string()))); + + let guard: usize = *next as usize; + let Kind::Switch { cases, .. } = &f.events[guard].kind else { panic!("expected the applied flag guard") }; + assert_eq!(cases.iter().find(|c| c.val == 0).unwrap().ev, NONE, "an applied flag skips credit"); + let mut at: usize = cases.iter().find(|c| c.val == 1).unwrap().ev as usize; + + let mut order: Vec = Vec::new(); + for _ in 0..f.events.len() { + let Kind::Action { next, params, .. } = &f.events[at].kind else { panic!("expected a credit action") }; + if let Some(c) = params { + if let Some(Val::Str(name)) = c.get("GameDataName") { + order.push(name.clone()); + } else if let Some(Val::Str(id)) = c.get("MessageId") { + order.push(id.clone()); + } + } + if *next == NONE { + break; + } + at = *next as usize; + } + assert_eq!( + order, + vec![ + format!("DungeonInfo.{}.SmallKeyNum", r.folder), + format!("DungeonInfo.{}.SmallKeyTotalNum", r.folder), + format!("DungeonInfo.{}.IsGetSmallKeyOnce", r.folder), + crate::key_rings::applied_flag(r.folder), + crate::dungeon_text::message_id(r.folder).to_string(), + ], + "the ring is gotten first, then keys are written, then the count is spoken" + ); + } + + #[test] + fn the_hideout_ring_chest_uses_the_gerudo_fortress_credit() { + let r: &'static crate::key_rings::Ring = &crate::key_rings::HIDEOUT_RING; + let mut f: Flow = small(); + ring_credit(&mut f, r).unwrap(); + assert!(audit(&small(), &f).is_empty()); + let e: &Entry = f.entries.iter().find(|e| e.name == ring_entry_name(r.folder)).unwrap(); + assert_eq!(param(&f.events[e.main as usize], "ContentName"), Some(&Val::Str(r.actor.to_string()))); + assert!(f.events.iter().any(|e| matches!(&e.kind, Kind::Action { params: Some(c), .. } if c.get("GameDataName") == Some(&Val::Str(format!("DungeonInfo.{}.SmallKeyNum", r.folder)))))); + } + #[test] fn a_flow_without_the_holder_gets_one() { let mut f: Flow = small(); @@ -802,16 +969,16 @@ mod tests { #[test] fn the_edited_file_parses_back_and_is_stable() { let raw: Vec = bf(big()).write().unwrap(); - let (out, n): (Vec, usize) = edit_flow(&raw, &["ForestTemple", "SpiritTemple"], true).unwrap(); + let (out, n): (Vec, usize) = edit_flow(&raw, &["ForestTemple", "SpiritTemple"], &[], true).unwrap(); assert_eq!(n, 4); let b: Bf = Bf::parse(&out).unwrap(); assert_eq!(b.flows[0].entries.len(), 3); assert_eq!(b.flows[0].events.len(), 19); assert_eq!(b.flows[0].actors[2].actions, vec![ADD.to_string(), SET.to_string()]); assert_eq!((b.flows[0].actors[3].name.as_str(), b.flows[0].actors[3].actions.clone()), (TALKER, vec![TALK.to_string()])); - let (again, m): (Vec, usize) = edit_flow(&out, &["ForestTemple", "SpiritTemple"], true).unwrap(); + let (again, m): (Vec, usize) = edit_flow(&out, &["ForestTemple", "SpiritTemple"], &[], true).unwrap(); assert_eq!((again, m), (out, 0)); - assert!(edit_flow(&raw, &["Market"], true).is_err()); + assert!(edit_flow(&raw, &["Market"], &[], true).is_err()); } fn row(id: &str, deal: &str) -> Node { @@ -971,7 +1138,7 @@ mod tests { #[test] fn item_dungeon_names_map_to_the_key_counts_and_scenes() { assert_eq!(key_dungeon("Ganons Castle"), Some("InsideGanonCastle")); - assert_eq!(key_dungeon("Thieves Hideout"), None); + assert_eq!(key_dungeon("Thieves Hideout"), Some("GerudoFortress")); assert_eq!(scene_dungeon("Banc/InsideGanonCastle/x.bcett.byml.zs"), Some("InsideGanonCastle")); assert_eq!(scene_dungeon("Banc/GanonCastle/x.bcett.byml.zs"), None); assert!(KEY_DUNGEONS.iter().all(|d| DUNGEONS.contains(d))); diff --git a/randomizer/core/src/dungeon_grant.rs b/randomizer/core/src/dungeon_grant.rs index 1355c653..241bf416 100644 --- a/randomizer/core/src/dungeon_grant.rs +++ b/randomizer/core/src/dungeon_grant.rs @@ -399,7 +399,7 @@ mod tests { assert_eq!(Kind::of_actor("Item_Dungeon_SmallKey"), None); assert_eq!(struct_of("Ganons Castle"), Some("InsideGanonCastle")); assert_eq!(struct_of("Deku Tree"), Some("InsideTheDekuTree")); - assert_eq!(struct_of("Thieves Hideout"), None); + assert_eq!(struct_of("Thieves Hideout"), Some("GerudoFortress")); assert_eq!(event_name(Kind::Boss, "FireTemple", Size::Big), "OOTRR_Boss_FireTemple_Big"); assert_eq!(entry_name(Kind::Map, "IceCavern"), "Success_Map_IceCavern"); assert_eq!(message_id(Kind::Boss, "ForestTemple"), "EventFlowMsg/Dm_SY_Get:OOTRR_BossKey_ForestTemple"); diff --git a/randomizer/core/src/entr.rs b/randomizer/core/src/entr.rs index d03b38f5..1b3a5fc5 100644 --- a/randomizer/core/src/entr.rs +++ b/randomizer/core/src/entr.rs @@ -91,6 +91,23 @@ mod tests { assert!(moved >= 8, "{moved}"); } + #[test] + fn shuffled_hideout_keys_do_not_block_dungeon_entrances() { + for keys in ["any_dungeon", "keysanity"] { + let (_, failed): (usize, usize) = run( + &[ + (mode::SETTING, "dungeons"), + ("gerudo_fortress", "open"), + ("shuffle_hideoutkeys", keys), + ("shuffle_chests", "all"), + ], + 3, + &format!("hideout {keys}"), + ); + assert_eq!(failed, 0, "{keys}"); + } + } + #[test] fn the_setting_off_leaves_the_seed_file_without_entrances() { let d: Data = Data::load().unwrap(); diff --git a/randomizer/core/src/entr/logic.rs b/randomizer/core/src/entr/logic.rs index 2741aa75..e84c2171 100644 --- a/randomizer/core/src/entr/logic.rs +++ b/randomizer/core/src/entr/logic.rs @@ -3,7 +3,7 @@ use std::collections::HashMap as HM; use crate::entr::data::{load, Cat}; use crate::entr::layout::{ages_fit, Layout}; use crate::entr::mode::Mode; -use crate::entr::pools::DUNGEONS; +use crate::entr::pools::{find, DUNGEONS}; use crate::error::{Error as E, Res}; use crate::rng::Rng; use crate::search::Search; @@ -100,6 +100,9 @@ pub fn keeps(base: &[bool], got: &[bool]) -> bool { pub fn keys_fit(w: &World, h: &Have) -> bool { for (k, home) in &h.keys { + if find(home).is_none() { + continue; + } let mut prog: Vec = h.prog.clone(); if let Some(at) = prog.iter().position(|x| x == k) { prog.swap_remove(at); diff --git a/randomizer/core/src/gerudo_drops.rs b/randomizer/core/src/gerudo_drops.rs new file mode 100644 index 00000000..02215d03 --- /dev/null +++ b/randomizer/core/src/gerudo_drops.rs @@ -0,0 +1,54 @@ + + + + +use std::collections::BTreeMap as BM; + +use crate::error::{Error as E, Res}; +use crate::settings::seed::SeedFile; +use crate::slice::data::Data; +use crate::slice::key_spots::{self, Spot}; +use crate::slice::support::{Keep, Plan}; +use crate::world::{LocId, World}; + + +pub fn active(p: &Plan) -> bool { + p.hideout != Keep::Vanilla +} + + + +pub fn eligible(d: &Data, item: &str) -> bool { + key_spots::placeable(d, item, Spot::Free) +} + + + +pub fn add_checks(w: &World, p: &Plan, free: &mut Vec, left: &mut BM) { + if !active(p) { + return; + } + for name in crate::hideout_keys::NATIVE { + match w.loc(name) { + Some(l) => free.push(l), + None => { + *left.entry(format!("{name} is not in the logic world")).or_insert(0) += 1; + } + } + } +} + + +pub fn actors(d: &Data, seed: &SeedFile, fixed: &BM) -> Res> { + let mut out: BM = BM::new(); + for name in crate::hideout_keys::NATIVE { + let item: &str = seed + .placements + .get(name) + .ok_or_else(|| E::Msg(format!("{name} has no item in this seed")))?; + let pick: key_spots::Pick = key_spots::resolve_at(d, name, item, fixed.get(name).map(|s| s.as_str())) + .map_err(|e| E::Msg(format!("{name} holds {item}, which cannot drop from a guard: {e}")))?; + out.insert(name.to_string(), pick.pack); + } + Ok(out) +} diff --git a/randomizer/core/src/gift_keys.rs b/randomizer/core/src/gift_keys.rs index ff7d3f93..12131465 100644 --- a/randomizer/core/src/gift_keys.rs +++ b/randomizer/core/src/gift_keys.rs @@ -28,16 +28,23 @@ const PARAM: &str = "ActorName"; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum Item { Small, + + Ring(&'static crate::key_rings::Ring), Other(Grant), } impl Item { pub fn of(kind: &str) -> Option { match kind { - "SmallKey" => Some(Item::Small), + "SmallKey" | "HideoutSmallKey" => Some(Item::Small), k => Grant::of(k).map(Item::Other), } } + + + pub fn of_item(name: &str, kind: &str) -> Option { + crate::key_rings::by_item_any(name).map(Item::Ring).or_else(|| Item::of(kind)) + } } #[derive(Debug, Clone, PartialEq, Eq)] @@ -68,12 +75,15 @@ pub fn gifts(d: &Data, seed: &SeedFile) -> Res> { continue; } let Some(i) = d.item(item) else { continue }; - let Some(k) = Item::of(&i.kind) else { continue }; - let dungeon: &'static str = i - .dungeon - .as_deref() - .and_then(struct_of) - .ok_or_else(|| E::Msg(format!("{item} at {loc} belongs to no dungeon this build can credit")))?; + let Some(k) = Item::of_item(item, &i.kind) else { continue }; + let dungeon: &'static str = match k { + Item::Ring(r) => r.folder, + _ => i + .dungeon + .as_deref() + .and_then(struct_of) + .ok_or_else(|| E::Msg(format!("{item} at {loc} belongs to no dungeon this build can credit")))?, + }; let l = d.flow.by_name(loc).ok_or_else(|| E::Msg(format!("{loc} is not a flow location")))?; for e in l.edits.iter().filter(|e| e.role == "grant") { for file in std::iter::once(&e.file).chain(e.also.iter()) { @@ -89,14 +99,18 @@ pub fn marked(gs: &[Gift]) -> BS<(Grant, &'static str)> { gs.iter() .filter_map(|g| match g.item { Item::Other(k) => Some((k, g.dungeon)), - Item::Small => None, + Item::Small | Item::Ring(_) => None, }) .collect() } /// The dungeons whose small key line the gifts need (crate::hints::stage keys). pub fn small_dungeons(gs: &[Gift]) -> Vec<&'static str> { - let mut out: Vec<&'static str> = gs.iter().filter(|g| g.item == Item::Small).map(|g| g.dungeon).collect(); + let mut out: Vec<&'static str> = gs + .iter() + .filter(|g| matches!(g.item, Item::Small | Item::Ring(_))) + .map(|g| g.dungeon) + .collect(); out.sort(); out.dedup(); out @@ -119,6 +133,43 @@ fn action_name(f: &Flow, i: usize) -> Option { } } +fn add_count(name: String, count: u32) -> Cont { + Cont { + items: vec![ + ("Index".to_string(), Val::Int(-1)), + ("GameDataName".to_string(), Val::Str(name)), + ("Value".to_string(), Val::Int(count as i32)), + ], + } +} + + + + + + +pub fn is_ring_credit(f: &Flow, index: usize) -> bool { + let Some(next) = (match f.events.get(index).map(|e| &e.kind) { + Some(Kind::Action { next, .. } | Kind::Sub { next, .. }) => Some(*next), + _ => None, + }) else { + return false; + }; + let Some(c) = f.events.get(usize::from(next)).and_then(|e| e.kind.params()) else { + return false; + }; + let Some(Val::Str(name)) = c.get("GameDataName") else { + return false; + }; + let Some(folder) = name.strip_prefix("DungeonInfo.").and_then(|s| s.strip_suffix(".SmallKeyNum")) else { + return false; + }; + let Some(r) = crate::key_rings::by_folder_any(folder) else { + return false; + }; + c.get("Value") == Some(&Val::Int(r.count as i32)) +} + /// The credit writes and the dungeon line, ending on `end`. Returns the first event. pub fn credit(f: &mut Flow, item: Item, d: &'static str, end: u16) -> Res { let (a, set): (u16, u16) = action_slot(f, HOLDER, SET)?; @@ -132,6 +183,14 @@ pub fn credit(f: &mut Flow, item: Item, d: &'static str, end: u16) -> Res { push(f, Kind::Action { next: at + 3, actor: a, act: set, params: Some(set_bool(flag(d, "IsGetSmallKeyOnce"))) })?; push(f, Kind::Action { next: end, actor: t, act: say, params: Some(talk(crate::dungeon_text::message_id(d))) })?; } + Item::Ring(r) => { + let (_, add): (u16, u16) = action_slot(f, HOLDER, ADD_INT)?; + push(f, Kind::Action { next: at + 1, actor: a, act: add, params: Some(add_count(flag(d, "SmallKeyNum"), r.count)) })?; + push(f, Kind::Action { next: at + 2, actor: a, act: add, params: Some(add_count(flag(d, "SmallKeyTotalNum"), r.count)) })?; + push(f, Kind::Action { next: at + 3, actor: a, act: set, params: Some(set_bool(flag(d, "IsGetSmallKeyOnce"))) })?; + push(f, Kind::Action { next: at + 4, actor: a, act: set, params: Some(set_bool(crate::key_rings::applied_flag(d))) })?; + push(f, Kind::Action { next: end, actor: t, act: say, params: Some(talk(crate::dungeon_text::message_id(d))) })?; + } Item::Other(k) => { push(f, Kind::Action { next: at + 1, actor: a, act: set, params: Some(set_bool(flag(d, k.member()))) })?; push(f, Kind::Action { next: end, actor: t, act: say, params: Some(talk(crate::dungeon_grant::message_id(k, d))) })?; @@ -153,6 +212,13 @@ pub fn edit_flow(f: &mut Flow, index: usize, event: &str, item: Item, d: &'stati if action_name(f, index).as_deref() == Some(ADD) { let Kind::Action { next, .. } = f.events[index].kind else { unreachable!() }; let first: u16 = credit(f, item, d, next)?; + if matches!(item, Item::Ring(_)) { + + if let Kind::Action { next, .. } = &mut f.events[index].kind { + *next = first; + } + return Ok(()); + } // The add event itself becomes a jump to the credit: copy the first credit write in place. let k: Kind = f.events[first as usize].kind.clone(); f.events[index].kind = k; @@ -163,6 +229,13 @@ pub fn edit_flow(f: &mut Flow, index: usize, event: &str, item: Item, d: &'stati _ => return Err(E::Msg(format!("gift keys: {event} in {} is not a give, the game files differ", f.name))), }; let first: u16 = credit(f, item, d, next)?; + if matches!(item, Item::Ring(_)) { + + if let Kind::Sub { next, .. } = &mut f.events[index].kind { + *next = first; + } + return Ok(()); + } let k: &mut Kind = &mut f.events[index].kind; let Kind::Sub { next, params, flow, entry } = k else { unreachable!() }; *next = first; @@ -220,6 +293,7 @@ pub fn apply(rf: &mut Romfs, files: &mut Vec, gs: &[Gift], extra: &[ } }; let w: Option = match &call { + Some(_) if matches!(g.item, Item::Ring(_)) => None, Some((fl, en)) if g.item == Item::Small => Some(crate::item_window::key_window(&mut c, rf, files, fl, en)?), Some((fl, en)) => Some(crate::item_window::window(&mut c, rf, files, fl, en)?), None => None, @@ -253,6 +327,18 @@ mod tests { Some((rf, b)) } + fn gift_scene() -> Option<(Romfs, Bf)> { + let p: std::path::PathBuf = ootrr_game::test_romfs::path(); + if !p.is_dir() { + eprintln!("skipped: no romfs at {}, set OOTRR_ROMFS", p.display()); + return None; + } + let mut rf: Romfs = Romfs::open(&p).unwrap(); + let z: Vec = rf.read("Event/EventFlow/Dm_Kokiri_0155.bfevfl.zs").unwrap(); + let b: Bf = Bf::parse(&rf.zs.decompress(&z).unwrap()).unwrap(); + Some((rf, b)) + } + fn actor(f: &Flow, i: usize) -> String { f.events[i].kind.params().and_then(|c| c.get(PARAM)).and_then(|v| match v { Val::Str(s) => Some(s.clone()), @@ -347,4 +433,19 @@ mod tests { // The shown item still comes from the caller's ActorName (an argument, not a literal). assert!(shown); } + + + + #[test] + fn a_ring_gift_survives_the_shortened_gift_scene() { + for ring in crate::key_rings::all_with_hideout() { + let Some((_, mut b)) = gift_scene() else { return }; + let f: &mut Flow = b.flows.first_mut().unwrap(); + edit_flow(f, 51, "Event68", Item::Ring(ring), ring.folder, None).unwrap(); + assert!(is_ring_credit(f, 51), "{}", ring.item); + crate::story_skip::patch_gift(&mut b).unwrap(); + let f: &mut Flow = b.flows.first_mut().unwrap(); + assert!(is_ring_credit(f, 51), "the shortened gift no longer runs the {} credit", ring.item); + } + } } diff --git a/randomizer/core/src/hideout_keys.rs b/randomizer/core/src/hideout_keys.rs new file mode 100644 index 00000000..42311ae5 --- /dev/null +++ b/randomizer/core/src/hideout_keys.rs @@ -0,0 +1,305 @@ + + + + + + + + + + + + +use std::collections::BTreeMap as BM; + +use crate::bfevfl::{Bf, Kind, replace_str}; +use crate::byml::{Byml, Node}; +use crate::chest_slot::LIST; +use crate::error::{Error as E, Res}; +use crate::flow_locations::{StagedFile, dict_id}; +use crate::placement::hash_of; +use crate::romfs::Romfs; +use crate::settings::seed::SeedFile; +use crate::slice::data::Data; +use crate::slice::edit::Edited; +use crate::slice::support::{Keep, Plan}; +use crate::staging::{Out, rewrite}; +use crate::zs; + +pub const FLOW: &str = "Event/EventFlow/SageOfSpirit_RescueCarpenter.bfevfl.zs"; +pub const RUPEE: &str = "Obj_Rupee_Green"; +pub const NATIVE: [&str; 4] = [ + "Hideout 1 Torch Jail Gerudo Key", + "Hideout 2 Torches Jail Gerudo Key", + "Hideout 3 Torches Jail Gerudo Key", + "Hideout 4 Torches Jail Gerudo Key", +]; + +const FLOW_NAME: &str = "SageOfSpirit_RescueCarpenter"; +const WARP: &str = "EventWarpToActorIncludedRayCheck"; + + + + +fn orig_hash(i: usize) -> u64 { + [ + 14727159573379044362u64, + 5303541637929200213, + 1406667554698159711, + 10731814783987785199, + ][i] +} + +pub fn is_native(loc: &str) -> bool { + NATIVE.contains(&loc) +} + +fn old_actor(d: &Data, loc: &str) -> Res { + d.cat + .by_name(loc) + .map(|l| l.item.clone()) + .ok_or_else(|| E::Msg(format!("{loc} is not in the location catalog"))) +} + + +pub fn edit_banc( + file: &str, + raw: &[u8], + edited: Option, + d: &Data, + p: &Plan, + seed: &SeedFile, + fixed: &BM, +) -> Res> { + if p.hideout == Keep::Vanilla { + return Ok(edited); + } + let actors: BM = crate::gerudo_drops::actors(d, seed, fixed)?; + let mut jobs: Vec<(usize, String, Vec<(u64, String, String)>)> = Vec::new(); + for (i, name) in NATIVE.iter().copied().enumerate() { + let Some(l) = d.cat.by_name(name) else { + return Err(E::Msg(format!("{name} is not in the location catalog"))); + }; + let old: String = l.item.clone(); + let new: String = actors + .get(name) + .cloned() + .ok_or_else(|| E::Msg(format!("{name} has no pickup pack actor")))?; + let mut refs: Vec<(u64, String, String)> = Vec::new(); + for r in &l.refs { + if r.files.iter().any(|f| f == file) { + refs.push((r.hash, old.clone(), new.clone())); + } + } + if !refs.is_empty() { + jobs.push((i, name.to_string(), refs)); + } + } + if jobs.is_empty() { + return Ok(edited); + } + let bytes: &[u8] = edited.as_ref().map_or(raw, |e| &e.bytes); + let mut y: Byml = Byml::parse(bytes)?; + let Some(list) = y.root.get_mut("Actors").and_then(|a| a.as_arr_mut()) else { + return Err(E::Msg(format!("{file} has no Actors array"))); + }; + for (_i, loc, refs) in jobs { + let mut flow: Option = None; + let mut spare: Option = None; + for (hash, _, _) in &refs { + let Some(at) = list.iter().position(|a| hash_of(a) == Some(*hash)) else { + continue; + }; + let name: Option<&str> = list[at].get("Name").and_then(|v| v.as_str()); + if name.is_some_and(|s| s.starts_with("SmallKeyForEvent_")) { + flow = Some(at); + } else if spare.is_none() { + spare = Some(at); + } + } + let Some(flow_i) = flow else { + return Err(E::Msg(format!("{loc} has no flow-bound drop actor in {file}"))); + }; + let Some(spare_i) = spare else { + return Err(E::Msg(format!("{loc} has no spare drop actor in {file}"))); + }; + let flow_hash: u64 = hash_of(&list[flow_i]).unwrap_or(0); + let (_, old, new) = refs + .iter() + .find(|(h, _, _)| *h == flow_hash) + .ok_or_else(|| E::Msg(format!("{loc} flow actor is not a catalog ref")))?; + + + if list[flow_i].get("Gyaml").and_then(|v| v.as_str()) != Some(old.as_str()) { + return Err(E::Msg(format!("{loc} flow actor does not hold {old} in {file}"))); + } + list[flow_i].set("Gyaml", Node::Str(RUPEE.to_string())); + + if list[spare_i].get("Gyaml").and_then(|v| v.as_str()) != Some(old.as_str()) { + return Err(E::Msg(format!("{loc} spare actor does not hold {old} in {file}"))); + } + + + list[spare_i].set("Gyaml", Node::Str(new.clone())); + } + let out: Vec = y.write()?; + let mut e: Edited = edited.unwrap_or(Edited { + file: file.to_string(), + old_len: raw.len(), + bytes: Vec::new(), + hits: Vec::new(), + used: Vec::new(), + hearts: Vec::new(), + wraps: Vec::new(), + touched: Vec::new(), + }); + e.bytes = out; + Ok(Some(e)) +} + +fn add_rows(y: &mut Byml, hashes: &[u64]) -> Res { + let rows: &mut Vec = y + .root + .get_mut("Data") + .and_then(|d| d.get_mut("Bool64bitKey")) + .and_then(|t| t.as_arr_mut()) + .ok_or_else(|| E::Format("hideout keys: the flag list has no Bool64bitKey table"))?; + let mut n: usize = 0; + for h in hashes { + if rows.iter().any(|r| hash_of(r) == Some(*h)) { + continue; + } + + + + let at: usize = rows.partition_point(|r| hash_of(r).is_some_and(|x| x < *h)); + rows.insert( + at, + Node::Map(vec![ + ("Hash".to_string(), Node::U64(*h)), + ("ResetTypeValue".to_string(), Node::I32(24)), + ("SaveFileIndex".to_string(), Node::I32(0)), + ]), + ); + n += 1; + } + Ok(n) +} + + + + +pub fn stage_rows(rf: &mut Romfs, more: &mut Vec, active: bool) -> Res<()> { + if !active { + return Ok(()); + } + let mut hashes: Vec = (0..NATIVE.len()).map(orig_hash).collect(); + hashes.sort_unstable(); + hashes.dedup(); + match more.iter().position(|o| o.path == LIST) { + Some(i) => { + let id: Option = dict_id(&more[i].z); + let raw: Vec = rf.zs.decompress(&more[i].z)?; + let mut y: Byml = Byml::parse(&raw)?; + add_rows(&mut y, &hashes)?; + let out: Vec = y.write()?; + more[i].new = out.len(); + more[i].z = zs::compress_raw(&out, id)?; + } + None => { + more.push(rewrite(rf, LIST, |raw| { + let mut y: Byml = Byml::parse(raw)?; + add_rows(&mut y, &hashes)?; + y.write() + })?); + } + } + Ok(()) +} + +fn patch_flow(raw: &[u8], d: &Data, actors: &BM) -> Res> { + let mut b: Bf = Bf::parse(raw)?; + for name in NATIVE { + let old: String = old_actor(d, name)?; + actors + .get(name) + .ok_or_else(|| E::Msg(format!("{name} has no pickup pack actor")))?; + let n = replace_str(&mut b, &old, RUPEE); + if n.total() == 0 { + return Err(E::Msg(format!("the carpenter rescue flow has no {old} to turn into a harmless rupee"))); + } + } + let f: &mut crate::bfevfl::Flow = b + .flows + .iter_mut() + .find(|f| f.name == FLOW_NAME) + .ok_or_else(|| E::Msg(format!("the carpenter rescue flow has no {FLOW_NAME}")))?; + + + + + + let drop: usize = f + .actors + .iter() + .position(|a| a.name == "Obj_Dungeon_SmallKey" && a.sub == "GerudoThiefDropKey(Obj_SmallKey)") + .ok_or_else(|| E::Format("the carpenter rescue flow has no GerudoThiefDropKey key actor"))?; + f.actors[drop].name = RUPEE.to_string(); + let drop_actor: u16 = crate::dungeon_credit::idx(drop)?; + let warp_action: u16 = crate::dungeon_credit::idx( + f.actors[drop] + .actions + .iter() + .position(|x| x == WARP) + .ok_or_else(|| E::Format("the carpenter rescue key actor has no warp action"))?, + )?; + + let warp: usize = f + .events + .iter() + .position(|e| e.name == "Event160") + .ok_or_else(|| E::Format("the carpenter rescue flow has no Event160 key warp"))?; + if let Kind::Action { actor, act, .. } = &mut f.events[warp].kind { + *actor = drop_actor; + *act = warp_action; + } else { + return Err(E::Format("the carpenter rescue key warp is not an action")); + } + let out: Vec = b.write()?; + if Bf::parse(&out)? != b { + return Err(E::Format("the carpenter rescue flow does not parse back after the pickup actor edit")); + } + Ok(out) +} + + + +pub fn stage_flow( + rf: &mut Romfs, + files: &mut Vec, + d: &Data, + p: &Plan, + seed: &SeedFile, + fixed: &BM, +) -> Res<()> { + if p.hideout == Keep::Vanilla { + return Ok(()); + } + let actors: BM = crate::gerudo_drops::actors(d, seed, fixed)?; + let at: Option = files.iter().position(|f| f.path == FLOW); + let compressed: Vec = match at { + Some(i) => files[i].z.clone(), + None => rf.read(FLOW)?, + }; + let id: Option = dict_id(&compressed); + let raw: Vec = rf.zs.decompress(&compressed)?; + let out: Vec = patch_flow(&raw, d, &actors)?; + let old: usize = at.map_or(raw.len(), |i| files[i].old); + let z: Vec = zs::compress_raw(&out, id)?; + let file: StagedFile = StagedFile { path: FLOW.to_string(), z, old, new: out.len() }; + match at { + Some(i) => files[i] = file, + None => files.push(file), + } + Ok(()) +} diff --git a/randomizer/core/src/key_ring_credit.rs b/randomizer/core/src/key_ring_credit.rs new file mode 100644 index 00000000..e503c0ee --- /dev/null +++ b/randomizer/core/src/key_ring_credit.rs @@ -0,0 +1,667 @@ + + + + + + + + + + + +use crate::bfevfl::flow::NONE; +use crate::bfevfl::{Bf, Case, Cont, Entry, Event, Flow, Kind, Val}; +use crate::byml::{Byml, Node}; +use crate::chest_slot::LIST; +use crate::error::{Error as E, Res}; +use crate::flow_locations::dict_id; +use crate::romfs::Romfs; +use crate::staging::{rewrite, Out}; +use crate::zs; + +const PREFIX: &str = "OOTRRKeyRing"; +const FLOW: &str = "ActionGuide"; + + +const WORLD_ENTRY: &str = "OOTRRRingWorld"; +const SHOP_ENTRY: &str = "ActionGuideForShop"; +const GET_ENTRY: &str = "ActionGuide"; +const WAIT_ACTOR: &str = "EventSystemActor"; +const WAIT_ACT: &str = "EventWait"; +const TRUE: u32 = 0x8000_0001; +const HOLDER: &str = "GameDataActor"; +const ASK_BOOL: &str = "EventQueryIsGameDataBool"; +const ADD: &str = "EventTriggerAddOrSubGameDataInt"; +const SET: &str = "EventTriggerSetGameDataBool"; +const BASE_ROW: u32 = 0x154ef588; + +fn idx(n: usize) -> Res { + u16::try_from(n).map_err(|_| E::Format("key rings: too many events in the flow")) +} + +fn push(f: &mut Flow, kind: Kind) -> Res { + let i: u16 = idx(f.events.len())?; + f.events.push(Event { name: format!("{PREFIX}{i}"), kind }); + Ok(i) +} + + + +fn switch(f: &mut Flow, actor: &str, query: &str, params: Cont, on_true: u16, on_false: u16) -> Res { + let (a, q): (u16, u16) = crate::start_state::query_slot(f, actor, query)?; + Ok(Kind::Switch { actor: a, query: q, cases: vec![Case { val: 0, ev: on_true }, Case { val: 1, ev: on_false }], params: Some(params) }) +} + +fn add_int(name: String, count: u32) -> Cont { + Cont { + items: vec![ + ("Index".to_string(), Val::Int(-1)), + ("GameDataName".to_string(), Val::Str(name)), + ("Value".to_string(), Val::Int(count as i32)), + ], + } +} + + + + +fn ring(f: &mut Flow, r: &'static crate::key_rings::Ring, next: u16) -> Res { + let applied: String = crate::key_rings::applied_flag(r.folder); + let (a, add): (u16, u16) = crate::dungeon_credit::action_slot(f, HOLDER, ADD)?; + let (_, set): (u16, u16) = crate::dungeon_credit::action_slot(f, HOLDER, SET)?; + let (t, say): (u16, u16) = crate::dungeon_credit::action_slot(f, crate::dungeon_credit::TALKER, crate::dungeon_credit::TALK)?; + + let say_it: u16 = push(f, Kind::Action { + next, + actor: t, + act: say, + params: Some(crate::dungeon_credit::talk(crate::dungeon_text::message_id(r.folder))), + })?; + let mark: u16 = push(f, Kind::Action { next: say_it, actor: a, act: set, params: Some(crate::dungeon_credit::set_bool(applied.clone())) })?; + let once: u16 = push(f, Kind::Action { + next: mark, + actor: a, + act: set, + params: Some(crate::dungeon_credit::set_bool(crate::dungeon_credit::flag(r.folder, "IsGetSmallKeyOnce"))), + })?; + let total: u16 = push(f, Kind::Action { + next: once, + actor: a, + act: add, + params: Some(add_int(crate::dungeon_credit::flag(r.folder, "SmallKeyTotalNum"), r.count)), + })?; + let num: u16 = push(f, Kind::Action { + next: total, + actor: a, + act: add, + params: Some(add_int(crate::dungeon_credit::flag(r.folder, "SmallKeyNum"), r.count)), + })?; + + + + let held: Kind = switch( + f, + HOLDER, + ASK_BOOL, + Cont { items: vec![("GameDataName".to_string(), Val::Str(crate::key_rings::got_flag(r.actor))), ("Index".to_string(), Val::Int(-1))] }, + num, + next, + )?; + let held_q: u16 = push(f, held)?; + + let asked: Kind = switch( + f, + HOLDER, + ASK_BOOL, + Cont { items: vec![("GameDataName".to_string(), Val::Str(applied)), ("Index".to_string(), Val::Int(-1))] }, + next, + held_q, + )?; + push(f, asked) +} + + + +pub fn patch(f: &mut Flow) -> Res<()> { + patch_with(f, &crate::key_rings::RINGS.iter().collect::>()) +} + +pub fn patch_with(f: &mut Flow, rings: &[&'static crate::key_rings::Ring]) -> Res<()> { + if rings.is_empty() { + return Ok(()); + } + if f.events.iter().any(|e| e.name.starts_with(PREFIX)) { + return Ok(()); + } + let template: &crate::bfevfl::Entry = f.entries.iter().find(|e| e.name == GET_ENTRY).ok_or_else(|| E::Msg(format!("key rings: no {GET_ENTRY} entry in the {FLOW} flow")))?; + let pad: u16 = template.pad; + let (a, x): (u16, u16) = crate::start_state::slot(f, WAIT_ACTOR, WAIT_ACT)?; + let wait: u16 = push(f, Kind::Action { + next: NONE, + actor: a, + act: x, + params: Some(Cont { + items: vec![("IsWaitEnd".to_string(), Val::Bool(TRUE)), ("Frames".to_string(), Val::Int(1))], + }), + })?; + let mut first: u16 = wait; + for r in rings.iter().rev() { + first = ring(f, r, first)?; + } + f.entries.push(Entry { name: WORLD_ENTRY.to_string(), subs: Vec::new(), vars: Vec::new(), main: first, pad }); + let shop: &mut crate::bfevfl::Entry = f.entries.iter_mut().find(|e| e.name == SHOP_ENTRY).ok_or_else(|| E::Msg(format!("key rings: no {SHOP_ENTRY} entry in the {FLOW} flow")))?; + shop.main = first; + Ok(()) +} + +pub fn patch_bf(b: &mut Bf, rings: &[&'static crate::key_rings::Ring]) -> Res<()> { + let f: &mut Flow = b.flows.iter_mut().find(|x| x.name == FLOW).ok_or_else(|| E::Msg(format!("key rings: no {FLOW} flow")))?; + patch_with(f, rings) +} + + +fn redirect(f: &mut Flow, file: &str) -> Res { + let mut n: usize = 0; + for e in &mut f.events { + if let Kind::Sub { entry, flow, .. } = &mut e.kind + && flow == FLOW + && entry == GET_ENTRY + { + *entry = WORLD_ENTRY.to_string(); + n += 1; + } + } + if n != 1 { + return Err(E::Msg(format!("key rings: {file} calls {FLOW}:{GET_ENTRY} {n} times, expected once"))); + } + Ok(n) +} + +pub fn redirect_bf(b: &mut Bf, file: &str) -> Res<()> { + let f: &mut Flow = b.flows.iter_mut().find(|x| x.name == file).ok_or_else(|| E::Msg(format!("key rings: no {file} flow")))?; + redirect(f, file)?; + Ok(()) +} + + + +pub fn stage_flows(rf: &mut Romfs, late: &mut Vec, work: &std::path::Path, rings: &[&'static crate::key_rings::Ring]) -> Res<()> { + if rings.is_empty() { + return Ok(()); + } + crate::story_skip::stage_late(rf, late, work, FLOW, |b| patch_bf(b, rings))?; + for file in ["Dm_SY_Get", "Dm_SY_Get_WithoutPlayer"] { + crate::story_skip::stage_late(rf, late, work, file, |b| redirect_bf(b, file))?; + } + Ok(()) +} + +fn flag_pairs_with(rings: &[&'static crate::key_rings::Ring]) -> Vec<(String, u32)> { + let mut out: Vec<(String, u32)> = Vec::new(); + for r in rings { + let got: String = crate::key_rings::got_flag(r.actor); + let applied: String = crate::key_rings::applied_flag(r.folder); + out.push((got.clone(), crate::flags::hash_name(&got))); + out.push((applied.clone(), crate::flags::hash_name(&applied))); + } + out +} + +fn row_hash(r: &Node) -> Option { + match r.get("Hash") { + Some(Node::U32(h)) => Some(*h), + _ => None, + } +} + +fn is_our_row(r: &Node, h: u32) -> bool { + row_hash(r) == Some(h) + && r.get("DefaultValue") == Some(&Node::Bool(false)) + && r.get("ResetTypeValue") == Some(&Node::I32(8)) + && r.get("SaveFileIndex") == Some(&Node::I32(0)) +} + + + + +fn add_isget_members_with(y: &mut Byml, rings: &[&'static crate::key_rings::Ring]) -> Res<()> { + let isget: u32 = crate::flags::hash_name("IsGet"); + let structs: &mut Vec = y + .root + .get_mut("Data") + .and_then(|d| d.get_mut("Struct")) + .and_then(|s| s.as_arr_mut()) + .ok_or_else(|| E::Format("key rings: the game data list has no Struct table"))?; + let members: &mut Vec = structs + .iter_mut() + .find(|s| row_hash(s) == Some(isget)) + .and_then(|s| s.get_mut("DefaultValue")) + .and_then(|v| v.as_arr_mut()) + .ok_or_else(|| E::Format("key rings: the game data list has no IsGet struct"))?; + for r in rings { + let member: u32 = crate::flags::hash_name(r.actor); + let flag: u32 = crate::flags::hash_name(&crate::key_rings::got_flag(r.actor)); + if let Some(row) = members.iter().find(|m| row_hash(m) == Some(member)) { + if row.get("Value") != Some(&Node::U32(flag)) { + return Err(E::Msg(format!("key rings: the IsGet member for {} differs from the game data", r.actor))); + } + continue; + } + members.push(Node::Map(vec![ + ("Hash".to_string(), Node::U32(member)), + ("Value".to_string(), Node::U32(flag)), + ])); + } + Ok(()) +} + +fn add_rows_with(y: &mut Byml, rings: &[&'static crate::key_rings::Ring]) -> Res<()> { + let rows: &mut Vec = y + .root + .get_mut("Data") + .and_then(|d| d.get_mut("Bool")) + .and_then(|b| b.as_arr_mut()) + .ok_or_else(|| E::Format("key rings: the game data list has no Bool table"))?; + let base: Node = rows + .iter() + .find(|r| row_hash(r) == Some(BASE_ROW)) + .cloned() + .ok_or_else(|| E::Format("key rings: the game data list has no saved Bool template"))?; + for (name, h) in flag_pairs_with(rings) { + if let Some(row) = rows.iter().find(|r| row_hash(r) == Some(h)) { + if !is_our_row(row, h) { + return Err(E::Msg(format!("key rings: the flag {name} clashes with a game flag"))); + } + continue; + } + let mut row: Node = base.clone(); + row.set("Hash", Node::U32(h)); + row.set("DefaultValue", Node::Bool(false)); + row.set("ResetTypeValue", Node::I32(8)); + row.set("SaveFileIndex", Node::I32(0)); + rows.push(row); + } + Ok(()) +} + +pub fn add_runtime_rows(raw: &[u8], rings: &[&'static crate::key_rings::Ring]) -> Res> { + let mut y: Byml = Byml::parse(raw)?; + add_rows_with(&mut y, rings)?; + add_isget_members_with(&mut y, rings)?; + y.write() +} + +fn edit_raw(raw: &[u8], rings: &[&'static crate::key_rings::Ring]) -> Res> { + add_runtime_rows(raw, rings) +} + + + +pub fn stage_rows(rf: &mut Romfs, more: &mut Vec, rings: &[&'static crate::key_rings::Ring]) -> Res<()> { + if rings.is_empty() { + return Ok(()); + } + match more.iter().position(|o| o.path == LIST) { + Some(i) => { + let id: Option = dict_id(&more[i].z); + let raw: Vec = rf.zs.decompress(&more[i].z)?; + let out: Vec = edit_raw(&raw, rings)?; + more[i].new = out.len(); + more[i].z = zs::compress_raw(&out, id)?; + } + None => more.push(rewrite(rf, LIST, |raw| edit_raw(raw, rings))?), + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::bfevfl::flow::NONE; + use crate::bfevfl::{Actor, Entry}; + use std::collections::{BTreeMap as BM, BTreeSet as BS}; + + fn flag_pairs() -> Vec<(String, u32)> { + flag_pairs_with(&crate::key_rings::RINGS.iter().collect::>()) + } + + fn add_isget_members(y: &mut Byml) -> Res<()> { + add_isget_members_with(y, &crate::key_rings::RINGS.iter().collect::>()) + } + + fn add_rows(y: &mut Byml) -> Res<()> { + add_rows_with(y, &crate::key_rings::RINGS.iter().collect::>()) + } + + const EXPECTED: [(&str, u32); 21] = [ + ("test", 0xba6bd213), + ("DungeonInfo.ForestTemple.SmallKeyNum", 0x90237092), + ("IsGet.Item_Dungeon_SmallKey", 0x154ef588), + ("IsGet.Item_Ring_Forest", 0x2299468c), + ("IsGet.Item_Ring_Fire", 0x223b086e), + ("IsGet.Item_Ring_Water", 0xd8db874b), + ("IsGet.Item_Ring_Shadow", 0x92d9860a), + ("IsGet.Item_Ring_Spirit", 0xb28490ba), + ("IsGet.Item_Ring_Well", 0xd5e3c18d), + ("IsGet.Item_Ring_GTG", 0x5f62ae19), + ("IsGet.Item_Ring_Ganon", 0x685bed59), + ("IsGet.Item_Ring_Hideout", 0x56844297), + ("OOTRR_KeyRing.ForestTemple", 0x2cffcc4f), + ("OOTRR_KeyRing.FireTemple", 0x4e79f9b5), + ("OOTRR_KeyRing.WaterTemple", 0xeba9f19f), + ("OOTRR_KeyRing.ShadowTemple", 0xc8d7d030), + ("OOTRR_KeyRing.SpiritTemple", 0x64576046), + ("OOTRR_KeyRing.BottomOfTheWell", 0x0607308e), + ("OOTRR_KeyRing.GerudoTrainingGround", 0x26517f00), + ("OOTRR_KeyRing.InsideGanonCastle", 0x97150d07), + ("OOTRR_KeyRing.GerudoFortress", 0x22c11c3d), + ]; + + fn actor(name: &str, acts: &[&str], queries: &[&str]) -> Actor { + Actor { + name: name.to_string(), + sub: String::new(), + arg: String::new(), + actions: acts.iter().map(|s| s.to_string()).collect(), + queries: queries.iter().map(|s| s.to_string()).collect(), + params: None, + ep: 0, + cut: 0, + } + } + + fn entries() -> [(&'static str, &'static str); 2] { + [(WORLD_ENTRY, "the world pickup"), (SHOP_ENTRY, "the shop get")] + } + + fn guide_wait(f: &Flow) -> usize { + f.events + .iter() + .position(|e| matches!(&e.kind, Kind::Action { params: Some(c), .. } if c.get("Frames") == Some(&Val::Int(1)) && c.get("IsWaitEnd") == Some(&Val::Bool(TRUE)))) + .expect("the ring chain has a one-frame wait") + } + + fn action_guide() -> Flow { + Flow { + name: FLOW.to_string(), + actors: vec![actor("EventSystemActor", &["EventWait"], &[])], + events: vec![ + Event { + name: "OOTRRNoGuide0".to_string(), + kind: Kind::Action { next: NONE, actor: 0, act: 0, params: None }, + }, + Event { + name: "OOTRRRingCallItemGet".to_string(), + kind: Kind::Action { next: 0, actor: 0, act: 0, params: None }, + }, + Event { + name: "OOTRRRingCallForShop".to_string(), + kind: Kind::Action { next: 0, actor: 0, act: 0, params: None }, + }, + ], + entries: vec![ + Entry { name: "ActionGuide".to_string(), subs: Vec::new(), vars: Vec::new(), main: 1, pad: 0 }, + Entry { name: "ActionGuideForShop".to_string(), subs: Vec::new(), vars: Vec::new(), main: 2, pad: 0 }, + ], + } + } + + #[test] + fn only_world_and_shop_gets_check_each_held_ring_before_their_guide_wait() { + let mut f: Flow = action_guide(); + patch(&mut f).unwrap(); + let wait: usize = guide_wait(&f); + for (entry_name, label) in entries() { + let entry: &Entry = f.entries.iter().find(|e| e.name == entry_name).unwrap(); + let mut at: usize = entry.main as usize; + assert_ne!(at, wait, "{label} starts at the ring checks, not the wait"); + let mut applied_seen: BS = BS::new(); + let mut held_seen: BS = BS::new(); + let mut reached_wait: bool = false; + for _ in 0..f.events.len() { + if at == wait { + reached_wait = true; + break; + } + let e: &Event = &f.events[at]; + match &e.kind { + Kind::Switch { params, cases, .. } => { + let c: &Cont = params.as_ref().unwrap(); + let Some(Val::Str(name)) = c.get("GameDataName") else { panic!("a ring switch needs a flag") }; + if name.starts_with("OOTRR_KeyRing.") { + applied_seen.insert(name.clone()); + } else if name.starts_with("IsGet.") { + held_seen.insert(name.clone()); + } + + + let answer: u32 = if name.starts_with("OOTRR_KeyRing.") { 1 } else { 0 }; + at = cases.iter().find(|c| c.val == answer).unwrap().ev as usize; + } + Kind::Action { next, .. } => at = *next as usize, + _ => panic!("unexpected ring credit event"), + } + } + assert!(reached_wait, "{label} reaches its wait"); + assert_eq!(applied_seen.len(), 8, "{label} has an applied-flag guard per ring"); + assert_eq!(held_seen.len(), 8, "{label} checks every saved IsGet bool"); + assert!(applied_seen.contains(&crate::key_rings::applied_flag("ForestTemple"))); + assert!(held_seen.contains(&crate::key_rings::got_flag("Item_Ring_Forest"))); + } + let ordinary: &Entry = f.entries.iter().find(|e| e.name == GET_ENTRY).unwrap(); + assert_eq!(ordinary.main, 1, "chests and gifts keep the untouched item-get entry"); + assert!(f.events.iter().any(|e| e.name.starts_with(PREFIX))); + let before: Flow = f.clone(); + patch(&mut f).unwrap(); + assert_eq!(f, before, "the credit is added once"); + } + + #[test] + fn the_hideout_ring_is_checked_and_credited_like_a_standard_ring() { + let mut f: Flow = action_guide(); + let rings: Vec<&'static crate::key_rings::Ring> = vec![&crate::key_rings::HIDEOUT_RING]; + patch_with(&mut f, &rings).unwrap(); + let wait: usize = guide_wait(&f); + let entry: &Entry = f.entries.iter().find(|e| e.name == WORLD_ENTRY).unwrap(); + let mut at: usize = entry.main as usize; + let mut applied: BS = BS::new(); + let mut held: BS = BS::new(); + let mut four: bool = false; + for _ in 0..f.events.len() { + if at == wait { + break; + } + match &f.events[at].kind { + Kind::Switch { params, cases, .. } => { + let c: &Cont = params.as_ref().unwrap(); + let Some(Val::Str(name)) = c.get("GameDataName") else { panic!("a ring switch needs a flag") }; + if name.starts_with("OOTRR_KeyRing.") { + applied.insert(name.clone()); + } else if name.starts_with("IsGet.") { + held.insert(name.clone()); + } + let answer: u32 = if name.starts_with("OOTRR_KeyRing.") { 1 } else { 0 }; + at = cases.iter().find(|c| c.val == answer).unwrap().ev as usize; + } + Kind::Action { next, params, .. } => { + if let Some(c) = params + && c.get("GameDataName") == Some(&Val::Str("DungeonInfo.GerudoFortress.SmallKeyNum".to_string())) + { + four = c.get("Value") == Some(&Val::Int(4)); + } + at = *next as usize; + } + _ => panic!("unexpected ring credit event"), + } + } + assert_eq!(applied.len(), 1); + assert_eq!(held.len(), 1); + assert!(applied.contains(&crate::key_rings::applied_flag("GerudoFortress"))); + assert!(held.contains(&crate::key_rings::got_flag("Item_Ring_Hideout"))); + assert!(four, "the Hideout ring writes four keys"); + } + + #[test] + fn only_the_world_get_flows_call_the_checked_entry() { + let sub = |flow: &str, entry: &str| Event { + name: format!("call {flow} {entry}"), + kind: Kind::Sub { next: NONE, params: None, flow: flow.to_string(), entry: entry.to_string() }, + }; + let mut b: Bf = Bf { + ver: [0, 4, 0, 0], + bom: 0xFEFF, + shift: 3, + pad: 0, + name: "flow".to_string(), + tls: Vec::new(), + flows: vec![Flow { + name: "Dm_SY_Get".to_string(), + actors: Vec::new(), + events: vec![sub(FLOW, GET_ENTRY), sub("Other", GET_ENTRY)], + entries: Vec::new(), + }], + }; + redirect_bf(&mut b, "Dm_SY_Get").unwrap(); + let Kind::Sub { entry, .. } = &b.flows[0].events[0].kind else { panic!("sub") }; + assert_eq!(entry, WORLD_ENTRY, "the world pickup calls the checked entry"); + let Kind::Sub { entry, .. } = &b.flows[0].events[1].kind else { panic!("sub") }; + assert_eq!(entry, GET_ENTRY, "other callers are left alone"); + assert!(redirect_bf(&mut b, "Dm_SY_Get").is_err(), "a second redirect is refused"); + } + + #[test] + fn a_picked_up_ring_writes_its_full_count_and_its_applied_flag() { + let mut f: Flow = action_guide(); + patch(&mut f).unwrap(); + let forest: &crate::key_rings::Ring = crate::key_rings::by_folder("ForestTemple").unwrap(); + let applied: String = crate::key_rings::applied_flag(forest.folder); + let wait: usize = guide_wait(&f); + let entry_name: &str = WORLD_ENTRY; + let mut at: usize = f.entries.iter().find(|e| e.name == entry_name).unwrap().main as usize; + let mut credit: Option = None; + for _ in 0..f.events.len() { + if at == wait { + break; + } + let e: &Event = &f.events[at]; + if let Kind::Switch { cases, params, .. } = &e.kind + && params.as_ref().and_then(|c| c.get("GameDataName")) == Some(&Val::Str(applied.clone())) + { + let skip: u16 = cases.iter().find(|c| c.val == 0).unwrap().ev; + credit = Some(cases.iter().find(|c| c.val == 1).unwrap().ev); + assert_ne!(skip, credit.unwrap(), "an applied flag has its own branch"); + break; + } + let Kind::Action { next, .. } = &e.kind else { panic!("expected a ring check") }; + at = *next as usize; + } + let mut at: usize = credit.expect("the Forest applied flag is checked once per chain") as usize; + let mut writes: BM = BM::new(); + for _ in 0..f.events.len() { + let e: &Event = &f.events[at]; + match &e.kind { + Kind::Switch { cases, params, .. } => { + + + let name: String = match params.as_ref().and_then(|c| c.get("GameDataName")) { + Some(Val::Str(n)) => n.clone(), + _ => panic!("a ring switch needs a flag"), + }; + let answer: u32 = if name.starts_with("OOTRR_KeyRing.") { 1 } else { 0 }; + at = cases.iter().find(|c| c.val == answer).unwrap().ev as usize; + } + Kind::Action { next, params, .. } => { + if let Some(c) = params + && let Some(Val::Str(name)) = c.get("GameDataName") + { + let value: Option = match c.get("Value") { + Some(Val::Int(v)) => Some(*v), + Some(Val::Bool(v)) => Some(*v as i32), + _ => None, + }; + if let Some(v) = value { + writes.insert(name.clone(), v); + } + } + if usize::from(*next) == wait { + break; + } + at = *next as usize; + } + _ => break, + } + } + assert_eq!(writes.get("DungeonInfo.ForestTemple.SmallKeyNum"), Some(&5)); + assert_eq!(writes.get("DungeonInfo.ForestTemple.SmallKeyTotalNum"), Some(&5)); + assert_eq!(writes.get("DungeonInfo.ForestTemple.IsGetSmallKeyOnce"), Some(&1)); + assert_eq!(writes.get(applied.as_str()), Some(&1)); + } + + #[test] + fn every_flag_the_ring_credit_uses_has_a_staged_game_data_row() { + let names: BS = flag_pairs().into_iter().map(|(n, _)| n).collect(); + for r in crate::key_rings::RINGS { + assert!(names.contains(&crate::key_rings::got_flag(r.actor))); + assert!(names.contains(&crate::key_rings::applied_flag(r.folder))); + } + for (n, h) in EXPECTED { + assert_eq!(crate::flags::hash_name(n), h, "{n}"); + } + } + + #[test] + fn the_pouch_add_can_record_each_ring_through_the_is_get_struct() { + let mut y: Byml = Byml { + root: Node::Map(vec![( + "Data".to_string(), + Node::Map(vec![ + ("Bool".to_string(), Node::Arr(vec![Node::Map(vec![("Hash".to_string(), Node::U32(BASE_ROW))])])), + ( + "Struct".to_string(), + Node::Arr(vec![Node::Map(vec![ + ("Hash".to_string(), Node::U32(crate::flags::hash_name("IsGet"))), + ("DefaultValue".to_string(), Node::Arr(Vec::new())), + ])]), + ), + ]), + )]), + version: 2, + big: false, + }; + add_rows(&mut y).unwrap(); + add_isget_members(&mut y).unwrap(); + let bools: &[Node] = y.root.get("Data").unwrap().get("Bool").unwrap().as_arr().unwrap(); + assert_eq!(bools.len(), 1 + 16, "each ring has a held flag and an applied flag"); + let isget: u32 = crate::flags::hash_name("IsGet"); + let members: &[Node] = y + .root + .get("Data") + .unwrap() + .get("Struct") + .unwrap() + .as_arr() + .unwrap() + .iter() + .find(|s| row_hash(s) == Some(isget)) + .unwrap() + .get("DefaultValue") + .unwrap() + .as_arr() + .unwrap(); + assert_eq!(members.len(), 8, "each generated ring actor gets one IsGet member"); + for r in crate::key_rings::RINGS { + let member: u32 = crate::flags::hash_name(r.actor); + let flag: u32 = crate::flags::hash_name(&crate::key_rings::got_flag(r.actor)); + assert_eq!( + members.iter().find(|m| row_hash(m) == Some(member)).and_then(|m| m.get("Value")), + Some(&Node::U32(flag)), + "{}", + r.actor + ); + } + let before: Byml = y.clone(); + add_rows(&mut y).unwrap(); + add_isget_members(&mut y).unwrap(); + assert_eq!(y, before, "the rows are added once"); + } +} diff --git a/randomizer/core/src/key_ring_text.rs b/randomizer/core/src/key_ring_text.rs new file mode 100644 index 00000000..ff44c808 --- /dev/null +++ b/randomizer/core/src/key_ring_text.rs @@ -0,0 +1,110 @@ + + + + + + +use std::path::Path as P; + +use crate::error::{Error as E, Res}; +use crate::key_rings::Ring; +use crate::msbt::{self, Msbt}; +use crate::romfs::Romfs; +use crate::sarc; +use crate::staging::Out; + +pub const POUCH_MSG: &str = "ActorMsg/PouchContent.msbt"; + +fn lines(r: &Ring) -> [(&str, String); 4] { + let name: String = format!("Small Key Ring ({})", r.dungeon); + [ + ("_Name", name.clone()), + ("_Caption", format!("A ring holding all {} small keys for the {}.", r.count, r.dungeon)), + ("_GetMessage", format!("You got the {name}!")), + ("_GetCaption", format!("All {} small keys for the {} are now yours.", r.count, r.dungeon)), + ] +} + +fn label(r: &Ring, suffix: &str) -> String { + format!("{}{suffix}", r.actor) +} + + +pub fn apply(raw: &[u8]) -> Res> { + apply_with(raw, &crate::key_rings::all_with_hideout()) +} + +pub fn apply_with(raw: &[u8], rings: &[&Ring]) -> Res> { + let mut es: Vec = sarc::parse(raw)?; + let at: usize = es + .iter() + .position(|e| e.name == POUCH_MSG) + .ok_or_else(|| E::Msg(format!("key ring text: the language archive has no {POUCH_MSG}")))?; + let mut m: Msbt = msbt::parse(&es[at].data)?; + if m.write()? != es[at].data { + return Err(E::Format("key ring text: PouchContent.msbt does not round trip")); + } + for r in rings { + for (suffix, text) in lines(r) { + m.put_markup(&label(r, suffix), &text)?; + } + } + let w: Vec = m.write()?; + msbt::parse(&w)?; + es[at].data = w; + sarc::write(&es) +} + + + +pub fn stage(rf: &mut Romfs, work: &P, more: &mut Vec, rings: &[&Ring]) -> Res<()> { + if rings.is_empty() { + return Ok(()); + } + for f in crate::hints::languages(rf)? { + crate::staging::edit_staged(rf, more, work, &f, true, |raw| apply_with(raw, rings))?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::msbt::{Label, Sec}; + + fn book() -> Vec { + let groups: usize = 2; + let mut g: Vec> = vec![Vec::new(); groups]; + let mut t: Vec> = Vec::new(); + let src: Vec = msbt::encode(&msbt::from_markup("Small Key").unwrap(), false).unwrap(); + g[msbt::label_group("Item_Dungeon_SmallKey_Name", groups)].push(Label { name: "Item_Dungeon_SmallKey_Name".to_string(), idx: 0 }); + t.push(src); + Msbt { be: false, unk_a: [0, 0], enc: 0, ver: 3, unk_b: [0, 0], pad: [0; 10], secs: vec![Sec::Lbl(g), Sec::Txt(t)] }.write().unwrap() + } + + fn archive() -> Vec { + sarc::write(&[sarc::Entry { name: POUCH_MSG.to_string(), data: book() }]).unwrap() + } + + #[test] + fn every_ring_gets_four_nonempty_texts_that_name_the_dungeon() { + let es: Vec = sarc::parse(&apply(&archive()).unwrap()).unwrap(); + let m: Msbt = msbt::parse(&sarc::get(&es, POUCH_MSG).unwrap().data).unwrap(); + for r in crate::key_rings::all_with_hideout() { + for (suffix, _) in lines(r) { + let s: String = msbt::to_markup(&m.text(&label(r, suffix)).unwrap_or_else(|e| panic!("{}: {e}", r.actor))); + assert!(!s.is_empty(), "{}", r.actor); + } + let got: String = msbt::to_markup(&m.text(&label(r, "_GetMessage")).unwrap()); + assert!(got.contains(r.dungeon), "{got}"); + } + } + + #[test] + fn the_pouch_name_matches_the_item_name_in_the_spoiler_log() { + for r in crate::key_rings::all_with_hideout() { + let name: String = lines(r)[0].1.clone(); + assert_eq!(name, r.item); + } + } +} diff --git a/randomizer/core/src/key_rings.rs b/randomizer/core/src/key_rings.rs new file mode 100644 index 00000000..38d314f1 --- /dev/null +++ b/randomizer/core/src/key_rings.rs @@ -0,0 +1,347 @@ + + + + + + +use crate::rng::Rng; + +pub const SETTING: &str = "key_rings"; +pub const NUM: u16 = 204; +pub const MODE_SETTING: &str = "key_rings_mode"; +pub const MODE_NUM: u16 = 205; +pub const COUNT_SETTING: &str = "key_rings_count"; +pub const COUNT_NUM: u16 = 206; +pub const SELECTION_SETTING: &str = "key_rings_selection"; +pub const SELECTION_NUM: u16 = 207; +pub const HIDEOUT_SETTING: &str = "hideout_key_rings"; +pub const HIDEOUT_NUM: u16 = 208; + +pub const NOTE: &str = "Each standard dungeon's small keys become one key ring. A ring gives every key of its dungeon when it is picked up."; + + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub struct Ring { + pub item: &'static str, + pub key: &'static str, + pub dungeon: &'static str, + + pub choice: &'static str, + + pub select: &'static str, + pub folder: &'static str, + + pub actor: &'static str, + + pub drop_item: &'static str, + + pub drop_actor: &'static str, + pub count: u32, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Mode { + All, + Count, + Selection, + Random, +} + +impl Mode { + pub fn id(self) -> &'static str { + match self { + Mode::All => "all", + Mode::Count => "count", + Mode::Selection => "selection", + Mode::Random => "random", + } + } +} + +pub const CHOICES: [(&str, &str); 8] = [ + ("forest_temple", "Forest Temple"), + ("fire_temple", "Fire Temple"), + ("water_temple", "Water Temple"), + ("shadow_temple", "Shadow Temple"), + ("spirit_temple", "Spirit Temple"), + ("bottom_of_the_well", "Bottom of the Well"), + ("gerudo_training_ground", "Gerudo Training Ground"), + ("ganons_castle", "Ganon's Castle"), +]; + +pub const CHOICE_IDS: [&str; 8] = [ + "forest_temple", + "fire_temple", + "water_temple", + "shadow_temple", + "spirit_temple", + "bottom_of_the_well", + "gerudo_training_ground", + "ganons_castle", +]; + +pub const FOLDERS: [&str; 8] = [ + "ForestTemple", + "FireTemple", + "WaterTemple", + "ShadowTemple", + "SpiritTemple", + "BottomOfTheWell", + "GerudoTrainingGround", + "InsideGanonCastle", +]; + +pub const RINGS: [Ring; 8] = [ + Ring { item: "Small Key Ring (Forest Temple)", key: "Small Key (Forest Temple)", dungeon: "Forest Temple", choice: "forest_temple", select: "key_ring_forest_temple", folder: "ForestTemple", actor: "Item_Ring_Forest", drop_item: "Item_RingDrop_Forest", drop_actor: "Obj_RingDrop_Forest", count: 5 }, + Ring { item: "Small Key Ring (Fire Temple)", key: "Small Key (Fire Temple)", dungeon: "Fire Temple", choice: "fire_temple", select: "key_ring_fire_temple", folder: "FireTemple", actor: "Item_Ring_Fire", drop_item: "Item_RingDrop_Fire", drop_actor: "Obj_RingDrop_Fire", count: 8 }, + Ring { item: "Small Key Ring (Water Temple)", key: "Small Key (Water Temple)", dungeon: "Water Temple", choice: "water_temple", select: "key_ring_water_temple", folder: "WaterTemple", actor: "Item_Ring_Water", drop_item: "Item_RingDrop_Water", drop_actor: "Obj_RingDrop_Water", count: 6 }, + Ring { item: "Small Key Ring (Shadow Temple)", key: "Small Key (Shadow Temple)", dungeon: "Shadow Temple", choice: "shadow_temple", select: "key_ring_shadow_temple", folder: "ShadowTemple", actor: "Item_Ring_Shadow", drop_item: "Item_RingDrop_Shadow", drop_actor: "Obj_RingDrop_Shadow", count: 5 }, + Ring { item: "Small Key Ring (Spirit Temple)", key: "Small Key (Spirit Temple)", dungeon: "Spirit Temple", choice: "spirit_temple", select: "key_ring_spirit_temple", folder: "SpiritTemple", actor: "Item_Ring_Spirit", drop_item: "Item_RingDrop_Spirit", drop_actor: "Obj_RingDrop_Spirit", count: 5 }, + Ring { item: "Small Key Ring (Bottom of the Well)", key: "Small Key (Bottom of the Well)", dungeon: "Bottom of the Well", choice: "bottom_of_the_well", select: "key_ring_bottom_of_the_well", folder: "BottomOfTheWell", actor: "Item_Ring_Well", drop_item: "Item_RingDrop_Well", drop_actor: "Obj_RingDrop_Well", count: 3 }, + Ring { item: "Small Key Ring (Gerudo Training Ground)", key: "Small Key (Gerudo Training Ground)", dungeon: "Gerudo Training Ground", choice: "gerudo_training_ground", select: "key_ring_gerudo_training_ground", folder: "GerudoTrainingGround", actor: "Item_Ring_GTG", drop_item: "Item_RingDrop_GTG", drop_actor: "Obj_RingDrop_GTG", count: 9 }, + Ring { item: "Small Key Ring (Ganons Castle)", key: "Small Key (Ganons Castle)", dungeon: "Ganons Castle", choice: "ganons_castle", select: "key_ring_ganons_castle", folder: "InsideGanonCastle", actor: "Item_Ring_Ganon", drop_item: "Item_RingDrop_Ganon", drop_actor: "Obj_RingDrop_Ganon", count: 2 }, +]; + + + + +pub const HIDEOUT_RING: Ring = Ring { + item: "Small Key Ring (Thieves Hideout)", + key: "Small Key (Thieves Hideout)", + dungeon: "Thieves Hideout", + choice: "thieves_hideout", + select: HIDEOUT_SETTING, + folder: "GerudoFortress", + actor: "Item_Ring_Hideout", + drop_item: "Item_RingDrop_Hideout", + drop_actor: "Obj_RingDrop_Hideout", + count: 4, +}; + +pub fn all() -> Vec<&'static Ring> { + RINGS.iter().collect() +} + + + +pub fn all_with_hideout() -> Vec<&'static Ring> { + let mut out: Vec<&'static Ring> = all(); + out.push(&HIDEOUT_RING); + out +} + +pub fn by_item(item: &str) -> Option<&'static Ring> { + RINGS.iter().find(|r| r.item == item) +} + +pub fn by_key(item: &str) -> Option<&'static Ring> { + RINGS.iter().find(|r| r.key == item) +} + +pub fn by_dungeon(dungeon: &str) -> Option<&'static Ring> { + RINGS.iter().find(|r| r.dungeon == dungeon) +} + +pub fn by_choice(choice: &str) -> Option<&'static Ring> { + RINGS.iter().find(|r| r.choice == choice) +} + +pub fn by_folder(folder: &str) -> Option<&'static Ring> { + RINGS.iter().find(|r| r.folder == folder) +} + +pub fn by_actor(actor: &str) -> Option<&'static Ring> { + RINGS.iter().find(|r| r.actor == actor || r.drop_actor == actor) +} + +pub fn by_drop_item(item: &str) -> Option<&'static Ring> { + RINGS.iter().find(|r| r.drop_item == item) +} + +pub fn by_drop_actor(actor: &str) -> Option<&'static Ring> { + RINGS.iter().find(|r| r.drop_actor == actor) +} + + + +pub fn by_item_any(item: &str) -> Option<&'static Ring> { + by_item(item).or_else(|| (item == HIDEOUT_RING.item).then_some(&HIDEOUT_RING)) +} + +pub fn by_key_any(key: &str) -> Option<&'static Ring> { + by_key(key).or_else(|| (key == HIDEOUT_RING.key).then_some(&HIDEOUT_RING)) +} + +pub fn by_folder_any(folder: &str) -> Option<&'static Ring> { + by_folder(folder).or_else(|| (folder == HIDEOUT_RING.folder).then_some(&HIDEOUT_RING)) +} + +pub fn by_actor_any(actor: &str) -> Option<&'static Ring> { + by_actor(actor).or_else(|| (actor == HIDEOUT_RING.actor || actor == HIDEOUT_RING.drop_actor).then_some(&HIDEOUT_RING)) +} + +pub fn drop_pack_any(actor: &str) -> String { + by_actor_any(actor).map(|r| r.drop_actor.to_string()).unwrap_or_else(|| actor.to_string()) +} + +pub fn is_any_ring(item: &str) -> bool { + by_item_any(item).is_some() +} + + +pub fn selected(ids: &[String]) -> Vec<&'static Ring> { + RINGS.iter().filter(|r| ids.iter().any(|id| id == r.choice)).collect() +} + +fn order(seed: &str, tag: &str) -> Vec { + let mut out: Vec = (0..RINGS.len()).collect(); + Rng::from_text(&format!("{seed} key rings {tag}")).shuffle(&mut out); + out +} + + +pub fn count(seed: &str, n: usize) -> Vec<&'static Ring> { + order(seed, &format!("count {n}")) + .into_iter() + .take(n.min(RINGS.len())) + .map(|i| &RINGS[i]) + .collect() +} + + +pub fn random(seed: &str) -> (usize, Vec<&'static Ring>) { + let mut rng: Rng = Rng::from_text(&format!("{seed} key rings random count")); + let n: usize = 1 + rng.below(RINGS.len() as u64) as usize; + (n, order(seed, &format!("random {n}")).into_iter().take(n).map(|i| &RINGS[i]).collect()) +} + + +pub fn mode_note(mode: Mode, count: usize, active: &[&'static Ring]) -> String { + let names: Vec<&str> = active.iter().map(|r| r.dungeon).collect(); + match mode { + Mode::All => String::new(), + Mode::Count => format!("Key rings were given to {count} seed-randomized standard dungeons: {}.", names.join(", ")), + Mode::Selection => format!("Key rings were given to the selected standard dungeons: {}.", names.join(", ")), + Mode::Random => format!("Key rings were given to {count} seed-randomized standard dungeons: {}.", names.join(", ")), + } +} + +pub fn is_ring(item: &str) -> bool { + by_item(item).is_some() +} + + +pub fn pack(actor: &str) -> String { + actor.to_string() +} + + + +pub fn drop_pack(actor: &str) -> String { + by_actor(actor).map(|r| r.drop_actor.to_string()).unwrap_or_else(|| actor.to_string()) +} + +pub fn got_flag(actor: &str) -> String { + format!("IsGet.{actor}") +} + +pub fn applied_flag(folder: &str) -> String { + format!("OOTRR_KeyRing.{folder}") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_ring_has_a_unique_short_actor_and_flag() { + let mut actors = std::collections::BTreeSet::new(); + let mut drops = std::collections::BTreeSet::new(); + let mut flags = std::collections::BTreeSet::new(); + let mut choices = std::collections::BTreeSet::new(); + let mut selects = std::collections::BTreeSet::new(); + for r in &RINGS { + assert!(r.actor.len() <= 25, "{} is too long", r.actor); + assert!(r.drop_actor.len() <= 25, "{} is too long", r.drop_actor); + assert!(actors.insert(r.actor), "{} repeats an actor", r.actor); + assert!(drops.insert(r.drop_actor), "{} repeats a drop actor", r.drop_actor); + assert!(flags.insert(applied_flag(r.folder)), "{} repeats a flag", r.folder); + assert!(choices.insert(r.choice), "{} repeats a choice", r.choice); + assert!(selects.insert(r.select), "{} repeats a logic setting", r.select); + assert!(by_item(r.item) == Some(r)); + assert!(by_key(r.key) == Some(r)); + assert!(by_dungeon(r.dungeon) == Some(r)); + assert!(by_choice(r.choice) == Some(r)); + assert!(by_folder(r.folder) == Some(r)); + assert!(by_actor(r.actor) == Some(r)); + assert!(by_actor(r.drop_actor) == Some(r)); + assert!(by_drop_item(r.drop_item) == Some(r)); + assert!(by_drop_actor(r.drop_actor) == Some(r)); + assert_eq!(pack(r.actor), r.actor); + assert_eq!(drop_pack(r.actor), r.drop_actor); + } + assert_eq!(actors.len(), RINGS.len()); + assert_eq!(drops.len(), RINGS.len()); + assert_eq!(flags.len(), RINGS.len()); + assert_eq!(choices.len(), RINGS.len()); + assert_eq!(selects.len(), RINGS.len()); + } + + #[test] + fn hideout_and_tcg_rings_are_not_standard_rings() { + assert!(!is_ring("Small Key Ring (Thieves Hideout)")); + assert!(!is_ring("Small Key Ring (Treasure Chest Game)")); + assert!(is_any_ring("Small Key Ring (Thieves Hideout)")); + assert!(!is_any_ring("Small Key Ring (Treasure Chest Game)")); + } + + #[test] + fn hideout_ring_is_only_reachable_through_the_manual_helpers() { + let r: &'static Ring = &HIDEOUT_RING; + assert!(r.actor.len() <= 25); + assert!(r.drop_actor.len() <= 25); + assert_eq!(r.select, HIDEOUT_SETTING); + assert_eq!(by_item_any(r.item), Some(r)); + assert_eq!(by_key_any(r.key), Some(r)); + assert_eq!(by_folder_any(r.folder), Some(r)); + assert_eq!(by_actor_any(r.actor), Some(r)); + assert_eq!(by_actor_any(r.drop_actor), Some(r)); + assert_eq!(drop_pack_any(r.actor), r.drop_actor); + assert_eq!(all_with_hideout().len(), RINGS.len() + 1); + + assert_eq!(by_item(r.item), None); + assert_eq!(by_key(r.key), None); + assert_eq!(by_choice(r.choice), None); + assert!(!FOLDERS.contains(&r.folder)); + assert!(!all().iter().any(|x| x.item == r.item)); + assert!(!selected(&[r.choice.to_string()]).iter().any(|x| x.item == r.item)); + assert!(!count("seed", 8).iter().any(|x| x.item == r.item)); + assert!(!random("seed").1.iter().any(|x| x.item == r.item)); + assert!(!mode_note(Mode::All, 8, &all()).contains(r.dungeon)); + } + + #[test] + fn seed_derived_subsets_are_stable_and_bounded() { + let a: Vec<&'static Ring> = count("seed", 3); + assert_eq!(a.len(), 3); + assert_eq!(a, count("seed", 3)); + assert_ne!(a, count("other seed", 3)); + let (n, b): (usize, Vec<&'static Ring>) = random("seed"); + assert!((1..=RINGS.len()).contains(&n)); + assert_eq!(b.len(), n); + assert_eq!(b, random("seed").1); + for subset in [&a, &b] { + let mut seen: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new(); + for r in subset { + assert!(seen.insert(r.choice)); + } + } + } + + #[test] + fn manual_selection_keeps_catalog_order() { + let ids: Vec = vec!["ganons_castle".into(), "forest_temple".into()]; + let got: Vec<&'static Ring> = selected(&ids); + assert_eq!(got.iter().map(|r| r.choice).collect::>(), ["forest_temple", "ganons_castle"]); + } +} diff --git a/randomizer/core/src/lib.rs b/randomizer/core/src/lib.rs index 81889511..c9fe3777 100644 --- a/randomizer/core/src/lib.rs +++ b/randomizer/core/src/lib.rs @@ -40,14 +40,20 @@ pub mod entr; pub mod event_chests; pub mod fast; pub mod gerudo_card; +pub mod gerudo_drops; pub mod malon_song; pub mod flow_locations; pub mod flow_extra; pub mod flow_sim; pub mod hints; +pub mod hideout_keys; pub mod intro_skip; pub mod gift_keys; pub mod item_window; +pub mod key_ring_credit; +pub mod key_rings; +pub mod key_ring_text; +pub mod ring_event; pub mod lacs_key; pub mod medal_gate; pub mod nocturne_gate; diff --git a/randomizer/core/src/no_tutorials.rs b/randomizer/core/src/no_tutorials.rs index f883075c..209dd9de 100644 --- a/randomizer/core/src/no_tutorials.rs +++ b/randomizer/core/src/no_tutorials.rs @@ -24,6 +24,9 @@ use crate::staging::{self, Out}; pub const FILE: &str = "Event/EventFlow/ActionGuide.bfevfl.zs"; pub const FLOW: &str = "ActionGuide"; pub const PREFIX: &str = "OOTRRNoGuide"; + + +pub const RING_PREFIX: &str = "OOTRRRingCall"; pub const ENTRIES: [&str; 5] = ["OpenActionGuideSceen", "OpenActionGuideSceenForce", "ActionGuide", "ActionGuideForShop", "OpenActionGuideSceenForOcarina"]; const NONE: u16 = 0xFFFF; const TRUE: u32 = 0x8000_0001; @@ -56,10 +59,12 @@ pub fn start_flags() -> Vec<(String, bool)> { .collect() } -/// Points every entry at one new wait event that ends the flow. Returns the entries changed. -pub fn patch(b: &mut Bf) -> Res { + + + +pub fn patch(b: &mut Bf, rings: bool) -> Res { let f: &mut Flow = b.flows.iter_mut().find(|f| f.name == FLOW).ok_or(Error::Format("no tutorials: no ActionGuide flow"))?; - if f.events.iter().any(|e| e.name.starts_with(PREFIX)) { + if f.events.iter().any(|e| e.name.starts_with(PREFIX) || e.name.starts_with(RING_PREFIX)) { return Err(Error::Format("no tutorials: ActionGuide was already patched")); } let names: Vec<&str> = f.entries.iter().map(|e| e.name.as_str()).collect(); @@ -68,29 +73,43 @@ pub fn patch(b: &mut Bf) -> Res { } let (a, x): (u16, u16) = crate::start_state::slot(f, "EventSystemActor", "EventWait")?; let end: usize = f.events.len(); - if end >= NONE as usize { + let calls: usize = usize::from(rings) * 2; + if end + calls >= NONE as usize { return Err(Error::Format("no tutorials: too many events in the flow")); } - f.events.push(Event { - name: format!("{PREFIX}{end}"), + let wait = |next, name| Event { + name, kind: Kind::Action { - next: NONE, + next, actor: a, act: x, params: Some(Cont { items: vec![("IsWaitEnd".to_string(), Val::Bool(TRUE)), ("Frames".to_string(), Val::Int(1))] }), }, - }); + }; + f.events.push(wait(NONE, format!("{PREFIX}{end}"))); + let (item_get, shop): (u16, u16) = if rings { + let at: u16 = (end + 1) as u16; + f.events.push(wait(end as u16, format!("{RING_PREFIX}ItemGet"))); + f.events.push(wait(end as u16, format!("{RING_PREFIX}ForShop"))); + (at, at + 1) + } else { + (end as u16, end as u16) + }; for e in &mut f.entries { - e.main = end as u16; + e.main = match (rings, e.name.as_str()) { + (true, "ActionGuide") => item_get, + (true, "ActionGuideForShop") => shop, + _ => end as u16, + }; e.subs.clear(); } Ok(f.entries.len()) } -pub fn stage(rf: &mut Romfs) -> Res { +pub fn stage(rf: &mut Romfs, rings: bool) -> Res { staging::rewrite(rf, FILE, |raw| { let mut b: Bf = Bf::parse(raw)?; - patch(&mut b)?; + patch(&mut b, rings)?; let out: Vec = b.write()?; if Bf::parse(&out)? != b { return Err(Error::Format("no tutorials: the patched flow does not parse back")); @@ -102,6 +121,7 @@ pub fn stage(rf: &mut Romfs) -> Res { #[cfg(test)] mod tests { use super::*; + use crate::bfevfl::Actor; #[test] fn a_new_game_marks_the_map_as_picked_up_once_and_every_guide_as_done() { @@ -126,8 +146,8 @@ mod tests { } let mut rf: Romfs = Romfs::open(&p).unwrap(); let mut b: Bf = Bf::parse(&rf.read_zs(FILE).unwrap()).unwrap(); - assert_eq!(patch(&mut b).unwrap(), ENTRIES.len()); - assert!(patch(&mut b).is_err()); + assert_eq!(patch(&mut b, false).unwrap(), ENTRIES.len()); + assert!(patch(&mut b, false).is_err()); let f: &Flow = &b.flows[0]; let end: u16 = f.entries[0].main; assert!(f.entries.iter().all(|e| e.main == end && e.subs.is_empty())); @@ -135,4 +155,91 @@ mod tests { assert_eq!(*next, NONE); assert_eq!(Bf::parse(&b.write().unwrap()).unwrap(), b); } + + fn synthetic() -> Bf { + let waiter: Actor = Actor { + name: "EventSystemActor".to_string(), + sub: String::new(), + arg: String::new(), + actions: vec!["EventWait".to_string()], + queries: Vec::new(), + params: None, + ep: 0, + cut: 0, + }; + let entries: Vec = ENTRIES + .iter() + .map(|e| crate::bfevfl::Entry { + name: e.to_string(), + subs: Vec::new(), + vars: Vec::new(), + main: NONE, + pad: 0, + }) + .collect(); + Bf { + ver: [0; 4], + bom: 0, + shift: 0, + pad: 0, + name: "test".to_string(), + flows: vec![Flow { + name: FLOW.to_string(), + actors: vec![waiter], + events: Vec::new(), + entries, + }], + tls: Vec::new(), + } + } + + fn next(f: &Flow, at: u16) -> u16 { + match f.events[at as usize].kind { + Kind::Action { next, .. } => next, + _ => panic!("{} is not an action", f.events[at as usize].name), + } + } + + fn patched(rings: bool) -> Bf { + let mut b: Bf = synthetic(); + assert_eq!(patch(&mut b, rings).unwrap(), ENTRIES.len()); + b + } + + #[test] + fn without_rings_every_entry_still_shares_one_wait() { + let b: Bf = patched(false); + let f: &Flow = &b.flows[0]; + assert_eq!(f.events.len(), 1); + assert!(f.events[0].name.starts_with(PREFIX)); + let end: u16 = f.entries[0].main; + assert!(f.entries.iter().all(|e| e.main == end && e.subs.is_empty())); + assert_eq!(next(f, end), NONE); + assert_eq!(Bf::parse(&b.write().unwrap()).unwrap(), b); + } + + #[test] + fn rings_keep_separate_item_get_and_shop_call_sites() { + let mut b: Bf = patched(true); + let f: &Flow = &b.flows[0]; + let end: u16 = f.entries.iter().find(|e| e.name == "OpenActionGuideSceen").unwrap().main; + let item: u16 = f.entries.iter().find(|e| e.name == "ActionGuide").unwrap().main; + let shop: u16 = f.entries.iter().find(|e| e.name == "ActionGuideForShop").unwrap().main; + assert_ne!(item, shop); + assert_ne!(item, end); + assert_ne!(shop, end); + assert!(f.events[item as usize].name.starts_with(RING_PREFIX), "{}", f.events[item as usize].name); + assert!(f.events[shop as usize].name.starts_with(RING_PREFIX), "{}", f.events[shop as usize].name); + assert_eq!(next(f, item), end); + assert_eq!(next(f, shop), end); + assert_eq!(next(f, end), NONE); + assert!(f.entries.iter().all(|e| e.subs.is_empty())); + for e in &f.entries { + if !matches!(e.name.as_str(), "ActionGuide" | "ActionGuideForShop") { + assert_eq!(e.main, end, "{} stayed off its own call site", e.name); + } + } + assert_eq!(Bf::parse(&b.write().unwrap()).unwrap(), b); + assert!(patch(&mut b, true).is_err()); + } } diff --git a/randomizer/core/src/open_world/quest_order.rs b/randomizer/core/src/open_world/quest_order.rs index 1ed17de4..e0c2ca40 100644 --- a/randomizer/core/src/open_world/quest_order.rs +++ b/randomizer/core/src/open_world/quest_order.rs @@ -61,6 +61,7 @@ pub struct Late { pub const ZORA_DONE: &str = "SageOfWater_KingZora_adult_Talk_Event198"; pub const CARD_DONE: &str = "HavePlayedEvent.Dm_Gerudo_0025"; pub const CARD_SCENE: &str = "Dm_Gerudo_0025"; +pub const CARD_ONCE_PREFIX: &str = "OOTRRCardOnce"; pub const LATE: [Late; 2] = [ // After the Water Temple, King Zora stands free in the thawed domain and talks through his own @@ -239,6 +240,55 @@ pub fn mark_clear(b: &mut Bf) -> Res<()> { Ok(()) } +fn card_transition(f: &Flow, i: usize) -> bool { + let Kind::Action { actor, act, params, .. } = &f.events[i].kind else { + return false; + }; + let Some(a) = f.actors.get(usize::from(*actor)) else { + return false; + }; + if a.name != MOVER || a.actions.get(usize::from(*act)).map(|s| s.as_str()) != Some(MOVE) { + return false; + } + matches!(params.as_ref().and_then(|p| p.get("EventName")), Some(Val::Str(s)) if s == CARD_SCENE) +} + + + + +pub fn card_once(b: &mut Bf) -> Res { + let f: &mut Flow = guard::flow_mut(b, CLEAR.0)?; + if f.events.iter().any(|e| e.name.starts_with(CARD_ONCE_PREFIX)) { + return Err(Error::Msg(format!("quest order: {} already guards the card scene", CLEAR.0))); + } + let targets: Vec = (0..f.events.len()).filter(|&i| card_transition(f, i)).collect(); + if targets.is_empty() { + return Err(Error::Msg(format!("quest order: {} has no transition to {CARD_SCENE}", CLEAR.0))); + } + let (qa, qi): (u16, u16) = query_slot(f, DATA, BOOL_QUERY)?; + let mut out: Vec = Vec::new(); + for (n, t) in targets.iter().enumerate() { + let old: u16 = guard::idx(*t)?; + let next: u16 = match &f.events[*t].kind { + Kind::Action { next, .. } => *next, + _ => unreachable!(), + }; + let to: u16 = guard::idx(f.events.len())?; + guard::retarget(f, old, to); + let cases: Vec = [(0, next), (1, old)].into_iter().filter(|(_, ev)| *ev != NONE).map(|(val, ev)| Case { val, ev }).collect(); + let name: String = format!("{CARD_ONCE_PREFIX}{n}"); + let params: Cont = Cont { + items: vec![ + ("Index".to_string(), Val::Int(-1)), + ("GameDataName".to_string(), Val::Str(CARD_DONE.to_string())), + ], + }; + f.events.push(Event { name: name.clone(), kind: Kind::Switch { actor: qa, query: qi, cases, params: Some(params) } }); + out.push(f.events[*t].name.clone()); + } + Ok(out.len()) +} + /// Every flow this module edits, each with its edit. pub fn edits() -> Vec<(&'static str, Box Res<()>>)> { let mut flows: Vec<&'static str> = Vec::new(); @@ -259,6 +309,9 @@ pub fn edits() -> Vec<(&'static str, Box Res<()>>)> { .into_iter() .map(|flow| { let edit: Box Res<()>> = Box::new(move |b: &mut Bf| { + if flow == CLEAR.0 { + card_once(b)?; + } for l in LATE.iter().filter(|l| l.flow == flow) { hook(b, l)?; } @@ -400,6 +453,58 @@ mod tests { assert_eq!(back, b); } + fn card_sample() -> Bf { + let actor = |n: &str, acts: &[&str], qs: &[&str]| crate::bfevfl::Actor { + name: n.to_string(), + sub: String::new(), + arg: String::new(), + actions: acts.iter().map(|s| s.to_string()).collect(), + queries: qs.iter().map(|s| s.to_string()).collect(), + params: None, + ep: 0xFFFF, + cut: 1, + }; + let f: Flow = Flow { + name: CLEAR.0.to_string(), + actors: vec![actor(MOVER, &[MOVE], &[]), actor(DATA, &[], &[BOOL_QUERY])], + events: vec![ + Event { name: "Start".to_string(), kind: Kind::Action { next: 1, actor: 0, act: 0, params: None } }, + Event { + name: "Event145".to_string(), + kind: Kind::Action { + next: 2, + actor: 0, + act: 0, + params: Some(Cont { items: vec![("EventName".to_string(), Val::Str(CARD_SCENE.to_string()))] }), + }, + }, + Event { name: "After".to_string(), kind: Kind::Action { next: NONE, actor: 0, act: 0, params: None } }, + ], + entries: vec![ + Entry { name: "Meet_FourCarpenter_ClearEvent".to_string(), subs: Vec::new(), vars: Vec::new(), main: 0, pad: 0 }, + ], + }; + Bf { ver: [0, 4, 0, 0], bom: 0xFEFF, shift: 3, pad: 0, name: CLEAR.0.to_string(), flows: vec![f], tls: Vec::new() } + } + + #[test] + fn the_card_scene_guard_skips_later_unlocks_but_keeps_the_first_grant() { + let mut b: Bf = card_sample(); + assert_eq!(card_once(&mut b).unwrap(), 1); + let f: &Flow = &b.flows[0]; + let Kind::Action { next, .. } = &f.events[0].kind else { panic!() }; + assert_eq!(*next, 3); + assert_eq!(cases(f, 3), vec![(0, 2), (1, 1)]); + assert_eq!(name_of(f, 3), CARD_DONE); + let Kind::Switch { actor, query, params, .. } = &f.events[3].kind else { panic!() }; + assert_eq!(f.actors[*actor as usize].name, DATA); + assert_eq!(f.actors[*actor as usize].queries[*query as usize], BOOL_QUERY); + assert_eq!(params.as_ref().and_then(|p| p.get("Index")), Some(&Val::Int(-1))); + assert!(card_once(&mut b).is_err()); + let back: Bf = Bf::parse(&b.write().unwrap()).unwrap(); + assert_eq!(back, b); + } + #[test] fn every_edit_applies_to_the_game_flows_and_reads_back() { let Some(root) = real() else { diff --git a/randomizer/core/src/pickup_pack.rs b/randomizer/core/src/pickup_pack.rs index 75c0707a..fdb8d5e6 100644 --- a/randomizer/core/src/pickup_pack.rs +++ b/randomizer/core/src/pickup_pack.rs @@ -32,6 +32,20 @@ pub struct Spec { pub name: String, pub style: Style, pub heap: Option, + + pub source: Option, + + pub identity: Option, +} + +impl Spec { + pub fn source(&self) -> &str { + self.source.as_deref().unwrap_or(&self.item) + } + + pub fn identity_override(&self) -> Option<&str> { + self.identity.as_deref() + } } #[derive(Clone, Debug, Default, PartialEq, Eq)] @@ -40,6 +54,16 @@ pub struct Layers { pub ammo: bool, pub magic: bool, pub model: Option, + + + pub pouch_from: Option, + + pub ring: Option, + + + pub drop_ring: bool, + + pub spin: bool, /// With spin: how far, in millimetres, the pickup's body reaches below its origin so that the /// turning item model clears the ground (crate::pickup_pack::lift). The pack builds fill it in. @@ -50,7 +74,7 @@ pub struct Layers { impl Layers { pub fn plain(&self) -> bool { - self.tags.is_empty() && !self.ammo && !self.magic && self.model.is_none() && !self.spin && !self.own + self.tags.is_empty() && !self.ammo && !self.magic && self.model.is_none() && self.pouch_from.is_none() && self.ring.is_none() && !self.drop_ring && !self.spin && !self.own } pub fn kit_ok(&self) -> bool { diff --git a/randomizer/core/src/pickup_pack/actor.rs b/randomizer/core/src/pickup_pack/actor.rs index 305cc00a..e6fea55b 100644 --- a/randomizer/core/src/pickup_pack/actor.rs +++ b/randomizer/core/src/pickup_pack/actor.rs @@ -12,6 +12,10 @@ pub const ANIM_REF: &str = "AnimationRef"; pub const AS_REF: &str = "ASRef"; pub const AS_INFO_REF: &str = "ASInfoRef"; pub const POUCH_REF: &str = "PouchContentRef"; +pub const EVENT_REF: &str = "EventPerformerRef"; + + +pub const EVENT_BASE: &str = "Item_EventObject_Base"; pub const ATTENTION_REF: &str = "AttentionSenderRef"; pub const POUCH_ACTOR: &str = "PouchActor"; pub const FIRST_CHECK: &str = "IsCountCheckOnFirstGet"; @@ -61,6 +65,17 @@ pub fn pouch_file(name: &str) -> String { format!("Component/PouchContentParam/{name}.game__component__PouchContentParam.bgyml") } + +pub fn model_file(name: &str) -> String { + format!("Component/ModelInfo/{name}.engine__component__ModelInfo.bgyml") +} + + + +pub fn event_file(name: &str) -> String { + format!("Component/EventPerformerParam/{name}.engine__component__EventPerformerParam.bgyml") +} + fn need<'a>(c: &'a Chain, who: &str, k: &str) -> Res<&'a str> { c.comps.get(k).map(|s| s.as_str()).ok_or_else(|| E::Msg(format!("{who} has no {k}, this template cannot carry it"))) } @@ -88,11 +103,12 @@ pub fn fits(p: &Pool, s: &Spec) -> Res> { } pub fn fits_with(p: &Pool, s: &Spec, l: &Layers) -> Res> { - let item: Chain = chain(p, &s.item)?; + let source: &str = s.source(); + let item: Chain = chain(p, source)?; let donor: Chain = chain(p, DONOR)?; let mut bad: Vec = Vec::new(); if item.files.contains(&actor_file(BASE)) { - bad.push(format!("{} is already a world pickup", s.item)); + bad.push(format!("{source} is already a world pickup")); } if let Some(m) = &l.model { if let Err(e) = model::model_ref(p, m) { @@ -100,8 +116,8 @@ pub fn fits_with(p: &Pool, s: &Spec, l: &Layers) -> Res> { } for k in [NAME_REF, POUCH_REF] { match item.comps.get(k) { - None => bad.push(format!("{} has no {k}", s.item)), - Some(v) if k != NAME_REF && held(p, &s.item, k, v).is_err() => bad.push(format!("{} keeps its {k} outside its pack", s.item)), + None => bad.push(format!("{source} has no {k}")), + Some(v) if k != NAME_REF && held(p, source, k, v).is_err() => bad.push(format!("{source} keeps its {k} outside its pack")), Some(_) => {} } } @@ -109,13 +125,13 @@ pub fn fits_with(p: &Pool, s: &Spec, l: &Layers) -> Res> { } for k in [NAME_REF, MODEL_REF, ANIM_REF, POUCH_REF] { match item.comps.get(k) { - None => bad.push(format!("{} has no {k}", s.item)), - Some(v) if k != NAME_REF && held(p, &s.item, k, v).is_err() => bad.push(format!("{} keeps its {k} outside its pack", s.item)), + None => bad.push(format!("{source} has no {k}")), + Some(v) if k != NAME_REF && held(p, source, k, v).is_err() => bad.push(format!("{source} keeps its {k} outside its pack")), Some(_) => {} } } if item.comps.get(AS_REF) != donor.comps.get(AS_REF) && !shared_anim(p, &item) { - bad.push(format!("{} does not use the animation set of the shipped pickups", s.item)); + bad.push(format!("{source} does not use the animation set of the shipped pickups")); } Ok(bad) } @@ -127,6 +143,9 @@ fn actor_in(r: &str) -> Option { } pub fn identity(p: &Pool, s: &Spec, item: &Chain, pouch: &str) -> Res { + if let Some(id) = s.identity_override() { + return Ok(id.to_string()); + } let mut seen: Vec = Vec::new(); let mut cur: Option = Some(pouch.to_string()); while let Some(f) = cur { @@ -147,13 +166,74 @@ pub fn make(p: &Pool, s: &Spec) -> Res { make_with(p, s, &Layers::default()) } + + + + + +fn make_event_ring(p: &Pool, s: &Spec, l: &Layers) -> Res { + let source: &str = s.source(); + let item: Chain = chain(p, source)?; + let pouch_source: &str = l.pouch_from.as_deref().ok_or_else(|| E::Msg("a key ring needs a --pouch-from key item".to_string()))?; + let pouch_chain: Chain = chain(p, pouch_source)?; + let who: &str = l.ring.as_deref().ok_or_else(|| E::Msg("a key ring needs a --ring identity".to_string()))?; + let version: u16 = p.byml(&actor_file(source))?.version; + + let key_model: String = held(p, source, MODEL_REF, need(&item, source, MODEL_REF)?)?; + let model: String = model_file(&s.name); + let model_data: Vec = p.get(&key_model).ok_or_else(|| E::Msg(format!("{source} model {key_model} is missing")))?.to_vec(); + let event: String = event_file(&s.name); + let pouch: String = pouch_file(&s.name); + let pouch_base: String = held(p, pouch_source, POUCH_REF, need(&pouch_chain, pouch_source, POUCH_REF)?)?; + + + + let pouch_data: Vec = p.get(&pouch_base).ok_or_else(|| E::Msg(format!("{pouch_source} pouch {pouch_base} is missing")))?.to_vec(); + let elink: String = held(p, pouch_source, ELINK_REF, need(&pouch_chain, pouch_source, ELINK_REF)?)?; + + let mut performer: Node = Node::Map(Vec::new()); + performer.set("EventUniqueAin", Node::Str(work(&format!("AI/Root/Event/{who}.event.root.ain")))); + performer.set("UseEventUniqueAin", Node::Bool(true)); + + let mut comps: Node = Node::Map(Vec::new()); + comps.set(AS_REF, Node::Str(need(&pouch_chain, pouch_source, AS_REF)?.to_string())); + comps.set(NAME_REF, Node::Str(format!("?ActorSystem/ActorName/{who}.engine__actor__ActorName.bgyml"))); + comps.set(ANIM_REF, Node::Str(need(&pouch_chain, pouch_source, ANIM_REF)?.to_string())); + comps.set(ELINK_REF, Node::Str(local(&elink))); + comps.set(EVENT_REF, Node::Str(local(&event))); + comps.set(MODEL_REF, Node::Str(local(&model))); + comps.set(POUCH_REF, Node::Str(local(&pouch))); + + let mut actor: Node = Node::Map(Vec::new()); + actor.set(PARENT, Node::Str(work(&actor_file(EVENT_BASE)))); + actor.set(COMPONENTS, comps); + Ok(Made { + actor: (actor_file(&s.name), Byml { root: actor, version, big: false }.write()?), + pouch: (pouch.clone(), pouch_data), + identity: who.to_string(), + extra: vec![ + (event, Byml { root: performer, version, big: false }.write()?), + (model, model_data), + ], + }) +} + pub fn make_with(p: &Pool, s: &Spec, l: &Layers) -> Res { - let item: Chain = chain(p, &s.item)?; + if l.ring.is_some() && !l.drop_ring { + return make_event_ring(p, s, l); + } + + + + let source: &str = s.source(); + let item: Chain = chain(p, source)?; let donor: Chain = chain(p, DONOR)?; if let Some(m) = fits_with(p, s, l)?.first() { return Err(E::Msg(format!("{m}, so the thin pickup template does not fit"))); } - let item_pouch: String = held(p, &s.item, POUCH_REF, need(&item, &s.item, POUCH_REF)?)?; + let pouch_source: &str = l.pouch_from.as_deref().unwrap_or(source); + let pouch_chain: Chain = if pouch_source == source { item.clone() } else { chain(p, pouch_source)? }; + let item_pouch: String = held(p, pouch_source, POUCH_REF, need(&pouch_chain, pouch_source, POUCH_REF)?)?; let version: u16 = p.byml(&actor_file(DONOR))?.version; let pouch_path: String = pouch_file(&s.name); let mut comps: Node = Node::Map(Vec::new()); @@ -170,11 +250,20 @@ pub fn make_with(p: &Pool, s: &Spec, l: &Layers) -> Res { comps.set(AS_INFO_REF, Node::Str(need(&donor, DONOR, AS_INFO_REF)?.to_string())); } comps.set(AS_REF, Node::Str(need(&donor, DONOR, AS_REF)?.to_string())); - if l.own || s.name.starts_with(crate::slice::key_spots::DUNGEON_PREFIX) { - comps.set(NAME_REF, Node::Str(own_name_ref(&s.name))); - } else { - comps.set(NAME_REF, Node::Str(need(&item, &s.item, NAME_REF)?.to_string())); - } + let name_ref: String = match l.ring.as_deref() { + Some(who) => own_name_ref(who), + None if l.own || s.name.starts_with(crate::slice::key_spots::DUNGEON_PREFIX) => { + + + own_name_ref(&s.name) + } + None => need(&item, source, NAME_REF)?.to_string(), + }; + comps.set(NAME_REF, Node::Str(name_ref)); + + + + match &l.model { Some(m) => { let (r, f, b): (String, String, Vec) = model::anim(&s.name, version, l.pose.as_deref())?; @@ -183,8 +272,8 @@ pub fn make_with(p: &Pool, s: &Spec, l: &Layers) -> Res { extra.push((f, b)); } None => { - comps.set(ANIM_REF, Node::Str(need(&item, &s.item, ANIM_REF)?.to_string())); - comps.set(MODEL_REF, Node::Str(need(&item, &s.item, MODEL_REF)?.to_string())); + comps.set(ANIM_REF, Node::Str(need(&item, source, ANIM_REF)?.to_string())); + comps.set(MODEL_REF, Node::Str(need(&item, source, MODEL_REF)?.to_string())); } } comps.set(POUCH_REF, Node::Str(local(&pouch_path))); @@ -192,10 +281,10 @@ pub fn make_with(p: &Pool, s: &Spec, l: &Layers) -> Res { comps.set(ATTENTION_REF, Node::Str(need(&donor, DONOR, ATTENTION_REF)?.to_string())); } if l.magic { - if meter::applies(&s.item) { - return Err(E::Msg(format!("{} gives no magic meter, the magic layer would add the raise back", s.item))); + if meter::applies(s.source()) { + return Err(E::Msg(format!("{} gives no magic meter, the magic layer would add the raise back", s.source()))); } - let (f, d, r): (String, Vec, String) = magic::make(p, &item, &chain(p, BASE)?, &s.item, &s.name)?; + let (f, d, r): (String, Vec, String) = magic::make(p, &item, &chain(p, BASE)?, s.source(), &s.name)?; comps.set(magic::TABLE_REF, Node::Str(r)); extra.push((f, d)); } @@ -317,7 +406,7 @@ pub(crate) mod tests { } pub(crate) fn spec(style: Style) -> Spec { - Spec { item: "Item_Test".to_string(), name: "Obj_Test".to_string(), style, heap: None } + Spec { item: "Item_Test".to_string(), name: "Obj_Test".to_string(), style, heap: None, source: None, identity: None } } #[test] @@ -394,11 +483,11 @@ pub(crate) mod tests { ]), )]); p.add(&actor_file("Item_Odd"), &odd).unwrap(); - let sp: Spec = Spec { item: "Item_Odd".to_string(), name: "Obj_Odd".to_string(), style: Style::Touch, heap: None }; + let sp: Spec = Spec { item: "Item_Odd".to_string(), name: "Obj_Odd".to_string(), style: Style::Touch, heap: None, source: None, identity: None }; let bad: Vec = fits(&p, &sp).unwrap(); assert_eq!(bad.len(), 3); assert!(make(&p, &sp).is_err()); - let own: Spec = Spec { item: DONOR.to_string(), name: "Obj_Twice".to_string(), style: Style::Touch, heap: None }; + let own: Spec = Spec { item: DONOR.to_string(), name: "Obj_Twice".to_string(), style: Style::Touch, heap: None, source: None, identity: None }; assert!(fits(&p, &own).unwrap().iter().any(|m| m.contains("already a world pickup"))); } @@ -424,7 +513,7 @@ pub(crate) mod tests { ]), )]); p.add(&actor_file(name), &y).unwrap(); - Spec { item: name.to_string(), name: format!("Obj_{name}"), style: Style::Touch, heap: None } + Spec { item: name.to_string(), name: format!("Obj_{name}"), style: Style::Touch, heap: None, source: None, identity: None } } #[test] diff --git a/randomizer/core/src/pickup_pack/build.rs b/randomizer/core/src/pickup_pack/build.rs index b6f044d8..c6aaf518 100644 --- a/randomizer/core/src/pickup_pack/build.rs +++ b/randomizer/core/src/pickup_pack/build.rs @@ -1,8 +1,10 @@ use std::collections::BTreeSet as BS; use crate::error::{Error as E, Res}; -use crate::pickup_pack::actor::{make_with, Made}; -use crate::pickup_pack::closure::{chain, dangling_with, is_byml, select, Chain, Pool}; +use crate::pickup_pack::actor::{make_with, Made, EVENT_REF}; +use crate::pickup_pack::closure::{chain, dangling_with, is_byml, select_with, Chain, Pool}; +#[cfg(test)] +use crate::pickup_pack::closure::select; use crate::pickup_pack::{is_actor_name, Layers, Spec}; use crate::sarc::{self, Entry}; @@ -24,30 +26,52 @@ pub fn pool_of(packs: &[Vec]) -> Res { Ok(p) } + + + +pub fn extra_roots(p: &Pool, l: &Layers) -> Res> { + if l.ring.is_none() || l.drop_ring { + return Ok(Vec::new()); + } + let base: Chain = chain(p, crate::pickup_pack::actor::EVENT_BASE)?; + Ok(base.comps.get(EVENT_REF).cloned().into_iter().collect()) +} + pub fn plan(packs: &[Vec], s: &Spec) -> Res { plan_with(packs, s, &Layers::default()) } pub fn plan_with(packs: &[Vec], s: &Spec, l: &Layers) -> Res { - if !is_actor_name(&s.name) || !is_actor_name(&s.item) { - return Err(E::Msg(format!("{} or {} is not a plain actor name", s.name, s.item))); + plan_with_files(packs, s, l, &[]) +} + +pub fn plan_with_files(packs: &[Vec], s: &Spec, l: &Layers, extra: &[(String, Vec)]) -> Res { + if !is_actor_name(&s.name) || !is_actor_name(&s.item) || !is_actor_name(s.source()) || s.identity.as_deref().is_some_and(|id| !is_actor_name(id)) { + return Err(E::Msg(format!("{}, {} or an override is not a plain actor name", s.name, s.item))); } let mut p: Pool = pool_of(packs)?; let peers: Vec<(String, usize)> = p.files.iter().map(|e| (e.0.clone(), e.1.len())).collect(); + + + let made: BS<&str> = extra.iter().map(|(f, _)| f.as_str()).collect(); let m: Made = make_with(&p, s, l)?; - let m: Made = if l.spin { crate::pickup_pack::lift::ground(&p, m, &s.name, l.lift)? } else { m }; + + + let lifted: bool = l.spin && (l.ring.is_none() || l.drop_ring); + let m: Made = if lifted { crate::pickup_pack::lift::ground(&p, m, &s.name, l.lift)? } else { m }; let mut fresh: Vec<(String, usize)> = Vec::new(); - for (f, d) in [&m.actor, &m.pouch].into_iter().chain(m.extra.iter()) { + for (f, d) in [&m.actor, &m.pouch].into_iter().chain(m.extra.iter()).chain(extra.iter()) { if p.get(f).is_some() { return Err(E::Msg(format!("{f} already exists, {} is taken", s.name))); } p.add(f, d)?; fresh.push((f.clone(), d.len())); } - let files: Vec = select(&p, &s.name)?; + let carry: Vec = extra_roots(&p, l)?; + let files: Vec = select_with(&p, &s.name, &carry)?; // Only the files the new pickup reaches go into its pack; a graph file the item's own pack // carries (its AI) is never reached through the thin template. - if let Some(f) = files.iter().find(|f| p.get(f).is_some_and(|d| !is_byml(d))) { + if let Some(f) = files.iter().find(|f| !made.contains(f.as_str()) && p.get(f).is_some_and(|d| !is_byml(d))) { return Err(E::Msg(format!("{f} is not a parameter file, an item whose pack carries graph or binary files needs a hand made template"))); } if let Some((f, _)) = fresh.iter().find(|f| !files.contains(&f.0)) { @@ -219,7 +243,7 @@ mod tests { }; let mut rf: Romfs = Romfs::open(&root).unwrap(); let src: Vec> = vec![load(&mut rf, BASE), load(&mut rf, DONOR), load(&mut rf, "Item_Hookshot")]; - let s: Spec = Spec { item: "Item_Hookshot".to_string(), name: "Obj_Hookshot".to_string(), style: Style::Touch, heap: None }; + let s: Spec = Spec { item: "Item_Hookshot".to_string(), name: "Obj_Hookshot".to_string(), style: Style::Touch, heap: None, source: None, identity: None }; let pl: Plan = plan(&src, &s).unwrap(); let base: BS = src[0].iter().map(|e| e.name.clone()).collect(); let got: BS = pl.files.iter().cloned().collect(); @@ -274,7 +298,7 @@ mod tests { fn pouch_of(rf: &mut Romfs, item: &str, name: &str) -> (Plan, Option, Option) { let src: Vec> = vec![load(rf, BASE), load(rf, DONOR), load(rf, item)]; - let s: Spec = Spec { item: item.to_string(), name: name.to_string(), style: Style::Touch, heap: None }; + let s: Spec = Spec { item: item.to_string(), name: name.to_string(), style: Style::Touch, heap: None, source: None, identity: None }; let pl: Plan = plan(&src, &s).unwrap(); let back: Vec = sarc::parse(&pl.sarc).unwrap(); let q: Byml = Byml::parse(&sarc::get(&back, &pouch_file(name)).unwrap().data).unwrap(); diff --git a/randomizer/core/src/pickup_pack/catalog.rs b/randomizer/core/src/pickup_pack/catalog.rs index 327a983d..d7dc8228 100644 --- a/randomizer/core/src/pickup_pack/catalog.rs +++ b/randomizer/core/src/pickup_pack/catalog.rs @@ -113,7 +113,7 @@ pub fn load() -> Res> { } pub fn spec(item: &str, a: &[String]) -> Res<(Spec, Layers)> { - let mut s: Spec = Spec { item: item.to_string(), name: default_name(item), style: Style::Touch, heap: None }; + let mut s: Spec = Spec { item: item.to_string(), name: default_name(item), style: Style::Touch, heap: None, source: None, identity: None }; let mut l: Layers = Layers::default(); let mut i: usize = 0; while i < a.len() { @@ -150,10 +150,40 @@ pub fn spec(item: &str, a: &[String]) -> Res<(Spec, Layers)> { l.model = Some(v.to_string()); 2 } + ("--pouch-from", Some(v)) => { + if !crate::pickup_pack::is_actor_name(v) { + return Err(E::Msg(format!("pickup pack catalog: {v} is not a plain actor name"))); + } + l.pouch_from = Some(v.to_string()); + 2 + } + ("--ring", Some(v)) => { + if !crate::pickup_pack::is_actor_name(v) { + return Err(E::Msg(format!("pickup pack catalog: {v} is not a plain actor name"))); + } + l.ring = Some(v.to_string()); + 2 + } + ("--drop-ring", Some(v)) => { + if !crate::pickup_pack::is_actor_name(v) { + return Err(E::Msg(format!("pickup pack catalog: {v} is not a plain actor name"))); + } + l.ring = Some(v.to_string()); + l.drop_ring = true; + 2 + } ("--heap", Some(v)) => { s.heap = Some(v.parse().map_err(|_| E::Msg(format!("pickup pack catalog: {v} is not a heap size")))?); 2 } + ("--source", Some(v)) => { + s.source = Some(v.to_string()); + 2 + } + ("--identity", Some(v)) => { + s.identity = Some(v.to_string()); + 2 + } (x, _) => return Err(E::Msg(format!("pickup pack catalog: {x} is not a pack option or lacks its value"))), }; i += step; @@ -239,11 +269,11 @@ mod tests { #[test] fn the_options_of_an_entry_become_a_spec_and_its_layers() { let (s, l): (Spec, Layers) = spec("Item_Hookshot", &strs(&["--heap", "199928", "--host", "hookshot"])).unwrap(); - assert_eq!(s, Spec { item: "Item_Hookshot".to_string(), name: "Obj_Hookshot".to_string(), style: Style::Touch, heap: Some(199928) }); + assert_eq!(s, Spec { item: "Item_Hookshot".to_string(), name: "Obj_Hookshot".to_string(), style: Style::Touch, heap: Some(199928), source: None, identity: None }); assert!(l.plain()); let (s, l): (Spec, Layers) = spec("Item_Bottle_Letter", &strs(&["--name", "Obj_Bottle_LetterLand", "--tag", "LetterBottle", "--tag", "LetterBottle"])).unwrap(); assert_eq!(s.name, "Obj_Bottle_LetterLand"); - assert_eq!(l, Layers { tags: strs(&["LetterBottle"]), ammo: false, magic: false, model: None, spin: false, lift: 0, own: false, pose: None }); + assert_eq!(l, Layers { tags: strs(&["LetterBottle"]), ammo: false, magic: false, model: None, pouch_from: None, ring: None, drop_ring: false, spin: false, lift: 0, own: false, pose: None }); let (s, l): (Spec, Layers) = spec("Item_Range_Bow", &strs(&["--ammo", "--magic", "--press"])).unwrap(); assert_eq!(s.style, Style::Press); assert!(l.ammo && l.magic); @@ -252,6 +282,47 @@ mod tests { assert!(spec("Item_Hookshot", &strs(&["--heap", "big"])).is_err()); } + #[test] + fn key_ring_entries_split_the_template_from_the_saved_identity() { + let all: Vec = load().unwrap(); + for r in crate::key_rings::all_with_hideout() { + let e: &Entry = all.iter().find(|e| e.item == r.actor).unwrap(); + assert_eq!(e.status, Status::Built, "{}", r.actor); + assert_eq!(e.identity.as_deref(), Some(r.actor), "{}", r.actor); + let (s, l): (Spec, Layers) = spec(&e.item, &e.args).unwrap(); + assert_eq!(s.item, r.actor, "{}", r.actor); + assert_eq!(s.name, e.pack.clone().unwrap(), "{}", r.actor); + assert_eq!(s.name, crate::key_rings::pack(r.actor), "{}", r.actor); + assert_eq!(s.source(), "Item_Dungeon_SmallKey", "{}", r.actor); + assert_eq!(s.identity_override(), Some(r.actor), "{}", r.actor); + assert_eq!(l.pouch_from.as_deref(), Some("Item_Medal_Forest"), "{}", r.actor); + assert_eq!(l.ring.as_deref(), Some(r.actor), "{}", r.actor); + assert!(!l.plain(), "{}", r.actor); + } + } + + #[test] + fn drop_ring_entries_keep_the_saved_ring_but_use_a_world_pickup_body() { + let all: Vec = load().unwrap(); + for r in crate::key_rings::all_with_hideout() { + let e: &Entry = all.iter().find(|e| e.item == r.drop_item).unwrap(); + assert_eq!(e.status, Status::Built, "{}", r.drop_item); + assert_eq!(e.identity.as_deref(), Some(r.actor), "{}", r.drop_item); + let (s, l): (Spec, Layers) = spec(&e.item, &e.args).unwrap(); + assert_eq!(s.item, r.drop_item, "{}", r.drop_item); + assert_eq!(s.name, e.pack.clone().unwrap(), "{}", r.drop_item); + assert_eq!(s.name, r.drop_actor, "{}", r.drop_item); + assert_eq!(s.source(), "Item_Dungeon_SmallKey", "{}", r.drop_item); + assert_eq!(s.identity_override(), Some(r.actor), "{}", r.drop_item); + assert_eq!(l.pouch_from.as_deref(), Some("Item_Medal_Forest"), "{}", r.drop_item); + assert_eq!(l.ring.as_deref(), Some(r.actor), "{}", r.drop_item); + assert!(l.drop_ring, "{}", r.drop_item); + assert!(!l.plain(), "{}", r.drop_item); + } + let (_, event): (Spec, Layers) = spec("Item_Ring_Forest", &strs(&["--ring", "Item_Ring_Forest"])).unwrap(); + assert!(!event.drop_ring); + } + #[test] fn a_broken_catalog_is_refused() { let one: &str = r#"{"group":"A","item":"Item_X","pack":"Obj_X","args":[],"status":"built","identity":"Item_X","notes":""}"#; @@ -285,8 +356,16 @@ mod tests { let d: Done = run_with(&root, P::new("unused"), "unused", &s, &o, &l).unwrap_or_else(|x| panic!("{} {a:?}: {x}", e.item)); assert!(d.root.is_none(), "{}", e.item); assert_eq!(d.files[0].path, pack_of(&s.name), "{}", e.item); - assert_eq!(Some(written(&d, &s.name)), e.identity, "{} {a:?}", e.item); - assert!(d.report.contains("stays collected once taken"), "{}", e.item); + + + let identity: String = if l.ring.is_some() { + s.identity_override().unwrap().to_string() + } else { + written(&d, &s.name) + }; + assert_eq!(Some(identity.as_str()), e.identity.as_deref(), "{} {a:?}", e.item); + let guard: &str = if l.ring.is_some() && !l.drop_ring { "is a saved key item" } else { "stays collected once taken" }; + assert!(d.report.contains(guard), "{} {:?}: {}", e.item, a, d.report); let again: Done = run_with(&root, P::new("unused"), "unused", &s, &o, &l).unwrap(); assert!(same(&d, &again), "{} {a:?}", e.item); } diff --git a/randomizer/core/src/pickup_pack/closure.rs b/randomizer/core/src/pickup_pack/closure.rs index 2bcec06c..4cc49ff5 100644 --- a/randomizer/core/src/pickup_pack/closure.rs +++ b/randomizer/core/src/pickup_pack/closure.rs @@ -141,11 +141,16 @@ pub fn chain(p: &Pool, actor: &str) -> Res { Ok(Chain { files, comps }) } -pub fn select(p: &Pool, actor: &str) -> Res> { + + + + +pub fn select_with(p: &Pool, actor: &str, extra: &[String]) -> Res> { let c: Chain = chain(p, actor)?; let mut seen: BS = c.files.iter().cloned().collect(); let mut todo: Vec = Vec::new(); let mut found: Vec = c.comps.values().cloned().collect(); + found.extend(extra.iter().cloned()); loop { for s in found.drain(..) { let Some(t) = norm(&s) else { @@ -167,6 +172,10 @@ pub fn select(p: &Pool, actor: &str) -> Res> { Ok(seen.into_iter().collect()) } +pub fn select(p: &Pool, actor: &str) -> Res> { + select_with(p, actor, &[]) +} + pub fn dangling(p: &Pool, files: &[String], known: &BS) -> Res> { let c: Chain = Chain { files: Vec::new(), comps: BM::new() }; dangling_with(p, files, known, &c) @@ -282,6 +291,13 @@ mod tests { assert_eq!(got, want); } + #[test] + fn extra_roots_keep_a_part_the_child_replaced() { + let got: Vec = select_with(&pool(), "Kid", &["?Component/ModelInfo/Dummy.bgyml".to_string()]).unwrap(); + assert!(got.contains(&"Component/ModelInfo/Dummy.bgyml".to_string())); + assert!(got.contains(&"Component/ModelInfo/Kid.bgyml".to_string())); + } + #[test] fn a_reference_to_a_known_file_left_out_is_reported() { let p: Pool = pool(); diff --git a/randomizer/core/src/pickup_pack/guard.rs b/randomizer/core/src/pickup_pack/guard.rs index 224706c8..6892f9b6 100644 --- a/randomizer/core/src/pickup_pack/guard.rs +++ b/randomizer/core/src/pickup_pack/guard.rs @@ -55,7 +55,7 @@ mod tests { } fn built(root: &P) -> Done { - let s: Spec = Spec { item: "Item_Hookshot".to_string(), name: "Obj_Hookshot".to_string(), style: Style::Touch, heap: None }; + let s: Spec = Spec { item: "Item_Hookshot".to_string(), name: "Obj_Hookshot".to_string(), style: Style::Touch, heap: None, source: None, identity: None }; let o: Opts = Opts { host: Host::Hookshot, base: None, rst_from: None, places: Vec::new(), dry: true }; run(root, P::new("unused"), "unused", &s, &o).unwrap() } diff --git a/randomizer/core/src/pickup_pack/kit.rs b/randomizer/core/src/pickup_pack/kit.rs index f37f0e23..30f39c9c 100644 --- a/randomizer/core/src/pickup_pack/kit.rs +++ b/randomizer/core/src/pickup_pack/kit.rs @@ -233,8 +233,8 @@ pub fn plan_with(packs: &[Vec], s: &Spec, l: &Layers) -> Res { if !l.kit_ok() { return Err(E::Format("pickup kit: only the model layer can ride on a kit")); } - if !is_actor_name(&s.name) || !is_actor_name(&s.item) { - return Err(E::Msg(format!("{} or {} is not a plain actor name", s.name, s.item))); + if !is_actor_name(&s.name) || !is_actor_name(&s.item) || s.identity.as_deref().is_some_and(|id| !is_actor_name(id)) { + return Err(E::Msg(format!("{}, {} or an override is not a plain actor name", s.name, s.item))); } if s.style == Style::Press { return Err(E::Format("pickup kit: the press style is not built for kit pickups, a kit is always taken by touch and falls to the floor, so that it can be reached below a wall or vine skulltula")); @@ -622,8 +622,8 @@ pub fn run(romfs: &P, load: &P, mod_name: &str, s: &Spec, o: &Opts, drops: &[u64 } pub fn run_with(romfs: &P, load: &P, mod_name: &str, s: &Spec, o: &Opts, drops: &[u64], l: &Layers) -> Res { - if !is_actor_name(&s.name) || !is_actor_name(&s.item) { - return Err(E::Msg(format!("{} or {} is not a plain actor name", s.name, s.item))); + if !is_actor_name(&s.name) || !is_actor_name(&s.item) || s.identity.as_deref().is_some_and(|id| !is_actor_name(id)) { + return Err(E::Msg(format!("{}, {} or an override is not a plain actor name", s.name, s.item))); } if !o.places.is_empty() { return Err(E::Format("pickup kit: a kit pickup is only for skulltula drops, at a placed spot it would write the saved rows of no skulltula")); @@ -787,7 +787,7 @@ mod tests { } fn kit(item: &str) -> Spec { - Spec { item: item.to_string(), name: default_kit(item), style: Style::Touch, heap: None } + Spec { item: item.to_string(), name: default_kit(item), style: Style::Touch, heap: None, source: None, identity: None } } fn temp(tag: &str) -> PB { @@ -851,7 +851,7 @@ mod tests { #[test] fn a_shipped_pickup_kit_is_a_thin_child_with_its_own_pouch_file() { - let sp: Spec = Spec { item: DONOR.to_string(), name: name_of(DONOR), style: Style::Touch, heap: None }; + let sp: Spec = Spec { item: DONOR.to_string(), name: name_of(DONOR), style: Style::Touch, heap: None, source: None, identity: None }; let mut packs: Vec> = toy_packs(); packs[0].push(Entry { name: pouch_file(DONOR), data: file(&[("A", Node::Bool(true))]) }); let i: usize = packs[0].iter().position(|e| e.name == actor_file(DONOR)).unwrap(); @@ -894,7 +894,7 @@ mod tests { } fn own_parts(packs: &[Vec]) -> (Vec, Option) { - let sp: Spec = Spec { item: "Obj_Soft".to_string(), name: "Obj_Soft_GS".to_string(), style: Style::Touch, heap: None }; + let sp: Spec = Spec { item: "Obj_Soft".to_string(), name: "Obj_Soft_GS".to_string(), style: Style::Touch, heap: None, source: None, identity: None }; let pl: Plan = plan(packs, &sp).unwrap(); let es: Vec = sarc::parse(&pl.sarc).unwrap(); let a: Byml = Byml::parse(&sarc::get(&es, &actor_file(&sp.name)).unwrap().data).unwrap(); @@ -930,7 +930,7 @@ mod tests { #[test] fn the_token_a_press_kit_a_taken_name_and_a_foreign_binary_are_refused() { - let tok: Spec = Spec { item: TOKEN.to_string(), name: "Obj_Token_Gold_GS".to_string(), style: Style::Touch, heap: None }; + let tok: Spec = Spec { item: TOKEN.to_string(), name: "Obj_Token_Gold_GS".to_string(), style: Style::Touch, heap: None, source: None, identity: None }; assert!(plan(&toy_packs(), &tok).is_err()); assert!(plan(&toy_packs(), &Spec { style: Style::Press, ..kit_spec() }).is_err()); assert!(plan(&toy_packs(), &Spec { name: "Item_Test".to_string(), ..kit_spec() }).is_err()); diff --git a/randomizer/core/src/pickup_pack/lift.rs b/randomizer/core/src/pickup_pack/lift.rs index 0a7ed06a..9b45296b 100644 --- a/randomizer/core/src/pickup_pack/lift.rs +++ b/randomizer/core/src/pickup_pack/lift.rs @@ -79,7 +79,7 @@ pub fn layers(rf: &mut Romfs, item: &str, l: &Layers) -> Res { pub fn for_pack(t: &Byml, pack: &str) -> Option { let p: crate::slice::key_spots::Pick = pick_of(pack)?; let (s, l) = p.spec().ok()?; - let mm: u32 = lift_of(t, l.model.as_deref().unwrap_or(&s.item)); + let mm: u32 = lift_of(t, l.model.as_deref().unwrap_or(s.source())); (mm > 0).then_some(mm as f32 / 1000.0) } diff --git a/randomizer/core/src/pickup_pack/sizes.rs b/randomizer/core/src/pickup_pack/sizes.rs index d3205ce8..c8fed3d3 100644 --- a/randomizer/core/src/pickup_pack/sizes.rs +++ b/randomizer/core/src/pickup_pack/sizes.rs @@ -27,6 +27,12 @@ pub fn file_size(rst: &Rst, peers: &[(String, usize)], path: &str, len: usize) - u32::try_from(align(len as u64 + over) + FILE_MARGIN).map_err(|_| E::Format("file size does not fit in 32 bits")) } + + +pub fn event_size(len: usize) -> Res { + u32::try_from(align(len as u64) + FILE_MARGIN).map_err(|_| E::Format("event size does not fit in 32 bits")) +} + #[cfg(test)] mod tests { use super::*; diff --git a/randomizer/core/src/pickup_pack/write.rs b/randomizer/core/src/pickup_pack/write.rs index 6e910899..80b21226 100644 --- a/randomizer/core/src/pickup_pack/write.rs +++ b/randomizer/core/src/pickup_pack/write.rs @@ -1,4 +1,4 @@ -use std::collections::BTreeMap as BM; +use std::collections::{BTreeMap as BM, BTreeSet as BS}; use std::fmt::Write as W; use std::fs; use std::path::{Path as P, PathBuf as PB}; @@ -9,8 +9,8 @@ use crate::flow_locations::dict_id; use crate::modpack::{Host, Pack}; use crate::pickup_pack::actor::pouch_file; use crate::pickup_pack::ammo; -use crate::pickup_pack::build::{plan_with, pool_of, Plan}; -use crate::pickup_pack::closure::{actor_file, chain, select, texts, Pool}; +use crate::pickup_pack::build::{extra_roots, plan_with_files, pool_of, Plan}; +use crate::pickup_pack::closure::{actor_file, chain, select_with, texts, Pool}; use crate::pickup_pack::guard; use crate::pickup_pack::magic; use crate::pickup_pack::meter; @@ -102,35 +102,49 @@ pub(crate) fn table(rf: &mut Romfs, o: &Opts, modded: bool, path: &str, edit: im } pub(crate) fn tables(rf: &mut Romfs, o: &Opts, modded: bool, s: &Spec, l: &Layers, identity: &str) -> Res<(Vec, i32)> { + let source: &str = s.source(); let seen: Byml = Byml::parse(&start(rf, o.base.as_ref(), ACTOR_INFO)?)?; - let own: i32 = rows::own_heap(&seen, &s.item)?; + let own: i32 = rows::own_heap(&seen, source)?; let heap: i32 = match s.heap { - Some(h) if h < own => return Err(E::Msg(format!("the heap {h} is below the {own} that {} needs by itself", s.item))), + Some(h) if h < own => return Err(E::Msg(format!("the heap {h} is below the {own} that {source} needs by itself"))), Some(h) => h, - None => rows::heap(&seen, &s.item)?, + None => rows::heap(&seen, source)?, }; let mut at: [usize; 2] = [0, 0]; let a: File = table(rf, o, modded, ACTOR_INFO, |y: &mut Byml| { - let mut r: Node = rows::actor_row(rows::need(y, &s.item, ACTOR_INFO)?, &s.name, heap); + let mut r: Node = rows::actor_row(rows::need(y, source, ACTOR_INFO)?, &s.name, heap); if let Some(m) = &l.model { crate::pickup_pack::model::row(&mut r, rows::need(y, m, ACTOR_INFO)?, l.pose.as_deref())?; } - if l.own { + if l.ring.is_some() { + + + + + r.set("ActorName", Node::Str(identity.to_string())); + if let Some(elink) = l.pouch_from.as_deref() { + r.set("ELinkUserName", Node::Str(elink.to_string())); + } + } else if l.own { r.set(rows::ACTOR_NAME, Node::Str(s.name.clone())); } at[0] = rows::insert(y, r)?; Ok(()) })?; let g: File = table(rf, o, modded, GAME_ACTOR_INFO, |y: &mut Byml| { - let r: Node = rows::game_row(rows::need(y, BASE, GAME_ACTOR_INFO)?, rows::need(y, &s.item, GAME_ACTOR_INFO)?, &s.name); + let r: Node = rows::game_row(rows::need(y, BASE, GAME_ACTOR_INFO)?, rows::need(y, source, GAME_ACTOR_INFO)?, &s.name); at[1] = rows::insert(y, r)?; Ok(()) })?; if at[0] != at[1] { - return Err(E::Msg(format!("the new row sits at {} in the actor table and at {} in the game actor table, the two tables no longer line up", at[0], at[1]))); + return Err(E::Msg(format!( + "the new rows sit at {} in the actor table and at {} in the game actor table, the two tables no longer line up", + at[0], at[1] + ))); } let q: File = table(rf, o, modded, POUCH_INFO, |y: &mut Byml| { - let mut r: Node = rows::pouch_row(rows::need(y, &s.item, POUCH_INFO)?, &s.name); + let pouch_source: &str = l.pouch_from.as_deref().unwrap_or(source); + let mut r: Node = rows::pouch_row(rows::need(y, pouch_source, POUCH_INFO)?, &s.name); if l.own { rows::quiet(&mut r); } else if s.name.starts_with(crate::slice::key_spots::DUNGEON_PREFIX) { @@ -138,6 +152,10 @@ pub(crate) fn tables(rf: &mut Romfs, o: &Opts, modded: bool, s: &Spec, l: &Layer r.set("PouchStockable", Node::Bool(true)); } rows::insert(y, r)?; + if identity != s.name && rows::find(y, identity).is_none() { + let id: Node = rows::pouch_row(rows::need(y, pouch_source, POUCH_INFO)?, identity); + rows::insert(y, id)?; + } if l.ammo { ammo::apply(y, &s.name, identity)?; } @@ -155,7 +173,7 @@ fn tag_file(rf: &mut Romfs, o: &Opts, modded: bool, s: &Spec, l: &Layers) -> Res } let first: Vec = start(rf, o.base.as_ref(), TAG)?; let old: Table = Table::parse(&first)?; - let raw: Vec = tag::add(&old, &s.item, &s.name, &l.tags)?.write()?; + let raw: Vec = tag::add(&old, s.source(), &s.name, &l.tags)?.write()?; let id: Option = dict_id(&rf.read(TAG)?); Ok(Some(File { path: TAG.to_string(), z: zs::compress_raw(&raw, id)?, old: old_len(rf, modded, TAG, &first)?, raw, fresh: false })) } @@ -267,7 +285,11 @@ pub(crate) fn sized(rst: &mut Rst, pl: &Plan, files: &[File], carried: &[File], let _ = writeln!(note, "{}: {} -> {} bytes, size table entry {:?} -> {:?}", f.path, f.old, f.raw.len(), was, now); } for (f, len) in &pl.fresh { - let n: u32 = sizes::file_size(rst, &pl.peers, f, *len)?; + let n: u32 = if sizes::kind(f) == "event.root.ainb" { + sizes::event_size(*len)? + } else { + sizes::file_size(rst, &pl.peers, f, *len)? + }; rst.set_size(f, n)?; let _ = writeln!(note, "{f}: new file in the pack, {len} bytes, size table entry {n}"); } @@ -356,7 +378,7 @@ pub fn audit(rf: &mut Romfs, s: &Spec, pl: &Plan, files: &[File], rst_z: &[u8], let p: Pool = pool_of(&[es.clone()])?; let mut names: Vec = es.iter().map(|e| e.name.clone()).collect(); names.sort(); - if select(&p, &s.name)? != names { + if select_with(&p, &s.name, &extra_roots(&p, sc.layers)?)? != names { return Err(E::Format("audit: the written pack holds a file its actor does not reach")); } for e in &es { @@ -382,9 +404,14 @@ pub fn audit(rf: &mut Romfs, s: &Spec, pl: &Plan, files: &[File], rst_z: &[u8], let n: usize = y.root.as_arr().map(|a| a.len()).unwrap_or(0); let m: usize = was.root.as_arr().map(|a| a.len()).unwrap_or(0); let had: usize = usize::from(rows::find(&was, &s.name).is_some()); + + + + let extra: usize = usize::from(t == POUCH_INFO && pl.identity != s.name && rows::find(&was, &pl.identity).is_none()); let r: &Node = rows::need(&y, &s.name, t)?; - if !rows::sorted(&y)? || n + had != m + 1 { - return Err(E::Msg(format!("audit: {t} is not the table it started from plus one sorted row"))); + if !rows::sorted(&y)? || n + had != m + 1 + extra { + let want: &str = if extra == 0 { "plus one sorted row" } else { "plus the expected sorted rows" }; + return Err(E::Msg(format!("audit: {t} is not the table it started from {want}"))); } let index: std::collections::HashMap<&str, &Node> = rows::index(&y); let eased = |x: &Node| t == POUCH_INFO && ((sc.layers.ammo && rows::id(x) == Some(pl.identity.as_str())) || (meter::applies(&pl.identity) && meter::loses(x))); @@ -437,29 +464,56 @@ pub fn run(romfs: &P, load: &P, mod_name: &str, s: &Spec, o: &Opts) -> Res } pub fn run_with(romfs: &P, load: &P, mod_name: &str, s: &Spec, o: &Opts, l: &Layers) -> Res { - if !is_actor_name(&s.name) || !is_actor_name(&s.item) { - return Err(E::Msg(format!("{} or {} is not a plain actor name", s.name, s.item))); + if !is_actor_name(&s.name) || !is_actor_name(&s.item) || !is_actor_name(s.source()) || s.identity.as_deref().is_some_and(|id| !is_actor_name(id)) { + return Err(E::Msg(format!("{}, {} or an override is not a plain actor name", s.name, s.item))); } + let source: &str = s.source(); let o: &Opts = &Opts { base: base_dir(o)?, ..o.clone() }; let mut rf: Romfs = Romfs::open(romfs)?; if rf.root.join(pack_of(&s.name)).is_file() { return Err(E::Msg(format!("the game already ships {}, use that actor", s.name))); } - if !rf.root.join(pack_of(&s.item)).is_file() { - return Err(E::Msg(format!("the game has no actor pack for {}", s.item))); + if !rf.root.join(pack_of(source)).is_file() { + return Err(E::Msg(format!("the game has no actor pack for {source}"))); } let posed: Layers = crate::pickup_pack::model::layers(&mut rf, l)?; - let lifted: Layers = crate::pickup_pack::lift::layers(&mut rf, &s.item, &posed)?; + let lifted: Layers = crate::pickup_pack::lift::layers(&mut rf, source, &posed)?; let l: &Layers = &lifted; let mut packs: Vec> = Vec::new(); - for n in [BASE, DONOR, s.item.as_str()] { - packs.push(sarc::parse(&start(&mut rf, o.base.as_ref(), &pack_of(n))?)?); + let mut seen: BS<&str> = BS::new(); + for n in [BASE, DONOR, source] + .into_iter() + .chain(l.pouch_from.as_deref()) + + + + .chain(l.ring.as_deref().filter(|_| !l.drop_ring).map(|_| crate::pickup_pack::actor::EVENT_BASE)) + { + if seen.insert(n) { + packs.push(sarc::parse(&start(&mut rf, o.base.as_ref(), &pack_of(n))?)?); + } } + + if let Some(m) = l.model.as_deref() { - let es: Vec = sarc::parse(&start(&mut rf, o.base.as_ref(), &pack_of(m))?)?; - packs.push(es.into_iter().filter(|e| crate::pickup_pack::closure::is_byml(&e.data)).collect()); + if seen.insert(m) { + let es: Vec = sarc::parse(&start(&mut rf, o.base.as_ref(), &pack_of(m))?)?; + packs.push(es.into_iter().filter(|e| crate::pickup_pack::closure::is_byml(&e.data)).collect()); + } } - let pl: Plan = plan_with(&packs, s, l)?; + let mut extra: Vec<(String, Vec)> = Vec::new(); + if let Some(who) = l.ring.as_deref() { + if !crate::pickup_pack::is_actor_name(who) || s.identity.as_deref() != Some(who) { + return Err(E::Msg(format!("{who} must be a plain actor name and the pack identity"))); + } + + + if !l.drop_ring { + let donor: Vec = crate::ring_event::donor(&mut rf)?; + extra.push((format!("AI/{who}.event.root.ainb"), crate::ring_event::make(who, &donor)?)); + } + } + let pl: Plan = plan_with_files(&packs, s, l, &extra)?; let (mut rst, modded): (Rst, bool) = size_table(&mut rf, o)?; let mut note: String = String::new(); let id: u32 = dict_id(&rf.read(&pack_of(BASE))?).unwrap_or(PACK_DICT); @@ -478,7 +532,14 @@ pub fn run_with(romfs: &P, load: &P, mod_name: &str, s: &Spec, o: &Opts, l: &Lay for line in audit(&mut rf, s, &pl, &files, &rst_z, &sc)? { let _ = writeln!(note, "{line}"); } - let _ = writeln!(note, "{}", guard::check(&mut rf, &s.name, &files, &carried)?); + + + let guard_line: String = if l.ring.is_some() && !l.drop_ring { + format!("{} is a saved key item, it does not carry a world pickup death table", s.name) + } else { + guard::check(&mut rf, &s.name, &files, &carried)? + }; + let _ = writeln!(note, "{guard_line}"); let mut root: Option = None; if !o.dry { let pk: Pack = Pack::create_for(load, TITLE_ID, mod_name, o.host)?; @@ -495,6 +556,7 @@ pub fn run_with(romfs: &P, load: &P, mod_name: &str, s: &Spec, o: &Opts, l: &Lay #[cfg(test)] mod tests { use super::*; + use crate::pickup_pack::build::plan_with; use crate::pickup_pack::Style; fn real() -> Option { @@ -508,7 +570,7 @@ mod tests { } fn hookshot() -> Spec { - Spec { item: "Item_Hookshot".to_string(), name: "Obj_Hookshot".to_string(), style: Style::Touch, heap: None } + Spec { item: "Item_Hookshot".to_string(), name: "Obj_Hookshot".to_string(), style: Style::Touch, heap: None, source: None, identity: None } } fn opts(places: Vec) -> Opts { @@ -618,6 +680,155 @@ mod tests { assert!(d.report.contains("pack reads back: 40 files")); } + #[test] + fn the_real_ring_build_uses_one_row_per_table_for_the_ring_identity() { + let Some(root) = real() else { + return; + }; + let s: Spec = Spec { + item: "Item_Ring_Forest".to_string(), + name: "Item_Ring_Forest".to_string(), + style: Style::Touch, + heap: None, + source: Some("Item_Dungeon_SmallKey".to_string()), + identity: Some("Item_Ring_Forest".to_string()), + }; + let l: Layers = Layers { + pouch_from: Some("Item_Medal_Forest".to_string()), + ring: Some("Item_Ring_Forest".to_string()), + ..Layers::default() + }; + let mut rf: Romfs = Romfs::open(&root).unwrap(); + let o: Opts = opts(Vec::new()); + let d: Done = run_with(&root, P::new("unused"), "unused", &s, &o, &l).unwrap(); + for t in [ACTOR_INFO, GAME_ACTOR_INFO, POUCH_INFO] { + let was: Byml = rf.read_byml(t).unwrap(); + let now: Byml = Byml::parse(&file(&d, t).raw).unwrap(); + let was_n: usize = was.root.as_arr().unwrap().len(); + let now_n: usize = now.root.as_arr().unwrap().len(); + assert_eq!(now_n, was_n + 1, "{t}"); + assert!(rows::find(&now, "Item_Ring_Forest").is_some(), "{t}"); + } + let actors: Byml = Byml::parse(&file(&d, ACTOR_INFO).raw).unwrap(); + let actor: &Node = rows::find(&actors, "Item_Ring_Forest").unwrap(); + assert_eq!(text(actor, "ActorName"), "Item_Ring_Forest"); + assert_eq!(text(actor, "ELinkUserName"), "Item_Medal_Forest"); + + let es: Vec = sarc::parse(&file(&d, &pack_of("Item_Ring_Forest")).raw).unwrap(); + let names: BS<&str> = es.iter().map(|e| e.name.as_str()).collect(); + for f in [ + "Actor/Item_Ring_Forest.engine__actor__ActorParam.bgyml", + "Component/EventPerformerParam/Item_Ring_Forest.engine__component__EventPerformerParam.bgyml", + "Component/EventPerformerParam/PouchContent.engine__component__EventPerformerParam.bgyml", + "Component/ModelInfo/Item_Ring_Forest.engine__component__ModelInfo.bgyml", + "Component/PouchContentParam/Item_Ring_Forest.game__component__PouchContentParam.bgyml", + "AI/Item_Ring_Forest.event.root.ainb", + ] { + assert!(names.contains(f), "{f} is missing from the ring pack"); + } + for f in [ + "Component/ASInfo/Item_Ring_Forest.engine__component__ASInfo.bgyml", + "Component/CaptureParam/Item_Ring_Forest.game__component__CaptureParam.bgyml", + "Component/ELink/Item_Ring_Forest.engine__component__ELinkParam.bgyml", + "Component/Physics/Item_Ring_Forest.engine__component__PhysicsParam.bgyml", + ] { + assert!(!names.contains(f), "{f} belongs to a world pickup, not a ring"); + } + + let actor_file_data: Byml = in_pack(&d, "Item_Ring_Forest", &actor_file("Item_Ring_Forest")).unwrap(); + assert_eq!(actor_file_data.root.get("$parent").and_then(Node::as_str), Some("Work/Actor/Item_EventObject_Base.engine__actor__ActorParam.gyml")); + assert_eq!(comp(&d, "Item_Ring_Forest", "ActorNameRef").as_deref(), Some("?ActorSystem/ActorName/Item_Ring_Forest.engine__actor__ActorName.bgyml")); + assert_eq!(comp(&d, "Item_Ring_Forest", "EventPerformerRef").as_deref(), Some("?Component/EventPerformerParam/Item_Ring_Forest.engine__component__EventPerformerParam.bgyml")); + assert_eq!(comp(&d, "Item_Ring_Forest", "ModelInfoRef").as_deref(), Some("?Component/ModelInfo/Item_Ring_Forest.engine__component__ModelInfo.bgyml")); + assert_eq!(comp(&d, "Item_Ring_Forest", "PouchContentRef").as_deref(), Some("?Component/PouchContentParam/Item_Ring_Forest.game__component__PouchContentParam.bgyml")); + assert!(comp(&d, "Item_Ring_Forest", "ELinkRef").unwrap().contains("Component/ELink/"), "{}", comp(&d, "Item_Ring_Forest", "ELinkRef").unwrap()); + assert!(comp(&d, "Item_Ring_Forest", "XLinkRef").is_none()); + assert!(comp(&d, "Item_Ring_Forest", "ASInfoRef").is_none()); + assert!(comp(&d, "Item_Ring_Forest", "AttentionSenderRef").is_none()); + + let performer: Byml = in_pack(&d, "Item_Ring_Forest", "Component/EventPerformerParam/Item_Ring_Forest.engine__component__EventPerformerParam.bgyml").unwrap(); + assert_eq!(performer.root.get("EventUniqueAin").and_then(Node::as_str), Some("Work/AI/Root/Event/Item_Ring_Forest.event.root.ain")); + assert_eq!(performer.root.get("UseEventUniqueAin"), Some(&Node::Bool(true))); + let model: Byml = in_pack(&d, "Item_Ring_Forest", "Component/ModelInfo/Item_Ring_Forest.engine__component__ModelInfo.bgyml").unwrap(); + assert_eq!(model.root.get("FmdbName").and_then(Node::as_str), Some("Obj_Dungeon_SmallKey")); + assert_eq!(model.root.get("ModelProjectName").and_then(Node::as_str), Some("Obj_Dungeon_SmallKey")); + let pouch: Byml = in_pack(&d, "Item_Ring_Forest", "Component/PouchContentParam/Item_Ring_Forest.game__component__PouchContentParam.bgyml").unwrap(); + assert_eq!(pouch.root.get("$parent").and_then(Node::as_str), Some("Work/Component/PouchContentParam/Default.game__component__PouchContentParam.gyml")); + assert!(pouch.root.get("PouchActor").is_none()); + assert!(pouch.root.get("IsCountCheckOnFirstGet").is_none()); + let ain: &[u8] = &sarc::get(&es, "AI/Item_Ring_Forest.event.root.ainb").unwrap().data; + let ain: String = String::from_utf8_lossy(ain).into_owned(); + assert!(ain.contains("IsGet.Item_Ring_Forest")); + assert!(!ain.contains("Item_KeyRing_")); + } + + #[test] + fn all_real_ring_packs_pass_the_persistence_guard() { + let Some(root) = real() else { + return; + }; + let catalog: Vec = crate::pickup_pack::catalog::load().unwrap(); + for r in crate::key_rings::all_with_hideout() { + let e: &crate::pickup_pack::catalog::Entry = catalog.iter().find(|e| e.item == r.actor).unwrap(); + let (s, mut l): (Spec, Layers) = crate::pickup_pack::catalog::spec(r.actor, &e.args).unwrap(); + l.spin = true; + let d: Done = run_with(&root, P::new("unused"), "unused", &s, &opts(Vec::new()), &l).unwrap(); + assert!(d.report.contains("is a saved key item"), "{}: {}", r.actor, d.report); + } + } + + #[test] + fn the_drop_ring_build_uses_the_generic_get_flow_on_a_world_pickup_body() { + let Some(root) = real() else { + return; + }; + let r: &'static crate::key_rings::Ring = &crate::key_rings::RINGS[0]; + let catalog: Vec = crate::pickup_pack::catalog::load().unwrap(); + let e: &crate::pickup_pack::catalog::Entry = catalog.iter().find(|e| e.item == r.drop_item).unwrap(); + let (s, mut l): (Spec, Layers) = crate::pickup_pack::catalog::spec(&e.item, &e.args).unwrap(); + l.spin = true; + let d: Done = run_with(&root, P::new("unused"), "unused", &s, &opts(Vec::new()), &l).unwrap(); + + for t in [ACTOR_INFO, GAME_ACTOR_INFO, POUCH_INFO] { + let now: Byml = Byml::parse(&file(&d, t).raw).unwrap(); + assert!(rows::find(&now, &s.name).is_some(), "{t} has no {}", s.name); + } + let pouch: Byml = Byml::parse(&file(&d, POUCH_INFO).raw).unwrap(); + assert!(rows::find(&pouch, r.actor).is_some(), "the saved ring identity has no pouch row"); + let actors: Byml = Byml::parse(&file(&d, ACTOR_INFO).raw).unwrap(); + let actor: &Node = rows::find(&actors, &s.name).unwrap(); + assert_eq!(text(actor, "ActorName"), r.actor); + assert_eq!(text(actor, "ELinkUserName"), "Item_Medal_Forest"); + + let es: Vec = sarc::parse(&file(&d, &pack_of(&s.name)).raw).unwrap(); + let names: BS<&str> = es.iter().map(|e| e.name.as_str()).collect(); + for f in [ + format!("Actor/{}.engine__actor__ActorParam.bgyml", s.name), + format!("Component/ASInfo/{}.engine__component__ASInfo.bgyml", s.name), + format!("Component/PouchContentParam/{}.game__component__PouchContentParam.bgyml", s.name), + ] { + assert!(names.contains(f.as_str()), "{f} is missing from the drop ring pack"); + } + let actor_file_data: Byml = in_pack(&d, &s.name, &actor_file(&s.name)).unwrap(); + assert_eq!(actor_file_data.root.get("$parent").and_then(Node::as_str), Some("Work/Actor/Obj_Item_Base.engine__actor__ActorParam.gyml")); + assert!(comp(&d, &s.name, "ActorNameRef").unwrap().contains(r.actor)); + assert!(comp(&d, &s.name, "ASInfoRef").unwrap().contains(&s.name)); + assert!(comp(&d, &s.name, "ELinkRef").is_none()); + + + assert!(comp(&d, &s.name, "EventPerformerRef").is_none(), "a drop ring must not override the generic get performer"); + assert!( + !names.contains(format!("Component/EventPerformerParam/{}.engine__component__EventPerformerParam.bgyml", s.name).as_str()), + "a drop ring must not ship a private get performer" + ); + assert!(!names.contains(format!("AI/{}.event.root.ainb", r.actor).as_str()), "a drop ring must not ship a private get event"); + + let line: String = format!("{} stays collected once taken", s.name); + assert!(d.report.contains(&line), "{}", d.report); + let mut rf: Romfs = Romfs::open(&root).unwrap(); + assert!(guard::check(&mut rf, &s.name, &d.files, &d.carried).is_ok()); + } + #[test] fn the_real_build_refuses_a_shipped_name_a_missing_item_and_a_chest() { let Some(root) = real() else { @@ -696,7 +907,7 @@ mod tests { let mut rows_seen: Vec> = vec![BM::new(), BM::new(), BM::new()]; let mut frozen: Vec<(PB, BM>)> = Vec::new(); for (i, (item, name)) in chain.iter().enumerate() { - let s: Spec = Spec { item: item.to_string(), name: name.to_string(), style: Style::Touch, heap: None }; + let s: Spec = Spec { item: item.to_string(), name: name.to_string(), style: Style::Touch, heap: None, source: None, identity: None }; let places: Vec = if i == 0 { vec![SPOT] } else { Vec::new() }; let o: Opts = Opts { host: Host::Hookshot, base: base.clone(), rst_from: None, places, dry: false }; let d: Done = run(&root, &load, &format!("step{i}"), &s, &o).unwrap(); @@ -749,7 +960,7 @@ mod tests { assert!(frozen[0].1.contains_key(banc)); assert!(!frozen[2].1.contains_key(banc)); assert_eq!(frozen[2].1.keys().filter(|k| k.starts_with("Pack/Actor/")).count(), 3); - let again: Spec = Spec { item: "Item_Boomerang".to_string(), name: "Obj_Boomerang".to_string(), style: Style::Touch, heap: None }; + let again: Spec = Spec { item: "Item_Boomerang".to_string(), name: "Obj_Boomerang".to_string(), style: Style::Touch, heap: None, source: None, identity: None }; let o: Opts = Opts { host: Host::Hookshot, base: base.clone(), rst_from: None, places: Vec::new(), dry: false }; let d: Done = run(&root, &load, "step2", &again, &o).unwrap(); assert_eq!(d.carried.len(), 2); @@ -769,7 +980,7 @@ mod tests { let one: Done = run(&root, &load, "one", &hookshot(), &o).unwrap(); let dir: PB = one.root.unwrap().join("romfs"); let mut rf: Romfs = Romfs::open(&root).unwrap(); - let boom: Spec = Spec { item: "Item_Boomerang".to_string(), name: "Obj_Boomerang".to_string(), style: Style::Touch, heap: None }; + let boom: Spec = Spec { item: "Item_Boomerang".to_string(), name: "Obj_Boomerang".to_string(), style: Style::Touch, heap: None, source: None, identity: None }; o.base = Some(dir.clone()); o.dry = true; let pl: Plan = { @@ -803,7 +1014,7 @@ mod tests { } fn spec_of(item: &str, name: &str) -> Spec { - Spec { item: item.to_string(), name: name.to_string(), style: Style::Touch, heap: None } + Spec { item: item.to_string(), name: name.to_string(), style: Style::Touch, heap: None, source: None, identity: None } } fn file<'a>(d: &'a Done, path: &str) -> &'a File { diff --git a/randomizer/core/src/pot_slice/targets.rs b/randomizer/core/src/pot_slice/targets.rs index 6f69e4dc..dc6b9216 100644 --- a/randomizer/core/src/pot_slice/targets.rs +++ b/randomizer/core/src/pot_slice/targets.rs @@ -34,7 +34,7 @@ pub fn actor_of(d: &Data, loc: &str, item: &str, fixed: &BM) -> if let Some(a) = pickup::of(item) { return Ok(dropped(a)); } - crate::slice::key_spots::resolve(d, item, fixed.get(loc).map(|s| s.as_str())) + crate::slice::key_spots::resolve_at(d, loc, item, fixed.get(loc).map(|s| s.as_str())) .map(|p| p.pack) .map_err(|e| E::Msg(format!("{item} has no world pickup and cannot be placed at {loc}: {e}"))) } diff --git a/randomizer/core/src/progressive.rs b/randomizer/core/src/progressive.rs index 6bcdf0de..1113d65a 100644 --- a/randomizer/core/src/progressive.rs +++ b/randomizer/core/src/progressive.rs @@ -651,9 +651,14 @@ pub struct Built { } pub fn stage(rf: &mut Romfs, used: &BS<(String, Size)>, scale: Option<(f32, i32)>, kids: &[(String, String)], keys: &[&str]) -> Res> { + stage_with(rf, used, scale, kids, keys, &[]) +} + + +pub fn stage_with(rf: &mut Romfs, used: &BS<(String, Size)>, scale: Option<(f32, i32)>, kids: &[(String, String)], keys: &[&str], rings: &[&'static str]) -> Res> { let mut outs: Vec = Vec::new(); let mut sizes: BS = used.iter().map(|u| u.1).collect(); - if !keys.is_empty() { + if !keys.is_empty() || !rings.is_empty() { sizes.extend([Size::Small, Size::Big]); } for s in &sizes { @@ -670,6 +675,9 @@ pub fn stage(rf: &mut Romfs, used: &BS<(String, Size)>, scale: Option<(f32, i32) if !keys.is_empty() { crate::dungeon_credit::credit_keys(flow, keys, *s == Size::Big)?; } + if !rings.is_empty() { + crate::dungeon_credit::credit_rings(flow, rings)?; + } if let Some((factor, min)) = scale { scale_waits(&mut bf, factor, min); } @@ -684,11 +692,15 @@ pub fn stage(rf: &mut Romfs, used: &BS<(String, Size)>, scale: Option<(f32, i32) let e: Option = if analyzed { None } else { Some(entry_name(fam)) }; m.entry(*s).or_default().push((event_name(fam, *s), e)); } - for s in [Size::Small, Size::Big].into_iter().filter(|_| !keys.is_empty()) { + for s in [Size::Small, Size::Big].into_iter().filter(|_| !keys.is_empty() || !rings.is_empty()) { for d in keys { let e: Option = if analyzed { None } else { Some(crate::dungeon_credit::entry_name(d)) }; m.entry(s).or_default().push((crate::dungeon_credit::event_name(d, s), e)); } + for d in rings { + let e: Option = if analyzed { None } else { Some(crate::dungeon_credit::ring_entry_name(d)) }; + m.entry(s).or_default().push((crate::dungeon_credit::ring_event_name(d, s), e)); + } } m }; diff --git a/randomizer/core/src/ring_event.rs b/randomizer/core/src/ring_event.rs new file mode 100644 index 00000000..d0461006 --- /dev/null +++ b/randomizer/core/src/ring_event.rs @@ -0,0 +1,177 @@ +use crate::ainb::build::Spec; +use crate::ainb::{audit, Ainb}; +use crate::error::{Error as E, Res}; + +pub const DONOR: &str = "AI/PouchContent.event.root.ainb"; +pub const DONOR_PACK: &str = "Pack/AI.Global.Product.111.pack.zs"; +const SET_FLAG: &str = "OneShotSetNonStructGameDataBool"; + +pub fn donor(rf: &mut crate::romfs::Romfs) -> Res> { + let raw: Vec = rf.read_zs(DONOR_PACK)?; + let es: Vec = crate::sarc::parse(&raw)?; + crate::sarc::get(&es, DONOR) + .map(|e: &crate::sarc::Entry| e.data.clone()) + .ok_or_else(|| E::Msg(format!("ring event: {DONOR} is missing from {DONOR_PACK}"))) +} + +fn ring(actor: &str) -> Res<&'static crate::key_rings::Ring> { + crate::key_rings::all_with_hideout() + .into_iter() + .find(|r| r.actor == actor) + .ok_or_else(|| E::Msg(format!("ring event: unknown actor {actor}"))) +} + +fn no_direct_credit(a: &Ainb, actor: &str) -> Res<()> { + let r: &crate::key_rings::Ring = ring(actor)?; + let applied: String = crate::key_rings::applied_flag(r.folder); + for kind in ["OneShotSetNonStructGameDataInt", "OneShotSetStructGameDataInt"] { + for i in a.find_els(kind) { + if let Some(name) = a.in_str(i, "GameDataFullName") { + if name.starts_with("DungeonInfo.") { + return Err(E::Format("ring event: the AINB must not write dungeon keys")); + } + } + } + } + for i in a.find_els(SET_FLAG) { + if a.in_str(i, "GameDataFullName") == Some(applied.as_str()) { + return Err(E::Format("ring event: the AINB must not set the applied flag")); + } + } + Ok(()) +} + +fn patch(a: &mut Ainb, flag: &str, event: &str) -> Res<()> { + let pf: u32 = a.pool.add(flag); + let pe: u32 = a.pool.add(event); + let f: Vec = pf.to_le_bytes().to_vec(); + let e: Vec = pe.to_le_bytes().to_vec(); + let z: Vec = 0u32.to_le_bytes().to_vec(); + let seq: usize = a.add_node(&Spec::composite(2, "ring#chain").kid(35, ""))?; + let set: usize = a.add_node( + &Spec::node("OneShotSetNonStructGameDataBool", "ring#save") + .constant(0, "GameDataIndex", z.clone()) + .constant(1, "Value", e.clone()) + .constant(3, "GameDataFullName", f.clone()), + )?; + let blank: u32 = a.pool.add(""); + a.params[seq].add_plug(2, 1, crate::ainb::Plug { a: set as u32, b: blank, extra: Vec::new() })?; + let q: usize = a.add_node( + &Spec::query("QueryGetNonStructGameDataBool", "ring#check") + .idle(0, "GameDataIndex", z.clone()) + .idle(1, "IsDirect", e.clone()) + .constant(3, "GameDataFullName", f.clone()), + )?; + let mut sel: Spec = Spec::composite(7, "ring#select").linked(1, "Input", q, 0).kid(77, "True").kid(seq, "False"); + sel.link_extra = 8; + let id: usize = a.add_node(&sel)?; + let g: usize = a.find_in(id, 1, "Input").ok_or_else(|| E::Format("ring event: the selector lost its input"))?; + a.set_in_val(1, g, &e)?; + let p: &mut crate::ainb::Param = &mut a.params[58]; + let [n, b]: [u8; 2] = p.pl[2]; + let old: &mut crate::ainb::Plug = p + .plugs + .get_mut(b as usize..b as usize + n as usize) + .and_then(|g: &mut [crate::ainb::Plug]| g.iter_mut().find(|q| q.a == 35)) + .ok_or_else(|| E::Format("ring event: the get flow lost its first child"))?; + old.a = id as u32; + Ok(()) +} + +pub fn make(actor: &str, donor: &[u8]) -> Res> { + ring(actor)?; + let flag: String = crate::key_rings::got_flag(actor); + let event: String = format!("{actor}.event.root"); + let mut a: Ainb = Ainb::parse(donor)?; + patch(&mut a, &flag, &event)?; + let set: Vec = a + .find_els(SET_FLAG) + .into_iter() + .filter(|&i| a.in_str(i, "GameDataFullName") == Some(flag.as_str())) + .collect(); + let get: Vec = a + .find_els("QueryGetNonStructGameDataBool") + .into_iter() + .filter(|&i| a.in_str(i, "GameDataFullName") == Some(flag.as_str())) + .collect(); + if set.len() != 1 || get.len() != 1 { + return Err(E::Format("ring event: the template lost its saved flag nodes")); + } + no_direct_credit(&a, actor)?; + let bad: Vec = audit(&a); + if !bad.is_empty() { + return Err(E::Msg(format!("ring event: {actor}: {}", bad.join("; ")))); + } + a.write() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::romfs::Romfs; + + fn donor() -> Option> { + let p: std::path::PathBuf = ootrr_game::test_romfs::path(); + if !p.exists() { + eprintln!("skipped: no romfs at {}, set OOTRR_ROMFS", p.display()); + return None; + } + let mut rf: Romfs = Romfs::open(&p).unwrap(); + super::donor(&mut rf).ok() + } + + #[test] + fn every_ring_event_sets_its_own_saved_flag() { + let Some(raw) = donor() else { + return; + }; + for r in crate::key_rings::all_with_hideout() { + let out: Vec = make(r.actor, &raw).unwrap(); + let a: Ainb = Ainb::parse(&out).unwrap(); + let flag: String = crate::key_rings::got_flag(r.actor); + let set: Vec = a + .find_els(SET_FLAG) + .into_iter() + .filter(|&i| a.in_str(i, "GameDataFullName") == Some(flag.as_str())) + .collect(); + let get: Vec = a + .find_els("QueryGetNonStructGameDataBool") + .into_iter() + .filter(|&i| a.in_str(i, "GameDataFullName") == Some(flag.as_str())) + .collect(); + assert_eq!((set.len(), get.len()), (1, 1), "{}", r.actor); + assert!(!String::from_utf8_lossy(&out).contains("Item_KeyRing_"), "{}", r.actor); + } + } + + #[test] + fn every_ring_event_leaves_key_credit_to_the_flows() { + let Some(raw) = donor() else { + return; + }; + for r in crate::key_rings::all_with_hideout() { + let out: Vec = make(r.actor, &raw).unwrap(); + let a: Ainb = Ainb::parse(&out).unwrap(); + for name in [format!("DungeonInfo.{}.SmallKeyNum", r.folder), format!("DungeonInfo.{}.SmallKeyTotalNum", r.folder)] { + for kind in ["OneShotSetNonStructGameDataInt", "OneShotSetStructGameDataInt"] { + let set: Vec = a + .find_els(kind) + .into_iter() + .filter(|&i| a.in_str(i, "GameDataFullName") == Some(name.as_str())) + .collect(); + assert!(set.is_empty(), "{}: {} must not be written by the AINB", r.actor, name); + } + } + let applied: String = crate::key_rings::applied_flag(r.folder); + let set: Vec = a + .find_els(SET_FLAG) + .into_iter() + .filter(|&i| a.in_str(i, "GameDataFullName") == Some(applied.as_str())) + .collect(); + assert!(set.is_empty(), "{}: {} must not be written by the AINB", r.actor, applied); + assert!(audit(&a).is_empty(), "{}: bad AINB", r.actor); + let again: Ainb = Ainb::parse(&a.write().unwrap()).unwrap(); + assert!(audit(&again).is_empty(), "{}: bad AINB after round trip", r.actor); + } + } +} diff --git a/randomizer/core/src/settings.rs b/randomizer/core/src/settings.rs index eea71dea..c2968938 100644 --- a/randomizer/core/src/settings.rs +++ b/randomizer/core/src/settings.rs @@ -322,6 +322,48 @@ mod tests { assert_eq!(s.encode().unwrap(), "OOTRR1-BEAQGGABAUOACZBEAMBAABWEOQ"); } + #[test] + fn frozen_key_ring_settings_strings_keep_decoding() { + const OFF: &str = "OOTRR1-A4AQECIBAMHACBQRAECCMAIBE4AQCMYBAFGACAKOAEBGSAIAQ4AQCADGNE"; + const ON: &str = "OOTRR1-A4AQECIBAMHACBQRAECCMAIBE4AQCMYBAFGACAKOAEBGSAIAQ4AQCAGMAEAQDFZ5"; + for (t, want) in [(OFF, false), (ON, true)] { + let l: Loaded = Settings::decode(t).unwrap(); + assert!(l.warnings.is_empty(), "{t}: {:?}", l.warnings); + assert_eq!(l.settings.text("gerudo_fortress").unwrap(), "open"); + assert_eq!(l.settings.text("shuffle_chests").unwrap(), "all"); + assert_eq!(l.settings.text("shuffle_pots").unwrap(), "all"); + assert_eq!(l.settings.text("shuffle_smallkeys").unwrap(), "keysanity"); + assert_eq!(l.settings.text("shuffle_hideoutkeys").unwrap(), "keysanity"); + assert_eq!(l.settings.flag("key_rings").unwrap(), want); + assert_eq!(l.settings.encode().unwrap(), t); + } + } + + #[test] + fn key_ring_suboptions_round_trip_through_a_settings_string() { + use crate::key_rings; + + let mut s: Settings = Settings::default(); + s.set("shuffle_smallkeys", Value::s("keysanity")).unwrap(); + s.set(key_rings::SETTING, Value::Bool(true)).unwrap(); + s.set(key_rings::MODE_SETTING, Value::s("count")).unwrap(); + s.set(key_rings::COUNT_SETTING, Value::Int(3)).unwrap(); + let t: String = s.encode().unwrap(); + let l: Loaded = Settings::decode(&t).unwrap(); + assert!(l.warnings.is_empty(), "{:?}", l.warnings); + assert!(l.settings.flag(key_rings::SETTING).unwrap()); + assert_eq!(l.settings.text(key_rings::MODE_SETTING).unwrap(), "count"); + assert_eq!(l.settings.int(key_rings::COUNT_SETTING).unwrap(), 3); + assert_eq!(l.settings.items(key_rings::SELECTION_SETTING).unwrap(), key_rings::CHOICE_IDS); + assert_eq!(l.settings.encode().unwrap(), t); + + s.set(key_rings::SETTING, Value::Bool(false)).unwrap(); + let t: String = s.encode().unwrap(); + let l: Loaded = Settings::decode(&t).unwrap(); + assert_eq!(l.settings.text(key_rings::MODE_SETTING).unwrap(), "all"); + assert_eq!(l.settings.int(key_rings::COUNT_SETTING).unwrap(), 8); + } + #[test] fn default_string_is_tiny_and_stable() { let t: String = Settings::default().encode().unwrap(); diff --git a/randomizer/core/src/settings/list.rs b/randomizer/core/src/settings/list.rs index 16a67fb1..cd692951 100644 --- a/randomizer/core/src/settings/list.rs +++ b/randomizer/core/src/settings/list.rs @@ -758,6 +758,39 @@ pub fn build() -> Schema { Setting::toggle(crate::debug_names::NUM, crate::debug_names::SETTING, "world", "Show location names", false) .tip("For checking the location data. After an item get, a text box shows the internal name of the location the item came from, such as [KF Midos Top Left Chest]. Covers chests, NPC, song and event rewards, Gold Skulltulas and items on the ground. Items on the ground need a button press, and a placed item missing from the location list says so. Experimental."), ); + s.push( + Setting::toggle(crate::key_rings::NUM, crate::key_rings::SETTING, "keys", "Key Rings", false) + .when_not("shuffle_smallkeys", "vanilla") + .tip("Replace the small keys of standard dungeons with one key ring per active dungeon. A ring gives every key of its dungeon when it is picked up. Rings can appear wherever small keys can, including pots, crates and flying pots. Use the options below to choose which dungeons are active. Off by default; only available when Small Key Shuffle is not Vanilla. Experimental, untested in the game."), + ); + s.push( + Setting::choice(crate::key_rings::MODE_NUM, crate::key_rings::MODE_SETTING, "keys", "Key Ring Dungeons", "all") + .when_on(crate::key_rings::SETTING) + .tip("Which standard dungeons get key rings. Hideout keys are separate and are never included here.\n\nAll - Every standard key dungeon gets a ring, as before.\n\nCount - A seed-randomized set of the number you choose gets rings. Other dungeons keep individual small keys.\n\nSelection - You tick each standard dungeon yes or no.\n\nRandom - A seed-randomized number from 1 to 8, then a seed-randomized set of that many dungeons. Experimental, untested in the game.") + .opt("all", "All", "Every standard key dungeon gets a ring.") + .opt("count", "Count", "A seed-randomized set of the chosen number of dungeons gets rings.") + .opt("selection", "Selection", "Choose each standard dungeon individually.") + .opt("random", "Random", "A seed-randomized number and set of standard dungeons."), + ); + s.push( + Setting::number(crate::key_rings::COUNT_NUM, crate::key_rings::COUNT_SETTING, "keys", "Key Ring Count", 8, 1, 8) + .when_on(crate::key_rings::SETTING) + .when(crate::key_rings::MODE_SETTING, "count") + .tip("How many standard dungeons get key rings in Count mode. The dungeons are chosen from the seed, not by order in this list. Inactive dungeons keep individual small keys and their normal placement rules. Experimental, untested in the game."), + ); + s.push( + Setting::multi_default(crate::key_rings::SELECTION_NUM, crate::key_rings::SELECTION_SETTING, "keys", "Key Ring Selection", &crate::key_rings::CHOICE_IDS) + .when_on(crate::key_rings::SETTING) + .when(crate::key_rings::MODE_SETTING, "selection") + .opts(&crate::key_rings::CHOICES) + .tip("Which standard dungeons get key rings in Selection mode. Unticked dungeons keep individual small keys with their normal placement rules. Experimental, untested in the game."), + ); + s.push( + Setting::toggle(crate::key_rings::HIDEOUT_NUM, crate::key_rings::HIDEOUT_SETTING, "keys", "Hideout Key Ring", false) + .when("shuffle_hideoutkeys", "keysanity") + .when("gerudo_fortress", "open") + .tip("When Gerudo Fortress Keys are Anywhere and the fortress starts Open, the four Thieves' Hideout keys become one Hideout key ring. This is a separate manual choice: it is not enabled by Key Rings and Hideout is never a target of Count, Selection or Random. Experimental, untested in the game."), + ); s.push(starting_items()); s.push(starting_songs()); s.extend(difficulty()); diff --git a/randomizer/core/src/settings/menu.rs b/randomizer/core/src/settings/menu.rs index 556dae66..76a66739 100644 --- a/randomizer/core/src/settings/menu.rs +++ b/randomizer/core/src/settings/menu.rs @@ -218,7 +218,7 @@ const JABU: View = View { const CARPENTERS: View = View { id: "gerudo_fortress", label: "Fortress Carpenters", - tip: "Sets the state of the carpenters captured by Gerudo in Gerudo Fortress, and with it the number of guards that spawn.\n\nNormal - All 4 carpenters are required to be saved.\n\nFast - Tested in game. Three carpenters start free. The guard gives the Membership Card check when the last carpenter is rescued: the card itself, or a random item when Shuffle Gerudo Membership Card is on.\n\nOpen - Tested in game. Start with the Gerudo Membership Card and the bridge built. The Membership Card check is still in the game and randomized. It triggers when you interact with your first jail cell.\n\nOnly \"Normal\" is compatible with Gerudo Fortress Keyrings.", + tip: "Sets the state of the carpenters captured by Gerudo in Gerudo Fortress, and with it the number of guards that spawn.\n\nNormal - All 4 carpenters are required to be saved.\n\nFast - Tested in game. Three carpenters start free. The guard gives the Membership Card check when the last carpenter is rescued: the card itself, or a random item when Shuffle Gerudo Membership Card is on.\n\nOpen - Tested in game. Start with the Gerudo Membership Card and the bridge built. The Membership Card check is still in the game and randomized. It triggers when you interact with your first jail cell.\n\nOnly \"Open\" is compatible with shuffled Gerudo Fortress Keys and the Hideout Key Ring.", kind: Kind::Pick, opts: &[ yes("Normal", "normal"), @@ -316,7 +316,7 @@ const GERUDO_KEYS: View = View { label: "Gerudo Fortress Keys", tip: "Vanilla - Thieves' Hideout Keys will appear in their vanilla locations.\n\nAny dungeon - Thieves' Hideout Keys can only appear inside of any dungeon.\n\nOverworld - Thieves' Hideout Keys can only appear outside of dungeons.\n\nAnywhere - Thieves' Hideout Keys can appear anywhere in the world.", kind: Kind::Pick, - opts: &[yes("Vanilla", "vanilla"), broken("Any Dungeon", "any_dungeon"), broken("Overworld", "overworld"), broken("Anywhere", "keysanity")], + opts: &[yes("Vanilla", "vanilla"), yes("Any Dungeon", "any_dungeon"), broken("Overworld", "overworld"), yes("Anywhere", "keysanity")], }; pub struct PortSection { @@ -472,15 +472,6 @@ const DUNGEONS_TAB: &[PortSection] = &[ ), ], ), - port( - "Keyrings", - &[gray_pick( - "Keyrings", - &["Off", "Random", "Count", "Selection"], - 0, - "Keyrings will replace all small keys from a particular dungeon with a single keyring that awards all keys for its associated dungeon.\n\nOff - No dungeons will have their keys replaced with keyrings.\n\nRandom - A random amount of dungeons will have their keys replaced with keyrings.\n\nCount - A specified amount of randomly selected dungeons will have their keys replaced with keyrings.\n\nSelection - Hand select which dungeons will have their keys replaced with keyrings\n(can also be left as random, in which case each one will have a 50% chance of being a keyring).\n\nSelecting keyring for dungeons will have no effect if Small Keys are set to Start With or Vanilla.\n\nThe maximum amount of Keyrings that can be selected by Random or Count is 8, plus one if Gerudo Fortress Carpenters is set to Normal and Gerudo Fortress Keys is set to anything other than Vanilla, plus one if Shuffle Chest Minigame is on.", - )], - ), ]; const FREESTANDING: View = View { @@ -782,6 +773,15 @@ pub const MENU: &[Page] = &[ sec("Minigames", &["unbreakable_bowling_grass", "harder_talon_cuccos"]), ], }, + Page { + id: "key_rings", + label: "Key Rings", + heading: IN_DEV, + sections: &[sec( + "Key Rings", + &[crate::key_rings::SETTING, crate::key_rings::MODE_SETTING, crate::key_rings::COUNT_SETTING, crate::key_rings::SELECTION_SETTING, crate::key_rings::HIDEOUT_SETTING], + )], + }, Page { id: "cosmetics", label: "Cosmetics", heading: GAMEPLAY, sections: &[sec("Looks", &["mega_like_likes"])] }, Page { id: "debug", label: "Debug", heading: DEBUG, sections: &[sec("Debug", &["debug_location_names"]), sec("Spawn enemies", &["enemy_spawn_combo"])] }, ]; diff --git a/randomizer/core/src/settings/model.rs b/randomizer/core/src/settings/model.rs index 1cb235d0..65e545cb 100644 --- a/randomizer/core/src/settings/model.rs +++ b/randomizer/core/src/settings/model.rs @@ -197,6 +197,10 @@ impl Setting { Setting::base(num, id, group, label, Kind::Multi, Value::Set(Vec::new())) } + pub fn multi_default(num: u16, id: &str, group: &str, label: &str, default: &[&str]) -> Setting { + Setting::base(num, id, group, label, Kind::Multi, Value::set(default)) + } + pub fn list(num: u16, id: &str, group: &str, label: &str, max_items: usize) -> Setting { let mut s: Setting = Setting::base(num, id, group, label, Kind::List, Value::Set(Vec::new())); s.max_items = max_items; diff --git a/randomizer/core/src/settings/seed.rs b/randomizer/core/src/settings/seed.rs index 8747f2c6..97f4a6d5 100644 --- a/randomizer/core/src/settings/seed.rs +++ b/randomizer/core/src/settings/seed.rs @@ -484,6 +484,24 @@ mod tests { assert!(SeedFile::read(&d).is_err()); } + #[test] + fn rings_on_seed_file_keeps_its_settings_string() { + const ON: &str = "OOTRR1-A4AQECIBAMHACBQRAECCMAIBE4AQCMYBAFGACAKOAEBGSAIAQ4AQCAGMAEAQDFZ5"; + let settings: Settings = Settings::decode(ON).unwrap().settings; + let f: SeedFile = SeedFile::new( + "rings on seed", + &settings, + "oot-remake:1.0.0", + placements(&[("deku_tree_compass_chest", "Small Key Ring (Forest Temple)")]), + ) + .unwrap(); + let text: String = f.to_text(); + assert!(text.contains(ON)); + let back: SeedFile = SeedFile::parse(&text).unwrap(); + assert_eq!(back, f); + assert_eq!(back.settings().unwrap().settings.encode().unwrap(), ON); + } + const FROZEN_V1: &str = r#"{ "format": "ootrr-seed", "version": 1, diff --git a/randomizer/core/src/shelf/actor.rs b/randomizer/core/src/shelf/actor.rs index 2645097d..366d49ee 100644 --- a/randomizer/core/src/shelf/actor.rs +++ b/randomizer/core/src/shelf/actor.rs @@ -124,7 +124,7 @@ pub fn make(rf: &mut Romfs, base: Option<&PB>, item: &str, model: Option<&str>, let mut actor: Node = Node::Map(Vec::new()); actor.set(PARENT, s(&work(&actor_file(BASE)))); actor.set(COMPONENTS, comps); - let sp: Spec = Spec { item: item.to_string(), name: name.to_string(), style: Style::Touch, heap: None }; + let sp: Spec = Spec { item: item.to_string(), name: name.to_string(), style: Style::Touch, heap: None, source: None, identity: None }; let who: String = shelf_identity(&identity(&p, &sp, &it, &item_pouch)?).to_string(); let mut pouch: Node = Node::Map(Vec::new()); pouch.set(PARENT, s(&work(&item_pouch))); diff --git a/randomizer/core/src/shelf/seed.rs b/randomizer/core/src/shelf/seed.rs index c3bbee06..83edaf69 100644 --- a/randomizer/core/src/shelf/seed.rs +++ b/randomizer/core/src/shelf/seed.rs @@ -11,7 +11,7 @@ use crate::slice::data::Data; use crate::slice::edit::Built; pub fn after(seed: &SeedFile, romfs: &P, load: &P, mod_name: &str, host: Host, mut b: Built) -> Res { - let p = crate::slice::support::plan(&seed.settings()?.settings)?; + let p = crate::slice::support::plan_with_seed(&seed.settings()?.settings, Some(&seed.seed))?; crate::shops::seed::check(&p.shops, seed)?; let Some(l) = crate::shops::seed::layout(seed)? else { return Ok(b); diff --git a/randomizer/core/src/shelf/stage.rs b/randomizer/core/src/shelf/stage.rs index 8a88b4a0..20ecd13c 100644 --- a/randomizer/core/src/shelf/stage.rs +++ b/randomizer/core/src/shelf/stage.rs @@ -474,7 +474,7 @@ mod tests { let t = crate::shops::table().unwrap(); let mut rf: Romfs = Romfs::open(&root).unwrap(); let mut want: Vec<(String, Option)> = Vec::new(); - for i in d.items.iter().filter(|i| crate::shops::rules::class(&d, &i.name).is_some()) { + for i in d.items.iter().filter(|i| crate::shops::rules::class(&d, &i.name).is_some() && !crate::key_rings::all_with_hideout().iter().any(|r| i.actor.as_deref() == Some(r.actor))) { match crate::shops::rules::class(&d, &i.name).unwrap() { crate::shops::rules::Class::Upgrade => want.extend(i.tiers.iter().map(|a| (a.clone(), crate::shops::jobs::donor(t, a)))), crate::shops::rules::Class::Song => want.push((i.actor.clone().unwrap(), t.song_models.first().cloned())), diff --git a/randomizer/core/src/slice.rs b/randomizer/core/src/slice.rs index 99e3ac01..7a92712f 100644 --- a/randomizer/core/src/slice.rs +++ b/randomizer/core/src/slice.rs @@ -37,6 +37,7 @@ pub mod pickups; pub mod plando; pub mod remake_chests; pub mod remake_overworld; +pub mod rings; pub mod scan; pub mod seed_packs; pub mod silver; diff --git a/randomizer/core/src/slice/chest_targets.rs b/randomizer/core/src/slice/chest_targets.rs index 07ce3c61..a5f7b84b 100644 --- a/randomizer/core/src/slice/chest_targets.rs +++ b/randomizer/core/src/slice/chest_targets.rs @@ -11,7 +11,8 @@ use crate::slice::data::{Data, Ev, State}; use crate::slice::flow_pool::{dest_form, pool_actor}; use crate::slice::flow_wrap::wraps as flow_wraps; use crate::slice::pickups as pu; -use crate::slice::support::plan; +use crate::slice::support::plan_with_seed as plan; +use crate::slice::support::Keep; #[derive(Debug, Clone, PartialEq)] @@ -95,27 +96,47 @@ pub(crate) fn actors_for(d: &Data, seed: &SeedFile) -> Res> { if crate::pot_slice::targets::is_loc(d, loc) || crate::shops::seed::skip(loc) || crate::slice::silver::is_spot(loc) { continue; } - let vanilla: &str = d.pool_item(loc).ok_or_else(|| E::Msg(format!("{loc} has no vanilla item")))?; - let actor: String = match d.flow.by_name(loc).and_then(|l| l.item.clone()) { - Some(a) if Some(vanilla) != d.vanilla_of(loc) => a, - _ => vanilla_actor(d, loc)?, - }; - pool.entry(vanilla.to_string()).or_default().push(actor); + + + if !crate::hideout_keys::is_native(loc) { + let vanilla: &str = d.pool_item(loc).ok_or_else(|| E::Msg(format!("{loc} has no vanilla item")))?; + let actor: String = match d.flow.by_name(loc).and_then(|l| l.item.clone()) { + Some(a) if Some(vanilla) != d.vanilla_of(loc) => a, + _ => vanilla_actor(d, loc)?, + }; + pool.entry(vanilla.to_string()).or_default().push(actor); + } if !crate::slice::silver::is_item(item) { dests.entry(item.clone()).or_default().push(loc.clone()); } } - let pl: crate::slice::support::Plan = plan(&seed.settings()?.settings)?; - let stripped: bool = crate::start_items::pool::active(&pl); + let p = plan(&seed.settings()?.settings, Some(&seed.seed))?; + let stripped: bool = crate::start_items::pool::active(&p); let mut out: BM = BM::new(); for (item, locs) in &dests { let mut acts: Vec = pool.get(item).cloned().unwrap_or_default(); let net: isize = crate::pot_slice::targets::delta(d, seed, item) + crate::shops::seed::delta(seed, item) + crate::slice::silver::delta(seed, item); adjust(d, item, net, &mut acts); + + + if p.hideout != Keep::Vanilla && d.item(item).is_some_and(|i| i.kind == "HideoutSmallKey") { + let canon: String = d.item(item).and_then(|i| i.actor.clone()).ok_or_else(|| E::Msg(format!("{item} has no key actor")))?; + while acts.len() < locs.len() { + acts.push(canon.clone()); + } + } + + + if let Some(r) = crate::key_rings::by_item_any(item) { + let made: String = crate::key_rings::pack(r.actor); + while acts.len() < locs.len() { + acts.push(made.clone()); + } + } if stripped { crate::start_items::pool::fit_actors(d, item, locs.len(), &mut acts); } - if pl.rewards.trade_items { + if p.rewards.trade_items { crate::open_world::trade_shuffle::fit_actors(d, item, locs.len(), &mut acts); } if acts.len() != locs.len() { @@ -150,11 +171,12 @@ pub(crate) fn targets_with(d: &Data, seed: &SeedFile, roam: bool, fixed: &BM = Vec::new(); let mut flows: Vec = Vec::new(); let mut same: usize = 0; + let hideout: bool = plan(&seed.settings()?.settings, Some(&seed.seed))?.hideout != Keep::Vanilla; let given: BM = actors_for(d, seed)?; let views: BM = crate::slice::tier_order::chest_views(d, seed)?; let wrapped: BM = flow_wraps(d, seed); for (loc, item) in &seed.placements { - if crate::pot_slice::targets::is_loc(d, loc) || crate::slice::skulls::is_skull(d, loc) || crate::shops::seed::skip(loc) || crate::slice::silver::is_item(item) { + if crate::hideout_keys::is_native(loc) || crate::pot_slice::targets::is_loc(d, loc) || crate::slice::skulls::is_skull(d, loc) || crate::shops::seed::skip(loc) || crate::slice::silver::is_item(item) { continue; } if let Some(t) = crate::slice::silver::targets(loc, item)? { @@ -252,16 +274,18 @@ pub(crate) fn targets_with(d: &Data, seed: &SeedFile, roam: bool, fixed: &BM chest_drop(f, views.get(loc.as_str()).map(|s| s.as_str()))?, - None => fixed.get(loc).or_else(|| given.get(loc)).cloned().ok_or_else(|| E::Msg(format!("{loc} was given no item actor")))?, + let new_actor: String = if hideout && new.kind == "HideoutSmallKey" { + new.actor.clone().ok_or_else(|| E::Msg(format!("{item} has no key actor")))? + } else { + match family { + Some(f) => chest_drop(f, views.get(loc.as_str()).map(|s| s.as_str()))?, + None => fixed.get(loc).or_else(|| given.get(loc)).cloned().ok_or_else(|| E::Msg(format!("{loc} was given no item actor")))?, + } }; // A story chest or the Treasure Chest Game prize keeps its event; its key is credited // after it (crate::debug_names::stage_credit_chests). let story: bool = loc == crate::slice::treasure::LOC || d.cat.by_name(loc).is_some_and(|l| l.refs.iter().any(|r| d.events.keep.contains(&r.hash))); - let key: Option<&'static str> = if roam && new.kind == "SmallKey" && !story { + let key: Option<&'static str> = if (roam && new.kind == "SmallKey" && !story) || (hideout && new.kind == "HideoutSmallKey") { let name: &str = new.dungeon.as_deref().unwrap_or(""); Some(key_dungeon(name).ok_or_else(|| E::Msg(format!("{item} cannot be placed in a chest, no key count belongs to it")))?) } else { @@ -352,6 +376,21 @@ mod tests { assert!(placed > 0); } + #[test] + fn rings_get_generated_actors_in_chests_and_gifts() { + let d: Data = Data::load().unwrap(); + let chest: &str = "KF Midos Top Left Chest"; + let gift: &str = "LW Gift from Saria"; + for r in crate::key_rings::RINGS { + let places: BM = [(chest, r.item), (gift, r.item)].into_iter().map(|(l, i)| (l.to_string(), i.to_string())).collect(); + let seed: SeedFile = SeedFile::new("rings in a chest and a gift", &Settings::default(), "rings", places).unwrap(); + let given: BM = actors_for(&d, &seed).unwrap(); + let made: String = crate::key_rings::pack(r.actor); + assert_eq!(given.get(chest).map(String::as_str), Some(made.as_str()), "{}", r.item); + assert_eq!(given.get(gift).map(String::as_str), Some(made.as_str()), "{}", r.item); + } + } + #[test] fn the_net_count_is_applied_once() { let d: Data = Data::load().unwrap(); diff --git a/randomizer/core/src/slice/data.rs b/randomizer/core/src/slice/data.rs index 00801dcd..2f0a3999 100644 --- a/randomizer/core/src/slice/data.rs +++ b/randomizer/core/src/slice/data.rs @@ -166,6 +166,21 @@ pub fn parse_items(t: &str) -> Res> { .unwrap_or_default(), }); } + + + + for r in crate::key_rings::all_with_hideout() { + let Some(item) = out.iter_mut().find(|i| i.name == r.item) else { + continue; + }; + item.kind = "Item".to_string(); + item.adv = true; + item.actor = Some(crate::key_rings::pack(r.actor)); + item.conf = "exact".to_string(); + item.dungeon = None; + item.tiers.clear(); + item.world.clear(); + } Ok(out) } @@ -401,6 +416,25 @@ mod tests { assert!(d.scan.game.starts_with("oot-remake:")); } + #[test] + fn rings_become_generated_items_without_duplicate_rows() { + let d: Data = Data::load().unwrap(); + for r in crate::key_rings::all_with_hideout() { + let i: &Item = d.item(r.item).unwrap(); + assert_eq!(i.kind, "Item", "{}", r.item); + assert_eq!(i.actor.as_deref(), Some(crate::key_rings::pack(r.actor).as_str()), "{}", r.item); + assert_eq!(i.conf, "exact", "{}", r.item); + assert!(i.adv, "{}", r.item); + assert!(i.dungeon.is_none(), "{}", r.item); + assert!(i.tiers.is_empty() && i.world.is_empty(), "{}", r.item); + } + assert_eq!( + d.items.iter().filter(|i| i.name == "Small Key Ring (Forest Temple)").count(), + 1 + ); + assert_eq!(d.items.iter().filter(|i| i.name == crate::key_rings::HIDEOUT_RING.item).count(), 1); + } + #[test] fn state_names_round_trip() { for s in [State::Eligible, State::Pool, State::Event, State::Check, State::Special, State::Unmapped, State::Mismatch] { diff --git a/randomizer/core/src/slice/dungeon_items.rs b/randomizer/core/src/slice/dungeon_items.rs index ab0f0e81..34064fd3 100644 --- a/randomizer/core/src/slice/dungeon_items.rs +++ b/randomizer/core/src/slice/dungeon_items.rs @@ -637,7 +637,6 @@ mod tests { let out: std::path::PathBuf = b.root.join("romfs"); let mut rf: crate::romfs::Romfs = crate::romfs::Romfs::open(root).unwrap(); let mut away: usize = 0; - let shared: std::collections::BTreeMap<(String, u64), u64> = crate::slice::copies::shared(&d, &g.seed_file.placements); for (loc, item) in &g.seed_file.placements { let Some(i) = d.item(item).filter(|i| Kind::of(&i.kind).is_some_and(|k| gr.sweep.contains(&k))) else { continue; @@ -658,7 +657,7 @@ mod tests { for f in &r.files { let old: Byml = Byml::parse(&rf.read_zs(f).unwrap()).unwrap(); let new: Byml = Byml::parse(&rf.zs.decompress(&std::fs::read(out.join(f)).unwrap()).unwrap()).unwrap(); - let a: &crate::byml::Node = actor(&new, shared.get(&(f.clone(), r.hash)).copied().unwrap_or(r.hash)).unwrap_or_else(|| panic!("{loc}: no chest {} in {f}", r.hash)); + let a: &crate::byml::Node = actor(&new, r.hash).unwrap(); // The vanilla chest may have no drop field yet (slice::banc::DEFAULT_DROPS). let v: &crate::byml::Node = old.root.get("Actors").and_then(|l| l.as_arr()).and_then(|l| l.iter().find(|a| crate::placement::hash_of(a) == Some(r.hash))).unwrap(); let size: Size = Size::of_gyaml(a.get("Gyaml").and_then(|x| x.as_str()).unwrap_or("")); diff --git a/randomizer/core/src/slice/edit.rs b/randomizer/core/src/slice/edit.rs index c1486340..690327fb 100644 --- a/randomizer/core/src/slice/edit.rs +++ b/randomizer/core/src/slice/edit.rs @@ -9,17 +9,17 @@ use crate::error::{Error as E, Res}; use crate::modpack::{Host, Pack}; use crate::pickup_persist::Extra; use crate::placement::banc_files; -use crate::progressive::{stage as stage_upgrades, Size}; +use crate::progressive::Size; use crate::romfs::Romfs; use crate::rsizetable::{self, Rst}; use crate::settings::seed::SeedFile; -use crate::slice::support::Songs; +use crate::slice::support::{Keep, Songs}; use crate::special; use crate::slice::banc::fingerprint; use crate::slice::data::Data; use crate::slice::flow_wrap::{grants as wrap_grants, wraps as flow_wraps}; use crate::slice::pickups as pu; -use crate::slice::support::plan; +use crate::slice::support::plan_with_seed as plan; use crate::zs; pub use crate::slice::banc_edit::{Edited, edit_file, edit_file_with}; @@ -143,7 +143,7 @@ pub fn build_for(seed: &SeedFile, romfs: &P, load: &P, mod_name: &str, host: Hos pub fn build_with(seed: &SeedFile, romfs: &P, load: &P, mod_name: &str, host: Host, extra: &Extra) -> Res { let d: Data = Data::load()?; let loaded = seed.settings()?; - let p = plan(&loaded.settings)?; + let p = plan(&loaded.settings, Some(&seed.seed))?; let d: Data = crate::slice::treasure::with(d, p.treasure); let mut rf: Romfs = Romfs::open(romfs)?; let have: String = fingerprint(&rf, &d.scan.files)?; @@ -156,6 +156,8 @@ pub fn build_with(seed: &SeedFile, romfs: &P, load: &P, mod_name: &str, host: Ho ))); } let roam: bool = p.keys_roam(); + let hideout: bool = p.hideout != Keep::Vanilla; + let hideout_ring: bool = p.hideout_ring; let gift_keys: Vec = crate::gift_keys::gifts(&d, seed)?; let key_cs: Vec = crate::debug_names::key_credits(&d, seed); // Dungeon items at NPCs with their own events, sale offers, story chests and the Treasure @@ -179,6 +181,10 @@ pub fn build_with(seed: &SeedFile, romfs: &P, load: &P, mod_name: &str, host: Ho } } let mut keys: Vec<&'static str> = if roam { KEY_DUNGEONS.to_vec() } else { Vec::new() }; + + if hideout && !hideout_ring && !keys.contains(&"GerudoFortress") { + keys.push("GerudoFortress"); + } for k in crate::gift_keys::small_dungeons(&gift_keys) { if !keys.contains(&k) { keys.push(k); @@ -219,7 +225,7 @@ pub fn build_with(seed: &SeedFile, romfs: &P, load: &P, mod_name: &str, host: Ho resized }; let raw: &[u8] = resized.as_deref().unwrap_or(&vanilla); - let e: Option = edit_file_with(&f, raw, &ts, roam, &small_hearts, &lifts, &wrapped_chests)?; + let e: Option = edit_file_with(&f, raw, &ts, roam || p.rings || hideout_ring, &small_hearts, &lifts, &wrapped_chests)?; let e: Option = match (e, &resized) { (Some(mut e), Some(_)) => { e.old_len = vanilla.len(); @@ -237,6 +243,7 @@ pub fn build_with(seed: &SeedFile, romfs: &P, load: &P, mod_name: &str, host: Ho }), (e, None) => e, }; + let e: Option = crate::hideout_keys::edit_banc(&f, raw, e, &d, &p, seed, &order.assign)?; if let Some(e) = crate::slice::map_passes::run(&f, raw, e, &mut passes)? { edits.push(e); } @@ -301,8 +308,16 @@ pub fn build_with(seed: &SeedFile, romfs: &P, load: &P, mod_name: &str, host: Ho let placed: BM = flow_wraps(&d, seed); let chest_fams: BS<&str> = upgrades.iter().map(|u| u.0.as_str()).collect(); let gs: Vec = wrap_grants(&d, seed, &chest_fams, &placed); - if !upgrades.is_empty() || roam || gr.active() || !passes.silver_used.is_empty() { - let mut outs: Vec = if !upgrades.is_empty() || roam { stage_upgrades(&mut rf, &upgrades, None, &kids, &keys)? } else { Vec::new() }; + if !upgrades.is_empty() || roam || hideout || p.rings || hideout_ring || gr.active() || !passes.silver_used.is_empty() { + let mut outs: Vec = if !upgrades.is_empty() || roam || hideout || p.rings || hideout_ring { + let mut ring_folders: Vec<&'static str> = if p.rings { crate::key_rings::FOLDERS.to_vec() } else { Vec::new() }; + if hideout_ring && !ring_folders.contains(&crate::key_rings::HIDEOUT_RING.folder) { + ring_folders.push(crate::key_rings::HIDEOUT_RING.folder); + } + crate::progressive::stage_with(&mut rf, &upgrades, None, &kids, &keys, &ring_folders)? + } else { + Vec::new() + }; crate::dungeon_grant::stage(&mut rf, &mut outs, &gr, &passes.marks.used)?; crate::slice::silver::stage(&mut rf, &mut outs, &passes.silver_used)?; scrub_rows = crate::scrubs_b::stage_rows(&mut rf, &scrub_jobs, &mut outs, false)?; @@ -335,6 +350,7 @@ pub fn build_with(seed: &SeedFile, romfs: &P, load: &P, mod_name: &str, host: Ho }); let windows: Vec<(&str, &str)> = if arrows_key { vec![crate::story_skip::ITEM_GET] } else { Vec::new() }; crate::gift_keys::apply(&mut rf, &mut staged.files, &gift_keys, &windows)?; + crate::hideout_keys::stage_flow(&mut rf, &mut staged.files, &d, &p, seed, &order.assign)?; for f in &staged.files { pk.write_romfs(&f.path, &f.z)?; if f.new > f.old { @@ -369,11 +385,11 @@ pub fn build_with(seed: &SeedFile, romfs: &P, load: &P, mod_name: &str, host: Ho } marked.extend(flow_cs.iter().chain(chest_cs.iter()).filter_map(|c| match c.item { crate::gift_keys::Item::Other(k) => Some((k, c.dungeon)), - crate::gift_keys::Item::Small => None, + crate::gift_keys::Item::Small | crate::gift_keys::Item::Ring(_) => None, })); marked.extend(key_cs.iter().filter_map(|c| match c.item { crate::gift_keys::Item::Other(k) => Some((k, c.dungeon)), - crate::gift_keys::Item::Small => None, + crate::gift_keys::Item::Small | crate::gift_keys::Item::Ring(_) => None, })); let c: crate::slice::stages::Ctx = crate::slice::stages::Ctx { d: &d, @@ -557,6 +573,11 @@ pub fn build_with(seed: &SeedFile, romfs: &P, load: &P, mod_name: &str, host: Ho crate::ocarina_hold::stage(&mut rf, &mut late, &work, crate::ocarina_hold::picked_up(&d, seed))?; // Rooms that could lock Link in once their item is shuffled away (crate::dungeon_fixes). crate::dungeon_fixes::stage(&mut rf, &mut late, &work)?; + + + if p.rings || hideout_ring { + crate::key_ring_credit::stage_flows(&mut rf, &mut late, &work, &p.all_rings())?; + } if p.short { crate::short_get::stage(&mut rf, &mut late, &work)?; } @@ -1089,9 +1110,9 @@ mod tests { } // Every flow location takes every item: the build stages the choices in untested mode, // so a name no game flow hands out is listed as untested instead of refused. - let songs: bool = plan(&st).unwrap().songs != Songs::Off; + let songs: bool = plan(&st, None).unwrap().songs != Songs::Off; let (_, _, untested): (Vec, usize, Vec) = - crate::flow_locations::plan(&d.flow, &flows, &FlowOpts { songs, untested: true, trades: plan(&st).unwrap().rewards.trade_items }).unwrap_or_else(|e| panic!("seed split {n}: {e}")); + crate::flow_locations::plan(&d.flow, &flows, &FlowOpts { songs, untested: true, trades: plan(&st, None).unwrap().rewards.trade_items }).unwrap_or_else(|e| panic!("seed split {n}: {e}")); for c in &flows { // Reward events hand out any item a chest gives, through its chest content actor (#24). let allowed: bool = g.seed_file.placements.get(&c.location).and_then(|it| d.item(it)).is_some_and(|i| crate::slice::flow_rules::allows(&d, &c.location, i) || crate::slice::flow_rules::linked(i, &c.item)); diff --git a/randomizer/core/src/slice/fill.rs b/randomizer/core/src/slice/fill.rs index e585891f..8f97fe83 100644 --- a/randomizer/core/src/slice/fill.rs +++ b/randomizer/core/src/slice/fill.rs @@ -322,6 +322,7 @@ pub fn fill_ordered( #[cfg(test)] mod tests { use super::*; + use crate::settings::Value; use crate::slice::logic::{world, world_with}; #[test] @@ -339,6 +340,25 @@ mod tests { assert!(w.start.iter().all(|(i, _)| !w.items.names[*i].starts_with("Small Key"))); } + #[test] + fn removing_a_ring_removes_all_of_its_keys() { + let d: Data = Data::load().unwrap(); + let mut s: crate::settings::Settings = crate::settings::Settings::default(); + s.set(crate::key_rings::SETTING, Value::Bool(true)).unwrap(); + s.set("shuffle_smallkeys", Value::s("keysanity")).unwrap(); + let p: crate::slice::support::Plan = crate::slice::support::plan(&s).unwrap(); + let w: World = world_with(&d, &p.logic()).unwrap(); + for r in crate::key_rings::RINGS { + let ring: crate::logic_items::ItemId = w.item(r.item).unwrap(); + let key: crate::logic_items::ItemId = w.item(r.key).unwrap(); + let mut search: crate::search::Search = crate::search::Search::new(&w); + search.add(ring, 1); + assert_eq!(search.cnt[key], r.count, "{}", r.item); + search.remove(ring); + assert_eq!(search.cnt[key], 0, "{}", r.item); + } + } + #[test] fn each_vanilla_key_layout_needs_its_own_slack() { let d: Data = Data::load().unwrap(); diff --git a/randomizer/core/src/slice/generate.rs b/randomizer/core/src/slice/generate.rs index 29efbde4..e2299dfa 100644 --- a/randomizer/core/src/slice/generate.rs +++ b/randomizer/core/src/slice/generate.rs @@ -15,7 +15,7 @@ use crate::slice::logic::world_with; use crate::slice::pick::{pick, scoped, Pick}; use crate::slice::pickups as pu; use crate::slice::plando::{loc_of, resolve, Entry}; -use crate::slice::support::{plan, Keep, Plan, Songs}; +use crate::slice::support::{plan, plan_with_seed, Keep, Plan, Songs}; use crate::slice::watch::{Live, Watch}; use crate::spoiler::{playthrough, Spoiler}; use crate::world::{LocId, Placement, World}; @@ -108,7 +108,18 @@ pub fn allowed(d: &Data, w: &World, p: &Plan, it: ItemId, l: LocId) -> bool { if !buildable(d, w, p, it, l) { return false; } + if let Some(ok) = crate::slice::place_rules::verdict(&spot) { + return ok; + } let here: Option<&str> = w.regions[w.locs[l].region].dungeon.as_deref(); + if let Some(r) = crate::key_rings::by_item(&w.items.names[it]) { + return match p.keys.small { + Keep::Dungeon => here == Some(r.dungeon), + Keep::AnyDungeon => here.is_some(), + Keep::Vanilla => false, + Keep::Anywhere | Keep::Overworld | Keep::Regional | Keep::Start | Keep::Lacs => true, + }; + } if scoped(p, &i.kind) { return i.dungeon.is_some() && i.dungeon.as_deref() == here; } @@ -250,8 +261,23 @@ pub fn generate_data(d: &Data, s: &Settings, seed: &str, o: &GenOpts) -> Res = p.logic(); + let mut xs: Vec<&'static crate::key_rings::Ring> = Vec::new(); + if p.rings { + for e in &o.plando { + if let Some(r) = crate::key_rings::by_item(&e.item) { + logic.push((r.select, "true")); + if !p.active_rings.contains(&r) && !xs.contains(&r) { + xs.push(r); + } + } + } + } let room: crate::shops::layout::Room = crate::shops::rules::room(d, &p)?; let forced: Vec = o.plando.iter().map(|e| e.location.clone()).collect(); let mut lay: Option = crate::shops::layout::of_with(&p.shops, seed, room, &forced)?; @@ -259,8 +285,8 @@ pub fn generate_data(d: &Data, s: &Settings, seed: &str, o: &GenOpts) -> Res = lay.as_ref().map(|l| crate::shops::logic::data_with(d, l)).transpose()?; let d: &Data = owned.as_ref().unwrap_or(d); let mut w: World = match &lay { - Some(l) => crate::shops::logic::world(d, &p.logic(), l)?, - None => world_with(d, &p.logic())?, + Some(l) => crate::shops::logic::world(d, &logic, l)?, + None => world_with(d, &logic)?, }; let mut named: Vec = Vec::with_capacity(p.excluded.len()); for e in &p.excluded { @@ -294,6 +320,13 @@ pub fn generate_data(d: &Data, s: &Settings, seed: &str, o: &GenOpts) -> Res) = crate::start_items::pool::base(d, &w, &p, &pooled, &pk.free)?; p.notes.extend(gone); + let mut ns: Vec = Vec::new(); + { + let ok = |it: ItemId, l: LocId| allowed(d, &w, &p, it, l); + crate::slice::rings::replace_with(d, &w, &p, &mut base, &pk.free, &ok, &mut ns, &xs)?; + crate::slice::rings::replace_hideout(d, &w, &p, &mut base, &pk.free, &ok, &mut ns)?; + } + p.notes.extend(ns); if p.rewards.trade_items { let n: Vec = crate::open_world::trade_shuffle::pool(d, &w, &pk.free, &mut base)?; p.notes.extend(n); @@ -320,6 +353,8 @@ pub fn generate_data(d: &Data, s: &Settings, seed: &str, o: &GenOpts) -> Res Res g, // A run out of time (or cancelled) stops here with that message, not a retry's. Err(_) if quick && watch.check().is_ok() => { @@ -579,6 +614,53 @@ mod tests { } } + #[test] + fn key_ring_count_and_random_modes_generate_with_matching_build_plans() { + use crate::key_rings; + + let d: Data = Data::load().unwrap(); + let seed: &str = "key ring smoke seed"; + for mode in ["count", "random"] { + let mut s: Settings = all_chests(); + s.set("shuffle_smallkeys", Value::s("keysanity")).unwrap(); + s.set(key_rings::SETTING, Value::Bool(true)).unwrap(); + s.set(key_rings::MODE_SETTING, Value::s(mode)).unwrap(); + if mode == "count" { + s.set(key_rings::COUNT_SETTING, Value::Int(3)).unwrap(); + } + let expected: Vec<&'static key_rings::Ring> = if mode == "count" { + key_rings::count(seed, 3) + } else { + key_rings::random(seed).1 + }; + let a: Plan = plan_with_seed(&s, Some(seed)).unwrap(); + assert_eq!(a.active_rings, expected, "{mode}"); + + let o: GenOpts = GenOpts { tries: 40, ..GenOpts::default() }; + let g: Generated = generate_data(&d, &s, seed, &o).unwrap_or_else(|e| panic!("{mode}: {e}")); + let loaded: crate::settings::Loaded = g.seed_file.settings().unwrap(); + let b: Plan = plan_with_seed(&loaded.settings, Some(&g.seed_file.seed)).unwrap(); + assert_eq!(b.ring_mode, a.ring_mode, "{mode}"); + assert_eq!(b.ring_count, a.ring_count, "{mode}"); + assert_eq!(b.active_rings, expected, "{mode}"); + assert_eq!(loaded.settings.text(key_rings::MODE_SETTING).unwrap(), mode); + assert!(g.report.contains("seed-randomized standard dungeons"), "{mode}: {}", g.report); + + for r in &key_rings::RINGS { + let active: bool = expected.iter().any(|x| x.item == r.item); + let rings: usize = g.seed_file.placements.values().filter(|v| v.as_str() == r.item).count(); + let keys: usize = g.seed_file.placements.values().filter(|v| v.as_str() == r.key).count(); + if active { + assert_eq!(rings, 1, "{}: {rings} ring placements", r.dungeon); + assert_eq!(keys, 0, "{}: {keys} key placements", r.dungeon); + } else { + assert_eq!(rings, 0, "{}: {rings} ring placements", r.dungeon); + assert!(keys > 0, "{}: inactive dungeon lost its small keys", r.dungeon); + } + } + } + } + #[test] fn verified_event_chests_are_part_of_the_pool() { let d: Data = Data::load().unwrap(); @@ -704,6 +786,75 @@ mod tests { } } + fn rings_settings(mode: &str) -> Settings { + let mut s: Settings = with(&[("shuffle_chests", "all"), ("shuffle_smallkeys", mode)]); + s.set(crate::key_rings::SETTING, Value::Bool(true)).unwrap(); + s.set(crate::key_rings::MODE_SETTING, Value::s("all")).unwrap(); + s + } + + #[test] + fn key_rings_follow_the_small_key_scope() { + let d: Data = Data::load().unwrap(); + for mode in ["dungeon", "any_dungeon", "keysanity"] { + let s: Settings = rings_settings(mode); + let p: Plan = plan(&s).unwrap(); + let w: World = world_with(&d, &p.logic()).unwrap(); + for n in 0..3 { + let g: Generated = generate_data(&d, &s, &format!("ring scope {mode} {n}"), &GenOpts::default()).unwrap(); + assert!(rebuilt(&d, &p, &g.seed_file.placements), "{mode} {n} is not beatable"); + for (loc, item) in &g.seed_file.placements { + let Some(r) = crate::key_rings::by_item(item) else { + continue; + }; + let l: LocId = w.loc(loc).unwrap(); + let here: Option<&str> = w.regions[w.locs[l].region].dungeon.as_deref(); + match mode { + "dungeon" => assert_eq!(here, Some(r.dungeon), "{item} at {loc}"), + "any_dungeon" => assert!(here.is_some(), "{item} at {loc} is outside a dungeon"), + _ => {} + } + } + } + } + } + + #[test] + fn key_rings_are_reachable_without_their_own_keys() { + let d: Data = Data::load().unwrap(); + let s: Settings = rings_settings("keysanity"); + let p: Plan = plan(&s).unwrap(); + let w: World = world_with(&d, &p.logic()).unwrap(); + for n in 0..3 { + let g: Generated = generate_data(&d, &s, &format!("ring reach {n}"), &GenOpts::default()).unwrap(); + for (loc, item) in &g.seed_file.placements { + let Some(r) = crate::key_rings::by_item(item) else { + continue; + }; + let l: LocId = w.loc(loc).unwrap(); + let mut without: Placement = vanilla_place(&w, &d).unwrap(); + for i in 0..without.item.len() { + let clear: bool = without.item[i].is_some_and(|held| { + let name: &str = &w.items.names[held]; + name == r.key || crate::key_rings::by_item_any(name) == Some(r) + }); + if clear { + without.item[i] = None; + } + } + for (other, held) in &g.seed_file.placements { + let grants: bool = held == r.key || crate::key_rings::by_item_any(held) == Some(r); + if !grants { + without.put(w.loc(other).unwrap(), w.item(held).unwrap()); + } + } + let mut search: crate::search::Search = crate::search::Search::new(&w); + search.settle(&without, true); + assert!(search.loc_access(l), "{item} at {loc} needs its own key"); + } + } + } + const FOREST_FIRST: &str = "Forest Temple First Room Chest"; #[test] diff --git a/randomizer/core/src/slice/key_spots.rs b/randomizer/core/src/slice/key_spots.rs index 341fa68d..bf620e13 100644 --- a/randomizer/core/src/slice/key_spots.rs +++ b/randomizer/core/src/slice/key_spots.rs @@ -150,6 +150,12 @@ fn family(i: &Item) -> Option<&'static str> { family_of(&i.tiers) } +fn content_of(i: &Item) -> String { + + + crate::key_rings::by_item_any(&i.name).map(|r| r.actor.to_string()).unwrap_or_else(|| i.actor.clone().unwrap_or_default()) +} + pub fn contents(d: &Data, item: &str) -> Vec { let Some(i) = d.item(item) else { return Vec::new(); @@ -161,7 +167,7 @@ pub fn contents(d: &Data, item: &str) -> Vec { match family(i) { Some(f) if TOP_ONLY.contains(&f) => i.tiers.last().cloned().into_iter().collect(), Some(_) => i.tiers.clone(), - None => i.actor.clone().into_iter().collect(), + None => Some(content_of(i)).into_iter().collect(), } } @@ -208,7 +214,7 @@ pub fn resolve(d: &Data, item: &str, tier: Option<&str>) -> Res { (Some(t), _) => t.to_string(), (None, Some(f)) if TOP_ONLY.contains(&f) => i.tiers.last().cloned().unwrap_or_default(), (None, Some(_)) => return Err(E::Msg(format!("{item} is an upgrade, the tier order names no tier for its spot"))), - (None, None) => i.actor.clone().unwrap_or_default(), + (None, None) => content_of(i), }; if !contents(d, item).contains(&content) { return Err(E::Msg(format!("{item} as {content} has no pickup pack this build can place yet"))); @@ -227,6 +233,35 @@ pub fn resolve_kit(d: &Data, item: &str, tier: Option<&str>) -> Res { kit_pick(&p.content).ok_or_else(|| E::Msg(format!("{item} has no pickup pack a kit can carry ({})", p.content))) } + + +pub fn world_spot(d: &Data, loc: &str) -> bool { + d.pots.has(loc) + || crate::slice::skulls::is_skull(d, loc) + || crate::hideout_keys::is_native(loc) + || d.cat.by_name(loc).is_some_and(crate::slice::pickups::on_ground) +} + +pub fn resolve_drop(d: &Data, item: &str, tier: Option<&str>) -> Res { + let Some(r) = crate::key_rings::by_item_any(item) else { + return resolve_kit(d, item, tier); + }; + + + let _ = tier; + pick(&r.drop_item).ok_or_else(|| E::Msg(format!("{item} has no drop-form pickup pack this build can place"))) +} + +pub fn resolve_at(d: &Data, loc: &str, item: &str, tier: Option<&str>) -> Res { + if crate::key_rings::is_any_ring(item) && world_spot(d, loc) { + resolve_drop(d, item, tier) + } else if crate::slice::skulls::is_skull(d, loc) { + resolve_kit(d, item, tier) + } else { + resolve(d, item, tier) + } +} + pub fn top(f: &str) -> Option<&'static str> { tiers(f).ok().and_then(|t| t.last().copied()) } @@ -277,7 +312,7 @@ pub fn spoiler(d: &Data, w: &World, free: &[LocId], got: &Placement, assign: &BM continue; } let held: bool = d.pots.has(name); - let actor: String = match resolve(d, item, assign.get(name).map(|s| s.as_str())) { + let actor: String = match resolve_at(d, name, item, assign.get(name).map(|s| s.as_str())) { Ok(p) if crate::slice::skulls::is_skull(d, name) => p.hang(), Ok(p) => p.pack.clone(), Err(_) if held && crate::pot_slice::pickup::of(item).is_some_and(|a| !crate::pot_slice::pickup::refill(a)) => crate::pickup_pack::fall::dropped(crate::pot_slice::pickup::of(item).unwrap_or("")), @@ -424,5 +459,54 @@ mod tests { assert_eq!(k.heap, Some(199928)); assert!(pick("Item_Range_Bow").unwrap().kit_spec().is_err()); } + + #[test] + fn all_rings_resolve_to_generated_packs_at_every_pickup_spot() { + let d: Data = d(); + let pot: String = d.pots.state.iter().filter(|(n, s)| **s == crate::slice::data::State::Eligible && crate::slice::copies::copies(&d, n) < 2).map(|(n, _)| n.clone()).min().unwrap(); + let free: &str = "LLR Freestanding PoH"; + let skull: &str = "KF GS Bean Patch"; + let chest: &str = "KF Midos Top Left Chest"; + let gift: &str = "LW Gift from Saria"; + let native: &str = crate::hideout_keys::NATIVE[0]; + for r in crate::key_rings::all_with_hideout() { + let event_pack: String = crate::key_rings::pack(r.actor); + assert_eq!(contents(&d, r.item), vec![r.actor.to_string()], "{}", r.item); + let p: Pick = resolve(&d, r.item, None).unwrap_or_else(|e| panic!("{}: {e}", r.item)); + assert_eq!(p.pack, event_pack, "{}", r.item); + let (s, _): (Spec, Layers) = p.spec().unwrap(); + assert_eq!(s.item, r.actor, "{}", r.item); + assert_eq!(s.source(), "Item_Dungeon_SmallKey", "{}", r.item); + assert_eq!(s.identity_override(), Some(r.actor), "{}", r.item); + for loc in [chest, gift] { + assert_eq!(resolve_at(&d, loc, r.item, None).unwrap().pack, event_pack, "{} at {loc}", r.item); + } + + let drop_pack: String = crate::key_rings::drop_pack_any(r.actor); + let drop: Pick = resolve_drop(&d, r.item, None).unwrap_or_else(|e| panic!("{} drop: {e}", r.item)); + assert_eq!(drop.content, r.drop_item, "{}", r.item); + assert_eq!(drop.pack, drop_pack, "{}", r.item); + let (ds, dl): (Spec, Layers) = drop.spec().unwrap(); + assert_eq!(ds.item, r.drop_item, "{}", r.item); + assert_eq!(ds.name, r.drop_actor, "{}", r.item); + assert_eq!(ds.source(), "Item_Dungeon_SmallKey", "{}", r.item); + assert_eq!(ds.identity_override(), Some(r.actor), "{}", r.item); + assert_eq!(dl.ring.as_deref(), Some(r.actor), "{}", r.item); + assert!(dl.drop_ring, "{}", r.item); + for loc in [pot.as_str(), free, skull, native] { + assert_eq!(resolve_at(&d, loc, r.item, None).unwrap().pack, drop_pack, "{} at {loc}", r.item); + } + for at in [Spot::Free, Spot::Pot, Spot::Skull] { + assert!(placeable(&d, r.item, at), "{} at {at:?}", r.item); + } + let k: Spec = p.kit_spec().unwrap(); + assert_eq!(k.name, format!("{event_pack}_GS"), "{}", r.item); + assert_eq!(k.item, r.actor, "{}", r.item); + assert_eq!(k.source(), "Item_Dungeon_SmallKey", "{}", r.item); + assert_eq!(k.identity_override(), Some(r.actor), "{}", r.item); + assert!(drop.kit_spec().is_ok(), "{}", r.item); + assert_eq!(drop.kit(), format!("{drop_pack}_GS"), "{}", r.item); + } + } } diff --git a/randomizer/core/src/slice/logic.rs b/randomizer/core/src/slice/logic.rs index b346f7fd..24cd9487 100644 --- a/randomizer/core/src/slice/logic.rs +++ b/randomizer/core/src/slice/logic.rs @@ -71,8 +71,30 @@ pub fn spec(d: &Data, over: &[(&str, &str)]) -> Res { // condition. Otherwise they are not progress, so the fill may put them where the logic never // goes (a Piece of Heart behind a bean spot nobody can plant). let hearts: bool = HEART_GOALS.iter().any(|k| s.settings.get(k) == Some(&Val::Str("hearts".to_string()))); + let rings: bool = s.settings.flag(crate::key_rings::SETTING); + let hideout_ring: bool = s.settings.flag(crate::key_rings::HIDEOUT_SETTING); + let rs: Vec<&'static crate::key_rings::Ring> = if rings { + let picked: Vec<&'static crate::key_rings::Ring> = crate::key_rings::RINGS + .iter() + .filter(|r| s.settings.flag(r.select)) + .collect(); + + if picked.is_empty() { crate::key_rings::RINGS.iter().collect() } else { picked } + } else { + Vec::new() + }; for it in &d.items { let heart: bool = crate::slice::generate::HEARTS.iter().any(|h| it.name.starts_with(h)); + if let Some(r) = crate::key_rings::by_item_any(&it.name) { + let active: bool = rs.iter().any(|x| x.item == r.item) + || (hideout_ring && r.item == crate::key_rings::HIDEOUT_RING.item); + if active { + s.add_ring(r.item, r.key, r.count); + } else { + s.add_item(&it.name, it.adv && (hearts || !heart), 0); + } + continue; + } s.add_item(&it.name, it.adv && (hearts || !heart), 0); } s.add_helpers(HELPERS)?; diff --git a/randomizer/core/src/slice/pick.rs b/randomizer/core/src/slice/pick.rs index 8cbbea16..8c0b3292 100644 --- a/randomizer/core/src/slice/pick.rs +++ b/randomizer/core/src/slice/pick.rs @@ -189,6 +189,7 @@ pub fn pick(d: &Data, w: &World, p: &Plan) -> Pick { } } pu::select(d, w, p, &mut free, &mut left, &mut flow); + crate::gerudo_drops::add_checks(w, p, &mut free, &mut left); flow += crate::pot_slice::pick::add(d, w, p, &mut free, &mut left); let (sk, n): (Vec, usize) = crate::slice::skulls::pick(d, w, p, &mut left); free.extend(sk); diff --git a/randomizer/core/src/slice/place_rules.rs b/randomizer/core/src/slice/place_rules.rs index 558d9799..5ca4a3f1 100644 --- a/randomizer/core/src/slice/place_rules.rs +++ b/randomizer/core/src/slice/place_rules.rs @@ -30,6 +30,42 @@ pub fn setting_verdict(s: &Spot) -> Option { SETTING_RULES.iter().find_map(|(_, r)| r(s)) } +pub const RULES: [(&str, Rule); 2] = [ + ("native hideout guard drops", native_hideout), + ("hideout small keys", hideout_key), +]; + +pub fn verdict(s: &Spot) -> Option { + RULES.iter().find_map(|(_, r)| r(s)) +} + +fn native_hideout(s: &Spot) -> Option { + if !crate::hideout_keys::is_native(s.name) { + return None; + } + let i: &crate::slice::data::Item = s.d.item(s.item)?; + Some(crate::gerudo_drops::eligible(s.d, &i.name)) +} + +fn hideout_key(s: &Spot) -> Option { + if s.p.hideout == crate::slice::support::Keep::Vanilla { + return None; + } + let i: &crate::slice::data::Item = s.d.item(s.item)?; + if i.kind != "HideoutSmallKey" { + return None; + } + let here: Option<&str> = s.w.regions[s.w.locs[s.l].region].dungeon.as_deref(); + let dungeon: bool = here.is_some(); + let place: bool = match s.p.hideout { + crate::slice::support::Keep::AnyDungeon => dungeon, + _ => true, + }; + let chest: bool = s.d.flow.by_name(s.name).is_none() && !s.d.special(s.name) && crate::slice::dungeon_items::chest_ok(s.d, s.name) && s.d.cat.by_name(s.name).is_some_and(|c| c.kind == "chest"); + let gift: bool = crate::gift_keys::spot(s.d, s.name); + Some(place && i.dungeon.is_some() && (chest || gift)) +} + /// The adult trade chain keeps its items at home: the sequence is not shuffled, unless adult trade /// shuffle makes each trade item its own item (crate::open_world::trade_shuffle). fn adult_trade(s: &Spot) -> Option { diff --git a/randomizer/core/src/slice/rings.rs b/randomizer/core/src/slice/rings.rs new file mode 100644 index 00000000..702e10f7 --- /dev/null +++ b/randomizer/core/src/slice/rings.rs @@ -0,0 +1,303 @@ +use crate::error::{Error as E, Res}; +use crate::logic_items::ItemId; +use crate::slice::data::Data; +use crate::start_items::pool::JUNK; +use crate::slice::support::Plan; +use crate::world::{LocId, Placement, World}; + + + +pub fn replace( + d: &Data, + w: &World, + p: &Plan, + base: &mut Placement, + free: &[LocId], + ok: &dyn Fn(ItemId, LocId) -> bool, + notes: &mut Vec, +) -> Res<()> { + replace_with(d, w, p, base, free, ok, notes, &[]) +} + + + +pub fn replace_with( + d: &Data, + w: &World, + p: &Plan, + base: &mut Placement, + free: &[LocId], + ok: &dyn Fn(ItemId, LocId) -> bool, + notes: &mut Vec, + extra: &[&'static crate::key_rings::Ring], +) -> Res<()> { + if !p.rings { + return Ok(()); + } + if p.active_rings.is_empty() { + return Err(E::Msg("key rings: the active dungeons were not derived from a seed".to_string())); + } + let junk: ItemId = w.item(JUNK).ok_or_else(|| E::Msg(format!("{JUNK} is not in the logic item list")))?; + let mut changes: Vec = Vec::new(); + for r in &p.active_rings { + let key: ItemId = w.item(r.key).ok_or_else(|| E::Msg(format!("{} is not in the logic item list", r.key)))?; + let ring: ItemId = w.item(r.item).ok_or_else(|| E::Msg(format!("{} is not in the logic item list", r.item)))?; + let old: Vec = w.real.iter().copied().filter(|l| base.get(*l) == Some(key)).collect(); + if old.is_empty() { + return Err(E::Msg(format!("key rings: {} has no small keys to replace", r.dungeon))); + } + let primary: Option = old.iter().copied().find(|l| free.contains(l) && ok(ring, *l)); + let spare: Option = primary.or_else(|| { + free.iter().copied().find(|l| { + ok(ring, *l) + && base.get(*l).is_some_and(|i| { + i == junk || d.item(&w.items.names[i]).is_some_and(|it| !it.adv) + }) + }) + }); + let Some(at): Option = spare else { + return Err(E::Msg(format!("key rings: no free spot can hold {}", r.item))); + }; + for l in &old { + base.put(*l, junk); + } + base.put(at, ring); + changes.push(format!("{} ({} keys)", r.dungeon, r.count)); + } + for r in extra { + if p.active_rings.contains(r) { + continue; + } + let ring: ItemId = w.item(r.item).ok_or_else(|| E::Msg(format!("{} is not in the logic item list", r.item)))?; + let at: LocId = free + .iter() + .copied() + .find(|l| ok(ring, *l) && base.get(*l).is_some_and(|i| i == junk || d.item(&w.items.names[i]).is_some_and(|it| !it.adv))) + .ok_or_else(|| E::Msg(format!("key rings: no free spot can hold the plandoed {}", r.item)))?; + base.put(at, ring); + changes.push(format!("{} ({} keys, plandoed)", r.dungeon, r.count)); + } + notes.push(format!( + "Each standard dungeon's small keys were replaced by one key ring: {}. The former key slots hold {JUNK} unless one holds its ring. A ring named by plando keeps its dungeon's small keys shuffled.", + changes.join(", ") + )); + Ok(()) +} + + + +pub fn replace_hideout( + d: &Data, + w: &World, + p: &Plan, + base: &mut Placement, + free: &[LocId], + ok: &dyn Fn(ItemId, LocId) -> bool, + notes: &mut Vec, +) -> Res<()> { + if !p.hideout_ring { + return Ok(()); + } + let r: &'static crate::key_rings::Ring = &crate::key_rings::HIDEOUT_RING; + let junk: ItemId = w.item(JUNK).ok_or_else(|| E::Msg(format!("{JUNK} is not in the logic item list")))?; + let key: ItemId = w.item(r.key).ok_or_else(|| E::Msg(format!("{} is not in the logic item list", r.key)))?; + let ring: ItemId = w.item(r.item).ok_or_else(|| E::Msg(format!("{} is not in the logic item list", r.item)))?; + let old: Vec = w.real.iter().copied().filter(|l| base.get(*l) == Some(key)).collect(); + if old.len() != r.count as usize { + return Err(E::Msg(format!("key rings: Hideout has {} small keys to replace, expected {}", old.len(), r.count))); + } + let primary: Option = old.iter().copied().find(|l| free.contains(l) && ok(ring, *l)); + let spare: Option = primary.or_else(|| { + free.iter().copied().find(|l| { + ok(ring, *l) + && base.get(*l).is_some_and(|i| i == junk || d.item(&w.items.names[i]).is_some_and(|it| !it.adv)) + }) + }); + let Some(at): Option = spare else { + return Err(E::Msg(format!("key rings: no free spot can hold {}", r.item))); + }; + for l in &old { + base.put(*l, junk); + } + base.put(at, ring); + notes.push(format!( + "The four Thieves' Hideout small keys were replaced by one Hideout key ring. The former key slots hold {JUNK} unless one holds its ring." + )); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::error::Res; + use crate::logic_items::ItemId; + use crate::search::Search; + use crate::settings::{Settings, Value}; + use crate::slice::generate::allowed; + use crate::slice::logic::world_with; + use crate::slice::pick::pick; + use crate::start_items::pool; + use crate::slice::support::{plan, plan_with_seed}; + + fn setup() -> Res<(Data, World, Plan, Placement, crate::slice::pick::Pick)> { + let mut s: Settings = Settings::default(); + s.set(crate::key_rings::SETTING, Value::Bool(true))?; + s.set("shuffle_smallkeys", Value::s("keysanity"))?; + let d: Data = Data::load()?; + let p: Plan = plan(&s)?; + let w: World = world_with(&d, &p.logic())?; + let v: Placement = crate::slice::fill::vanilla_place(&w, &d)?; + let pk: crate::slice::pick::Pick = pick(&d, &w, &p); + Ok((d, w, p, v, pk)) + } + + #[test] + fn a_ring_grants_its_full_key_count_in_logic() { + let (_, w, _, _, _): (Data, World, Plan, Placement, crate::slice::pick::Pick) = setup().unwrap(); + let mut s: Search = Search::new(&w); + for r in crate::key_rings::RINGS { + let key: ItemId = w.item(r.key).unwrap(); + let ring: ItemId = w.item(r.item).unwrap(); + let before: u32 = s.cnt[key]; + s.add(ring, 1); + assert_eq!(s.cnt[key], before + r.count, "{}", r.item); + s.remove(ring); + assert_eq!(s.cnt[key], before, "{}", r.item); + } + } + + #[test] + fn one_ring_replaces_each_dungeons_small_keys() { + let (d, w, p, v, pk): (Data, World, Plan, Placement, crate::slice::pick::Pick) = setup().unwrap(); + let (mut base, _): (Placement, Vec) = pool::base(&d, &w, &p, &v, &pk.free).unwrap(); + let ok = |it: ItemId, l: LocId| allowed(&d, &w, &p, it, l); + let mut notes: Vec = Vec::new(); + replace(&d, &w, &p, &mut base, &pk.free, &ok, &mut notes).unwrap(); + for r in crate::key_rings::RINGS { + let key: ItemId = w.item(r.key).unwrap(); + let ring: ItemId = w.item(r.item).unwrap(); + assert_eq!(base.item.iter().filter(|i| **i == Some(key)).count(), 0, "{}", r.key); + assert_eq!(base.item.iter().filter(|i| **i == Some(ring)).count(), 1, "{}", r.item); + } + assert_eq!(base.item.len(), v.item.len()); + assert_eq!(notes.len(), 1); + for r in crate::key_rings::RINGS { + assert!(notes[0].contains(&format!("{} ({} keys)", r.dungeon, r.count)), "{}", notes[0]); + } + } + + #[test] + fn only_selected_dungeons_lose_their_individual_small_keys() { + let mut s: Settings = Settings::default(); + s.set("shuffle_smallkeys", Value::s("keysanity")).unwrap(); + s.set(crate::key_rings::SETTING, Value::Bool(true)).unwrap(); + s.set(crate::key_rings::MODE_SETTING, Value::s("selection")).unwrap(); + s.set(crate::key_rings::SELECTION_SETTING, Value::set(&["forest_temple"])).unwrap(); + let d: Data = Data::load().unwrap(); + let p: Plan = plan_with_seed(&s, Some("seed")).unwrap(); + let w: World = world_with(&d, &p.logic()).unwrap(); + let forest: &crate::key_rings::Ring = crate::key_rings::by_choice("forest_temple").unwrap(); + let fire: &crate::key_rings::Ring = crate::key_rings::by_choice("fire_temple").unwrap(); + let forest_ring: ItemId = w.item(forest.item).unwrap(); + assert_eq!(w.ring_key(forest_ring), Some((w.item(forest.key).unwrap(), forest.count as u32))); + let fire_ring: ItemId = w.item(fire.item).unwrap(); + assert!(w.ring_key(fire_ring).is_none()); + + let v: Placement = crate::slice::fill::vanilla_place(&w, &d).unwrap(); + let pk: crate::slice::pick::Pick = pick(&d, &w, &p); + let (mut base, _): (Placement, Vec) = pool::base(&d, &w, &p, &v, &pk.free).unwrap(); + let ok = |it: ItemId, l: LocId| allowed(&d, &w, &p, it, l); + let mut notes: Vec = Vec::new(); + replace(&d, &w, &p, &mut base, &pk.free, &ok, &mut notes).unwrap(); + let forest_key: ItemId = w.item(forest.key).unwrap(); + let fire_key: ItemId = w.item(fire.key).unwrap(); + assert_eq!(base.item.iter().filter(|i| **i == Some(forest_ring)).count(), 1); + assert_eq!(base.item.iter().filter(|i| **i == Some(forest_key)).count(), 0); + assert!(base.item.iter().any(|i| *i == Some(fire_key))); + assert!(notes[0].contains("Forest Temple (5 keys)")); + assert!(!notes[0].contains("Fire Temple")); + } + + #[test] + fn rings_are_left_alone_when_the_setting_is_off() { + let mut s: Settings = Settings::default(); + s.set("shuffle_smallkeys", Value::s("keysanity")).unwrap(); + let d: Data = Data::load().unwrap(); + let p: Plan = plan(&s).unwrap(); + let w: World = world_with(&d, &p.logic()).unwrap(); + let v: Placement = crate::slice::fill::vanilla_place(&w, &d).unwrap(); + let pk: crate::slice::pick::Pick = pick(&d, &w, &p); + let (mut base, _): (Placement, Vec) = pool::base(&d, &w, &p, &v, &pk.free).unwrap(); + let original: Vec> = base.item.clone(); + let ok = |it: ItemId, l: LocId| allowed(&d, &w, &p, it, l); + let mut notes: Vec = Vec::new(); + replace(&d, &w, &p, &mut base, &pk.free, &ok, &mut notes).unwrap(); + assert_eq!(base.item, original); + assert!(notes.is_empty()); + } + + fn setup_hideout() -> Res<(Data, World, Plan, Placement, crate::slice::pick::Pick)> { + let mut s: Settings = Settings::default(); + s.set("gerudo_fortress", Value::s("open"))?; + s.set("shuffle_hideoutkeys", Value::s("keysanity"))?; + s.set(crate::key_rings::HIDEOUT_SETTING, Value::Bool(true))?; + let d: Data = Data::load()?; + let p: Plan = plan(&s)?; + let w: World = world_with(&d, &p.logic())?; + let v: Placement = crate::slice::fill::vanilla_place(&w, &d)?; + let pk: crate::slice::pick::Pick = pick(&d, &w, &p); + Ok((d, w, p, v, pk)) + } + + #[test] + fn a_hideout_ring_grants_its_full_key_count_in_logic() { + let (_, w, p, _, _): (Data, World, Plan, Placement, crate::slice::pick::Pick) = setup_hideout().unwrap(); + let r: &'static crate::key_rings::Ring = &crate::key_rings::HIDEOUT_RING; + assert_eq!(p.all_rings().len(), 1); + assert!(p.active_rings.is_empty()); + let mut s: Search = Search::new(&w); + let key: ItemId = w.item(r.key).unwrap(); + let ring: ItemId = w.item(r.item).unwrap(); + let before: u32 = s.cnt[key]; + s.add(ring, 1); + assert_eq!(s.cnt[key], before + r.count); + s.remove(ring); + assert_eq!(s.cnt[key], before); + } + + #[test] + fn the_hideout_ring_replaces_four_hideout_keys() { + let (d, w, p, v, pk): (Data, World, Plan, Placement, crate::slice::pick::Pick) = setup_hideout().unwrap(); + let (mut base, _): (Placement, Vec) = pool::base(&d, &w, &p, &v, &pk.free).unwrap(); + let ok = |it: ItemId, l: LocId| allowed(&d, &w, &p, it, l); + let mut notes: Vec = Vec::new(); + replace_hideout(&d, &w, &p, &mut base, &pk.free, &ok, &mut notes).unwrap(); + let r: &'static crate::key_rings::Ring = &crate::key_rings::HIDEOUT_RING; + let key: ItemId = w.item(r.key).unwrap(); + let ring: ItemId = w.item(r.item).unwrap(); + assert_eq!(base.item.iter().filter(|i| **i == Some(key)).count(), 0); + assert_eq!(base.item.iter().filter(|i| **i == Some(ring)).count(), 1); + assert_eq!(base.item.len(), v.item.len()); + assert_eq!(notes.len(), 1); + assert!(notes[0].contains("Thieves' Hideout")); + } + + #[test] + fn the_hideout_ring_is_untouched_when_its_toggle_is_off() { + let mut s: Settings = Settings::default(); + s.set("gerudo_fortress", Value::s("open")).unwrap(); + s.set("shuffle_hideoutkeys", Value::s("keysanity")).unwrap(); + let d: Data = Data::load().unwrap(); + let p: Plan = plan(&s).unwrap(); + let w: World = world_with(&d, &p.logic()).unwrap(); + let v: Placement = crate::slice::fill::vanilla_place(&w, &d).unwrap(); + let pk: crate::slice::pick::Pick = pick(&d, &w, &p); + let (mut base, _): (Placement, Vec) = pool::base(&d, &w, &p, &v, &pk.free).unwrap(); + let original: Vec> = base.item.clone(); + let ok = |it: ItemId, l: LocId| allowed(&d, &w, &p, it, l); + let mut notes: Vec = Vec::new(); + replace_hideout(&d, &w, &p, &mut base, &pk.free, &ok, &mut notes).unwrap(); + assert_eq!(base.item, original); + assert!(notes.is_empty()); + } +} diff --git a/randomizer/core/src/slice/seed_packs.rs b/randomizer/core/src/slice/seed_packs.rs index 4a866ef1..40d6e6a1 100644 --- a/randomizer/core/src/slice/seed_packs.rs +++ b/randomizer/core/src/slice/seed_packs.rs @@ -15,7 +15,7 @@ use crate::rsizetable::{Rst, TABLE_PATH}; use crate::settings::seed::SeedFile; use crate::slice::data::Data; use crate::slice::edit::{build_with, Built}; -use crate::slice::key_spots::{resolve, shield, Pick}; +use crate::slice::key_spots::{resolve_at, shield, Pick}; use crate::slice::tier_order::{fixed_actors, Verdict}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -23,6 +23,7 @@ pub enum Kind { Free, Holder, Skull, + Native, } impl Kind { @@ -49,6 +50,9 @@ impl Want { } fn kind_of(d: &Data, loc: &str, item: &str) -> Option { + if crate::hideout_keys::is_native(loc) { + return crate::gerudo_drops::eligible(d, item).then_some(Kind::Native); + } if crate::slice::skulls::is_skull(d, loc) { let t: crate::slice::skulls::Table = crate::slice::skulls::table().ok()?; let shipped: bool = item == crate::slice::skulls::TOKEN || crate::slice::skulls::pickup(&t, d, item).is_some(); @@ -74,10 +78,9 @@ pub fn need(d: &Data, seed: &SeedFile, fixed: &BM) -> Res = if k.kit() { crate::slice::key_spots::resolve_kit(d, item, fixed.get(loc).map(|s| s.as_str())) } else { resolve(d, item, fixed.get(loc).map(|s| s.as_str())) }; - let p: Pick = match found { + let p: Pick = match resolve_at(d, loc, item, fixed.get(loc).map(|s| s.as_str())) { Ok(p) => p, - // A boss heart whose item has no pack keeps the chest it always had (crate::boss_heart). + Err(_) if d.cat.by_name(loc).is_some_and(|l| l.kind == "bossheart") => continue, Err(e) => return Err(E::Msg(format!("{loc} holds {item}, which this build cannot place there yet: {e}"))), }; @@ -85,12 +88,25 @@ pub fn need(d: &Data, seed: &SeedFile, fixed: &BM) -> Res, dry: bool) -> Opts { fn run_one(romfs: &P, load: &P, mod_name: &str, w: &Want, o: &Opts) -> Res { let (s, mut l): (Spec, Layers) = w.spec()?; - // Every pickup the seed places turns in place, off the floor. + l.spin = true; if w.kind.kit() { return kit::run_with(romfs, load, mod_name, &s, o, &[], &l); @@ -171,6 +187,7 @@ pub fn audit(rf: &mut Romfs, base: &P, wants: &BM) -> Res "on the ground", Kind::Holder => "dropped by a pot, crate, flying pot, beehive, rock or grass tuft", Kind::Skull => "skulltula kit drop", + Kind::Native => "Gerudo carpenter guard drop", })); } for y in &ys { @@ -250,7 +267,7 @@ mod tests { let s: SeedFile = seed(&[(free, "Boomerang"), (pot.as_str(), "Megaton Hammer"), (skull, "Progressive Hookshot"), ("KF Midos Top Left Chest", "Bow")]); let fixed: BM = [(skull.to_string(), "Item_Hookshot".to_string())].into_iter().collect(); let w: BM = need(&d, &s, &fixed).unwrap(); - // Every seed also builds the song and Ocarina pickups the story skips hold up (crate::ocarina_hold). + let scene: Vec = crate::ocarina_hold::wanted(&d, &s).into_iter().map(|(_, p)| p.pack).collect(); let names: Vec<&str> = w.keys().map(|k| k.as_str()).filter(|k| !scene.iter().any(|x| x == k)).collect(); assert_eq!(names, vec!["Obj_Boomerang", "Obj_Hammer", "Obj_Hookshot_GH"]); @@ -266,8 +283,8 @@ mod tests { assert!(need(&d, &s, &BM::new()).is_err()); let plain: SeedFile = seed(&[(free, "Rupees (5)"), (pot.as_str(), "Rupees (20)"), ("KF Midos Top Left Chest", "Bow")]); assert!(need(&d, &plain, &BM::new()).unwrap().keys().all(|k| scene.iter().any(|x| x == k))); - // A kit cannot carry the Bow's ammo layer, so a skulltula drops the plain Bow kit (the - // starter bag hook adds the quiver after its get); a Bow on the ground keeps the ammo layer. + + let bow: SeedFile = seed(&[(skull, "Bow"), (free, "Bow")]); let wbow: BM = need(&d, &bow, &[(skull.to_string(), "Item_Range_Bow".to_string()), (free.to_string(), "Item_Range_Bow".to_string())].into_iter().collect()).unwrap(); assert_eq!(wbow["Obj_Range_Bow_GH"].kind, Kind::Skull); @@ -283,6 +300,40 @@ mod tests { assert!(need(&d, &shipped, &BM::new()).unwrap().keys().all(|k| scene.iter().any(|x| x == k))); } + #[test] + fn rings_are_written_as_packs_from_chests_gifts_pots_and_skulls() { + let d: Data = Data::load().unwrap(); + let r: &'static crate::key_rings::Ring = &crate::key_rings::RINGS[0]; + let pot: String = d.pots.state.iter().filter(|(n, s)| **s == crate::slice::data::State::Eligible && crate::slice::copies::copies(&d, n) < 2).map(|(n, _)| n.clone()).min().unwrap(); + let free: &str = "LLR Freestanding PoH"; + let chest: &str = "KF Midos Top Left Chest"; + let gift: &str = "LW Gift from Saria"; + let skull: &str = "KF GS Bean Patch"; + let s: SeedFile = seed(&[(chest, r.item), (gift, r.item), (pot.as_str(), r.item), (free, r.item), (skull, r.item)]); + let fixed: BM = [(skull.to_string(), r.actor.to_string())].into_iter().collect(); + let w: BM = need(&d, &s, &fixed).unwrap(); + + let event: String = crate::key_rings::pack(r.actor); + let given: &Want = &w[&event]; + for loc in [chest, gift] { + assert!(given.spots.contains(&loc.to_string()), "{loc} has no event ring pack"); + } + assert_eq!(given.spec().unwrap().0.item, r.actor); + + let drop: String = crate::key_rings::drop_pack(r.actor); + let world: &Want = &w[&drop]; + for loc in [pot.as_str(), free, skull] { + assert!(world.spots.contains(&loc.to_string()), "{loc} has no drop ring pack"); + } + assert!(matches!(world.kind, Kind::Free | Kind::Holder), "{:?}", world.kind); + let (spec, layers): (Spec, Layers) = world.spec().unwrap(); + assert_eq!(spec.item, r.drop_item); + assert_eq!(spec.name, r.drop_actor); + assert_eq!(spec.identity_override(), Some(r.actor)); + assert!(layers.drop_ring); + assert_eq!(w[&kit::hang_of(&drop)].kind, Kind::Skull); + } + fn real() -> Option { let p: PB = ootrr_game::test_romfs::path(); if p.join("Pack").join("ZsDic.pack.zs").is_file() { @@ -623,10 +674,11 @@ mod tests { return; }; let d: Data = Data::load().unwrap(); - // The story skips always hand out the lessons' songs and the Ocarinas with the item get, as - // their pickups (crate::ocarina_hold), so every seed builds those packs; a seed with no - // other new item at a pickup spot builds only them. + + + let scene = |g: &Generated| -> std::collections::BTreeSet { crate::ocarina_hold::wanted(&d, &g.seed_file).into_iter().map(|(_, p)| p.pack).collect() }; + let mut s: Settings = Settings::default(); s.set("shuffle_rewards", crate::settings::Value::s("off")).unwrap(); s.set("shuffle_chests", crate::settings::Value::s("off")).unwrap(); diff --git a/randomizer/core/src/slice/skull_kit.rs b/randomizer/core/src/slice/skull_kit.rs index 6a0a0b29..fd8cbafd 100644 --- a/randomizer/core/src/slice/skull_kit.rs +++ b/randomizer/core/src/slice/skull_kit.rs @@ -30,7 +30,7 @@ pub fn actors(ds: &[Drop]) -> BS<&str> { fn spec(kit: &str) -> Res { let from: &str = parent_of(kit).ok_or_else(|| E::Msg(format!("{kit} is not a kit pickup, a skulltula that drops it would come back after every visit")))?; - Ok(Spec { item: from.to_string(), name: kit.to_string(), style: Style::Touch, heap: None }) + Ok(Spec { item: from.to_string(), name: kit.to_string(), style: Style::Touch, heap: None, source: None, identity: None }) } pub fn build(rf: &mut Romfs, token: &[Entry], kit: &str) -> Res { @@ -319,7 +319,7 @@ mod tests { return; }; let mut rf: Romfs = Romfs::open(&root).unwrap(); - let s: Spec = Spec { item: "Item_Hookshot".to_string(), name: "Obj_Hookshot_GS".to_string(), style: Style::Touch, heap: None }; + let s: Spec = Spec { item: "Item_Hookshot".to_string(), name: "Obj_Hookshot_GS".to_string(), style: Style::Touch, heap: None, source: None, identity: None }; let o: Opts = Opts { host: Host::Hookshot, base: None, rst_from: None, places: Vec::new(), dry: true }; let done: Done = crate::pickup_pack::kit::run(&root, P::new("unused"), "unused", &s, &o, &[TREE]).unwrap(); let x: Extra = crate::pickup_pack::guard::extra(&done.files, &done.carried).unwrap(); diff --git a/randomizer/core/src/slice/skulls.rs b/randomizer/core/src/slice/skulls.rs index d25b4945..10bb097c 100644 --- a/randomizer/core/src/slice/skulls.rs +++ b/randomizer/core/src/slice/skulls.rs @@ -97,7 +97,7 @@ pub fn drop_actor(t: &Table, d: &Data, item: &str, tier: Option<&str>) -> Res { @@ -26,12 +26,13 @@ pub struct Ctx<'a> { pub type Stage = fn(&mut Romfs, &Ctx, &mut Vec) -> Res<()>; -pub const STAGES: [(&str, Stage); 27] = [ +pub const STAGES: [(&str, Stage); 30] = [ ("boss heart chests", boss_hearts), ("songs", songs), ("song models", song_models), ("hints", hints), ("dungeon item text", dungeon_text), + ("key ring text", key_ring_text), ("scrub hint text", scrub_hints), ("fairy price text", fairy_text), ("silver rupee text", silver_text), @@ -50,6 +51,8 @@ pub const STAGES: [(&str, Stage); 27] = [ ("starting items", start_items), ("dpad items", dpad), ("pot rows", pot_rows), + ("hideout drop rows", hideout_drop_rows), + ("key ring flags", key_ring_flags), ("start defaults", start_defaults), ("scrub rows", scrub_rows), ("debug location names", debug_names), @@ -100,6 +103,13 @@ fn dungeon_text(rf: &mut Romfs, c: &Ctx, more: &mut Vec) -> Res<()> { crate::dungeon_packs::stage_text(rf, more, &crate::dungeon_packs::placed(c.d, c.seed)) } +fn key_ring_text(rf: &mut Romfs, c: &Ctx, more: &mut Vec) -> Res<()> { + if c.p.rings || c.p.hideout_ring { + crate::key_ring_text::stage(rf, c.work, more, &c.p.all_rings())?; + } + Ok(()) +} + fn scrub_hints(rf: &mut Romfs, c: &Ctx, more: &mut Vec) -> Res<()> { crate::scrub_prices::stage_text(rf, c.d, c.seed, c.p.rewards.scrub_hint, more) } @@ -133,8 +143,8 @@ fn door_fix(rf: &mut Romfs, c: &Ctx, more: &mut Vec) -> Res<()> { Ok(()) } -fn no_tutorials(rf: &mut Romfs, _: &Ctx, more: &mut Vec) -> Res<()> { - more.push(crate::no_tutorials::stage(rf)?); +fn no_tutorials(rf: &mut Romfs, c: &Ctx, more: &mut Vec) -> Res<()> { + more.push(crate::no_tutorials::stage(rf, c.p.rings || c.p.hideout_ring)?); Ok(()) } @@ -221,6 +231,14 @@ fn pot_rows(rf: &mut Romfs, c: &Ctx, more: &mut Vec) -> Res<()> { crate::pot_slice::rows::stage(rf, more, c.pots) } +fn hideout_drop_rows(rf: &mut Romfs, c: &Ctx, more: &mut Vec) -> Res<()> { + crate::hideout_keys::stage_rows(rf, more, c.p.hideout != Keep::Vanilla) +} + +fn key_ring_flags(rf: &mut Romfs, c: &Ctx, more: &mut Vec) -> Res<()> { + crate::key_ring_credit::stage_rows(rf, more, &c.p.all_rings()) +} + fn start_defaults(rf: &mut Romfs, c: &Ctx, more: &mut Vec) -> Res<()> { let mut edits: Vec = crate::start_defaults::presets::chosen(&c.p.defaults())?; if let Some(n) = c.p.lacs { diff --git a/randomizer/core/src/slice/starts.rs b/randomizer/core/src/slice/starts.rs index 4ff258a1..4a47582d 100644 --- a/randomizer/core/src/slice/starts.rs +++ b/randomizer/core/src/slice/starts.rs @@ -5,7 +5,7 @@ use crate::settings::Loaded; use crate::slice::data::Data; use crate::slice::fill::vanilla_place; use crate::slice::logic::world_with; -use crate::slice::support::{plan, Plan}; +use crate::slice::support::{plan_with_seed as plan, Plan}; use crate::start_reward::pick as pick_start; use crate::world::{Placement, World}; @@ -33,7 +33,7 @@ pub fn add(d: &Data, p: &Plan, w: &mut World, seed: &str) -> Res<()> { pub fn rebuild(d: &Data, seed: &SeedFile) -> Res<(World, Placement)> { let loaded: Loaded = seed.settings()?; - let mut p: Plan = plan(&loaded.settings)?; + let mut p: Plan = plan(&loaded.settings, Some(&seed.seed))?; let lay: Option = crate::shops::seed::layout(seed)?; let owned: Option = lay.as_ref().map(|l| crate::shops::logic::data_with(d, l)).transpose()?; let d: &Data = owned.as_ref().unwrap_or(d); diff --git a/randomizer/core/src/slice/support.rs b/randomizer/core/src/slice/support.rs index 9593e8b2..82317ac6 100644 --- a/randomizer/core/src/slice/support.rs +++ b/randomizer/core/src/slice/support.rs @@ -56,6 +56,12 @@ pub struct Plan { pub own_strict: Vec<(&'static str, &'static str)>, pub chests: Mode, pub keys: di::Keys, + pub rings: bool, + pub ring_mode: crate::key_rings::Mode, + pub ring_count: usize, + pub active_rings: Vec<&'static crate::key_rings::Ring>, + pub hideout_ring: bool, + pub hideout: Keep, pub rewards: crate::flow_extra::Rewards, pub hearts: bool, pub world: pu::Free, @@ -136,6 +142,93 @@ fn chest_mode(s: &Settings, bad: &mut Vec) -> Mode { } } +fn hideout_mode(s: &Settings, bad: &mut Vec) -> Keep { + match s.text("shuffle_hideoutkeys") { + Ok("vanilla") => Keep::Vanilla, + Ok("any_dungeon") => Keep::AnyDungeon, + Ok("keysanity") | Ok("anywhere") => Keep::Anywhere, + Ok(v) => { + bad.push(format!("shuffle_hideoutkeys is {v}, which this build cannot place yet (only vanilla, any_dungeon and keysanity work)")); + Keep::Vanilla + } + Err(e) => { + bad.push(e.to_string()); + Keep::Vanilla + } + } +} + +fn ring_mode(s: &Settings, bad: &mut Vec) -> crate::key_rings::Mode { + use crate::key_rings::Mode; + match s.text(crate::key_rings::MODE_SETTING) { + Ok("all") => Mode::All, + Ok("count") => Mode::Count, + Ok("selection") => Mode::Selection, + Ok("random") => Mode::Random, + Ok(v) => { + bad.push(format!("{} is {v}, which is not a known choice", crate::key_rings::MODE_SETTING)); + Mode::All + } + Err(e) => { + bad.push(e.to_string()); + Mode::All + } + } +} + +fn ring_count(s: &Settings, bad: &mut Vec) -> usize { + match s.int(crate::key_rings::COUNT_SETTING) { + Ok(n) if (1..=crate::key_rings::RINGS.len() as i64).contains(&n) => n as usize, + Ok(n) => { + bad.push(format!("{} is {n}, outside 1..=8", crate::key_rings::COUNT_SETTING)); + 8 + } + Err(e) => { + bad.push(e.to_string()); + 8 + } + } +} + +fn ring_selection(s: &Settings, bad: &mut Vec) -> Vec<&'static crate::key_rings::Ring> { + match s.items(crate::key_rings::SELECTION_SETTING) { + Ok(ids) => crate::key_rings::selected(ids), + Err(e) => { + bad.push(e.to_string()); + Vec::new() + } + } +} + +fn active_rings( + s: &Settings, + seed: Option<&str>, + mode: crate::key_rings::Mode, + count: &mut usize, + bad: &mut Vec, +) -> Vec<&'static crate::key_rings::Ring> { + use crate::key_rings::Mode; + match mode { + Mode::All => crate::key_rings::all(), + Mode::Selection => { + let got: Vec<&'static crate::key_rings::Ring> = ring_selection(s, bad); + if got.is_empty() { + bad.push(format!("{} is empty; select at least one dungeon when key rings are on", crate::key_rings::SELECTION_SETTING)); + } + got + } + Mode::Count => seed.map(|x| crate::key_rings::count(x, *count)).unwrap_or_default(), + Mode::Random => match seed { + Some(x) => { + let (n, got): (usize, Vec<&'static crate::key_rings::Ring>) = crate::key_rings::random(x); + *count = n; + got + } + None => Vec::new(), + }, + } +} + pub const STRICT_KEYS: [(&str, &str); 3] = [("fire_key_layout", "shuffled"), ("water_key_layout", "shuffled"), ("spirit_key_layout", "shuffled")]; pub const OWN_STRICT: [(&str, &str); 2] = [("water_key_layout", "shuffled"), ("spirit_key_layout", "shuffled")]; pub const FIRE_LOOP: (&str, &str) = ("fire_loop_door", "open"); @@ -144,6 +237,24 @@ pub const FIRE_SPARE_KEY: &str = "Fire Temple Highest Goron Chest"; pub const OWN_KEYS: [(&str, &str); 3] = [OWN_STRICT[0], OWN_STRICT[1], FIRE_LOOP]; impl Plan { + + + pub fn all_rings(&self) -> Vec<&'static crate::key_rings::Ring> { + let mut out: Vec<&'static crate::key_rings::Ring> = if self.rings { + if self.active_rings.is_empty() { + crate::key_rings::all() + } else { + self.active_rings.clone() + } + } else { + Vec::new() + }; + if self.hideout_ring { + out.push(&crate::key_rings::HIDEOUT_RING); + } + out + } + pub fn keys_roam(&self) -> bool { self.keys.small.roams() } @@ -193,6 +304,23 @@ impl Plan { if self.fire_loop_open() { out.push(FIRE_LOOP); } + if self.rings { + out.push((crate::key_rings::SETTING, "true")); + for r in &self.active_rings { + out.push((r.select, "true")); + } + } + if self.hideout_ring { + out.push((crate::key_rings::HIDEOUT_SETTING, "true")); + } + if self.hideout != Keep::Vanilla { + let mode: &str = match self.hideout { + Keep::AnyDungeon => "any_dungeon", + Keep::Anywhere => "keysanity", + _ => "any_dungeon", + }; + out.push(("shuffle_hideoutkeys", mode)); + } if self.chus { out.push((crate::slice::bombchus::LOGIC_KEY, "true")); } @@ -269,13 +397,35 @@ pub(crate) fn toggle(s: &Settings, key: &str, bad: &mut Vec) -> bool { } pub fn plan(s: &Settings) -> Res { + plan_with_seed(s, None) +} + + + +pub fn plan_with_seed(s: &Settings, seed: Option<&str>) -> Res { let mut bad: Vec = Vec::new(); let mut noted: Vec = Vec::new(); crate::slice::unsupported::check(s, &mut bad, &mut noted); let chests: Mode = chest_mode(s, &mut bad); + let hideout: Keep = hideout_mode(s, &mut bad); + if hideout != Keep::Vanilla && matches!(chests, Mode::Off | Mode::Overworld) { + bad.push("shuffle_hideoutkeys needs chest shuffle to be Dungeons only or Everywhere".to_string()); + } let world: pu::Free = pu::mode(s, &mut bad); let drops: crate::pot_slice::Drops = crate::pot_slice::plan::read(s, &mut bad); let keys: di::Keys = di::Keys::read(s, &mut bad); + let rings: bool = toggle(s, crate::key_rings::SETTING, &mut bad); + if rings && keys.small == Keep::Vanilla { + bad.push("key_rings is on while shuffle_smallkeys is vanilla; key rings only work when small keys are shuffled".to_string()); + } + let ring_mode: crate::key_rings::Mode = ring_mode(s, &mut bad); + let mut ring_count: usize = ring_count(s, &mut bad); + let active_rings: Vec<&'static crate::key_rings::Ring> = if rings { + active_rings(s, seed, ring_mode, &mut ring_count, &mut bad) + } else { + Vec::new() + }; + let hideout_ring: bool = toggle(s, crate::key_rings::HIDEOUT_SETTING, &mut bad); di::chest_guard(s, chests, [keys.small, keys.boss, keys.ganon, keys.map], &mut bad); let mut rewards: crate::flow_extra::Rewards = crate::flow_extra::Rewards::read(s, &mut bad); let hearts: bool = toggle(s, "shuffle_boss_hearts", &mut bad); @@ -313,6 +463,15 @@ pub fn plan(s: &Settings) -> Res { let open: crate::open_world::Opts = crate::open_world::read(s, &mut bad); let trials: crate::ganon_trials::Trials = crate::ganon_trials::read(s, &mut bad); let difficulty: crate::difficulty::Opts = crate::difficulty::read(s, &mut bad); + if hideout != Keep::Vanilla && open.fortress != crate::open_world::Fortress::Open { + bad.push("shuffle_hideoutkeys needs gerudo_fortress=open; the four native drops are only rewired for the already-cleared fortress".to_string()); + } + if hideout_ring && !s.text("shuffle_hideoutkeys").is_ok_and(|v| v == "keysanity") { + bad.push("hideout_key_rings needs shuffle_hideoutkeys=keysanity; the Hideout ring replaces the four shuffled Hideout keys".to_string()); + } + if hideout_ring && open.fortress != crate::open_world::Fortress::Open { + bad.push("hideout_key_rings needs gerudo_fortress=open, like shuffled Hideout keys".to_string()); + } if open.fortress == crate::open_world::Fortress::Open { crate::start_items::give::add(&mut kit, "gerudo_card"); } @@ -369,6 +528,9 @@ pub fn plan(s: &Settings) -> Res { (start.reward != Reward::Off, "You start the game with one random Stone or Medallion."), (!start.pouch.is_empty(), "The ticked Kokiri Sword, Deku Shield or Slingshot is added to the pouch when a new game starts. A ticked Big or Biggest Bullet Bag brings the Slingshot with it."), (keys.small.roams(), "Small keys can be found in other dungeons or outside them. A chest key is counted for the dungeon it belongs to and the chest says which."), + (rings, crate::key_rings::NOTE), + (hideout != Keep::Vanilla, "Thieves' Hideout Small Keys are shuffled. The four native key drops hold shuffled non-key items."), + (hideout_ring, "The four Thieves' Hideout keys become one manually enabled Hideout key ring."), (gates.forest != Forest::Closed, "Kokiri Forest starts open. The blocker walls are switched off when a new game starts."), (gates.kakariko, "The Kakariko gate starts open and the castle visit is skipped. A new game sets the castle quest complete, the Door of Time quest past Impa's send off, the Fire Stone quest past the gate and the gate guard's flag, and gives the items of Zelda's Letter and the Song from Impa."), (gates.door, "The Door of Time starts open. The Temple of Time logic is edited so the door is always open and the Master Sword can be drawn without the Door of Time quest, and the door's opened flag is set when a new game starts, so the Ocarina and the Song of Time are not needed to reach the Master Sword. The quest itself is left alone, so Zelda's escape and the Song of Time stay checks, and the adult pedestal works before the Forest Sage so you can return to childhood at any time."), @@ -391,6 +553,12 @@ pub fn plan(s: &Settings) -> Res { notes.push(text.to_string()); } } + if rings { + let extra: String = crate::key_rings::mode_note(ring_mode, ring_count, &active_rings); + if !extra.is_empty() { + notes.push(extra); + } + } if gates.kakariko { notes.push(crate::start_defaults::presets::note(KAKARIKO.0, KAKARIKO.1)?); } @@ -459,7 +627,7 @@ pub fn plan(s: &Settings) -> Res { notes.push(crate::medal_gate::LACS_NOTE.to_string()); } let own_strict: Vec<(&'static str, &'static str)> = if matches!(chests, Mode::Dungeons | Mode::All) { OWN_STRICT.to_vec() } else { Vec::new() }; - Ok(Plan { own_strict, chests, keys, rewards, hearts, world, songs, harp_colors, hints, fast, chest_sizes, intro, start, gates, excluded, notes, drops, skulls, remake, chus, qol, treasure, day_skulls, kit, open, npc, shops, bridge, debug_names, silver, lacs, rainbow, trials, door, nocturne, prelude, short, first_pickups, area_intros, story, endings, ocarinas, kokiri_sword, difficulty }) + Ok(Plan { own_strict, chests, keys, rings, ring_mode, ring_count, active_rings, hideout_ring, hideout, rewards, hearts, world, songs, harp_colors, hints, fast, chest_sizes, intro, start, gates, excluded, notes, drops, skulls, remake, chus, qol, treasure, day_skulls, kit, open, npc, shops, bridge, debug_names, silver, lacs, rainbow, trials, door, nocturne, prelude, short, first_pickups, area_intros, story, endings, ocarinas, kokiri_sword, difficulty }) } #[cfg(test)] @@ -553,6 +721,92 @@ mod tests { assert_eq!(p.chests, Mode::Dungeons); } + #[test] + fn key_rings_need_shuffled_small_keys_and_reach_the_logic() { + let mut s: Settings = Settings::default(); + s.set("shuffle_smallkeys", Value::s("vanilla")).unwrap(); + s.set(crate::key_rings::SETTING, Value::Bool(true)).unwrap(); + let e: String = plan(&s).err().unwrap().to_string(); + assert!(e.contains("key_rings is on while shuffle_smallkeys is vanilla"), "{e}"); + + s.set("shuffle_smallkeys", Value::s("keysanity")).unwrap(); + let p: Plan = plan(&s).unwrap(); + assert!(p.rings); + assert!(p.notes.iter().any(|n| n == crate::key_rings::NOTE)); + assert!(p.logic().contains(&(crate::key_rings::SETTING, "true"))); + } + + #[test] + fn ring_modes_derive_the_active_standard_dungeons_from_settings_and_seed() { + use crate::key_rings::{self, Mode}; + + let mut s: Settings = Settings::default(); + s.set("shuffle_smallkeys", Value::s("keysanity")).unwrap(); + s.set(key_rings::SETTING, Value::Bool(true)).unwrap(); + + let all: Plan = plan_with_seed(&s, Some("seed")).unwrap(); + assert_eq!(all.ring_mode, Mode::All); + assert_eq!(all.active_rings, key_rings::all()); + assert_eq!(all.logic().iter().filter(|(k, _)| k.starts_with("key_ring_")).count(), 8); + + s.set(key_rings::MODE_SETTING, Value::s("selection")).unwrap(); + s.set(key_rings::SELECTION_SETTING, Value::set(&["ganons_castle", "forest_temple"])).unwrap(); + let picked: Plan = plan_with_seed(&s, Some("seed")).unwrap(); + assert_eq!(picked.active_rings.iter().map(|r| r.choice).collect::>(), ["forest_temple", "ganons_castle"]); + assert!(picked.logic().contains(&("key_ring_forest_temple", "true"))); + assert!(!picked.logic().contains(&("key_ring_fire_temple", "true"))); + s.set(key_rings::SELECTION_SETTING, Value::set(&[])).unwrap(); + let e: String = plan_with_seed(&s, Some("seed")).err().unwrap().to_string(); + assert!(e.contains("key_rings_selection is empty"), "{e}"); + + s.set(key_rings::MODE_SETTING, Value::s("count")).unwrap(); + s.set(key_rings::SELECTION_SETTING, Value::set(&key_rings::CHOICE_IDS)).unwrap(); + s.set(key_rings::COUNT_SETTING, Value::Int(3)).unwrap(); + let a: Plan = plan_with_seed(&s, Some("seed")).unwrap(); + let b: Plan = plan_with_seed(&s, Some("seed")).unwrap(); + assert_eq!(a.active_rings.len(), 3); + assert_eq!(a.ring_count, 3); + assert_eq!(a.active_rings, b.active_rings); + assert!(a.notes.iter().any(|n| n.contains("3 seed-randomized standard dungeons"))); + + s.set(key_rings::MODE_SETTING, Value::s("random")).unwrap(); + let r: Plan = plan_with_seed(&s, Some("seed")).unwrap(); + assert!((1..=8).contains(&r.ring_count)); + assert_eq!(r.active_rings.len(), r.ring_count); + assert_eq!(r.active_rings, plan_with_seed(&s, Some("seed")).unwrap().active_rings); + assert!(r.active_rings.iter().all(|x| key_rings::by_choice(x.choice).is_some())); + } + + #[test] + fn hideout_ring_is_a_separate_gated_toggle() { + use crate::key_rings; + + let mut s: Settings = Settings::default(); + s.set("shuffle_smallkeys", Value::s("keysanity")).unwrap(); + s.set("gerudo_fortress", Value::s("open")).unwrap(); + s.set("shuffle_hideoutkeys", Value::s("keysanity")).unwrap(); + s.set(key_rings::HIDEOUT_SETTING, Value::Bool(true)).unwrap(); + let p: Plan = plan_with_seed(&s, Some("seed")).unwrap(); + assert!(p.hideout_ring); + assert!(!p.rings); + assert!(p.active_rings.is_empty()); + assert_eq!(p.all_rings().iter().map(|r| r.item).collect::>(), ["Small Key Ring (Thieves Hideout)"]); + assert!(p.logic().contains(&("hideout_key_rings", "true"))); + assert!(p.logic().contains(&("shuffle_hideoutkeys", "keysanity"))); + assert!(p.notes.iter().any(|n| n.contains("one manually enabled Hideout key ring"))); + + for bad in ["vanilla", "regional", "overworld", "any_dungeon"] { + s.set("shuffle_hideoutkeys", Value::s(bad)).unwrap(); + let e: String = plan_with_seed(&s, Some("seed")).err().unwrap().to_string(); + assert!(e.contains("hideout_key_rings needs shuffle_hideoutkeys=keysanity"), "{e}"); + } + + s.set("shuffle_hideoutkeys", Value::s("keysanity")).unwrap(); + s.set("gerudo_fortress", Value::s("normal")).unwrap(); + let e: String = plan_with_seed(&s, Some("seed")).err().unwrap().to_string(); + assert!(e.contains("hideout_key_rings needs gerudo_fortress=open"), "{e}"); + } + #[test] fn every_setting_flagged_as_not_yet_is_refused_at_a_non_default_value() { let sch: &crate::settings::Schema = crate::settings::schema(); diff --git a/randomizer/core/src/slice/swap_guard.rs b/randomizer/core/src/slice/swap_guard.rs index e9495542..4af1599f 100644 --- a/randomizer/core/src/slice/swap_guard.rs +++ b/randomizer/core/src/slice/swap_guard.rs @@ -52,7 +52,7 @@ mod tests { } fn spec(item: &str, name: &str) -> Spec { - Spec { item: item.to_string(), name: name.to_string(), style: Style::Touch, heap: None } + Spec { item: item.to_string(), name: name.to_string(), style: Style::Touch, heap: None, source: None, identity: None } } fn opts(base: Option, dry: bool) -> Opts { diff --git a/randomizer/core/src/slice/tier_census.rs b/randomizer/core/src/slice/tier_census.rs index 97f41c84..f4f11b44 100644 --- a/randomizer/core/src/slice/tier_census.rs +++ b/randomizer/core/src/slice/tier_census.rs @@ -8,7 +8,7 @@ use crate::search::{explore, Search}; use crate::settings::seed::SeedFile; use crate::slice::data::Data; use crate::slice::edit::is_sale; -use crate::slice::support::{plan, Plan}; +use crate::slice::support::{plan_with_seed, Plan}; use crate::slice::tier_order::{fixed_actors, rank, slots, Give, Slot, Verdict}; use crate::start_items::Set; use crate::world::{LocId, Placement, World}; @@ -180,7 +180,7 @@ fn prize_rows(d: &Data, seed: &SeedFile) -> Vec { pub fn census(d: &Data, seed: &SeedFile) -> Res> { let (w, place): (World, Placement) = crate::slice::starts::rebuild(d, seed)?; - let p: Plan = plan(&seed.settings()?.settings)?; + let p: Plan = plan_with_seed(&seed.settings()?.settings, Some(&seed.seed))?; let v: Verdict = fixed_actors(d, seed)?; let sl: Vec = slots(d, &seed.placements); let wrapped: BM = crate::slice::flow_wrap::wraps(d, seed); @@ -385,7 +385,7 @@ mod tests { ] { let mut s: Settings = Settings::default(); s.set("starting_items", Value::set(&ids)).unwrap(); - let p: Plan = plan(&s).unwrap(); + let p: Plan = plan_with_seed(&s, None).unwrap(); let rows: Vec = start_rows(&d, &p); let r: &Row = rows.iter().find(|r| r.family == fam).unwrap_or_else(|| panic!("{ids:?}")); println!("{ids:?}\t{}\t{}\tpouch {:?}", r.tier, r.risk, p.start.pouch); diff --git a/randomizer/core/src/slice/tier_order.rs b/randomizer/core/src/slice/tier_order.rs index 024ba1c9..285f382d 100644 --- a/randomizer/core/src/slice/tier_order.rs +++ b/randomizer/core/src/slice/tier_order.rs @@ -65,6 +65,7 @@ pub fn fixed_spot(d: &Data, loc: &str) -> bool { crate::pot_slice::targets::is_loc(d, loc) || crate::shops::is_loc(loc) || crate::slice::skulls::is_skull(d, loc) + || crate::hideout_keys::is_native(loc) || loc == crate::slice::treasure::LOC || d.cat.by_name(loc).is_some_and(|l| crate::slice::pickups::is_world(l) || l.kind == "bossheart") } diff --git a/randomizer/core/src/slice/unsupported.rs b/randomizer/core/src/slice/unsupported.rs index 735fe4b7..edabb3d7 100644 --- a/randomizer/core/src/slice/unsupported.rs +++ b/randomizer/core/src/slice/unsupported.rs @@ -51,9 +51,14 @@ pub fn check(s: &Settings, bad: &mut Vec, noted: &mut Vec) { Err(e) => bad.push(e.to_string()), } } - match s.text("shuffle_hideoutkeys") { - Ok("vanilla") => {} - Ok(v) => bad.push(format!("shuffle_hideoutkeys is {v}, which this build cannot place yet (only vanilla works)")), - Err(e) => bad.push(e.to_string()), + let hideout: &str = s.text("shuffle_hideoutkeys").unwrap_or("vanilla"); + match hideout { + "vanilla" | "any_dungeon" | "keysanity" | "anywhere" => {} + v => bad.push(format!("shuffle_hideoutkeys is {v}, which this build cannot place yet (only vanilla, any_dungeon and keysanity work)")), + } + if hideout != "vanilla" + && !matches!(s.text("gerudo_fortress").unwrap_or("normal"), "fast" | "open") + { + bad.push(format!("shuffle_hideoutkeys is {hideout}, which needs gerudo_fortress to be fast or open")); } } diff --git a/randomizer/core/src/start_items/pool.rs b/randomizer/core/src/start_items/pool.rs index 29e72d99..633108da 100644 --- a/randomizer/core/src/start_items/pool.rs +++ b/randomizer/core/src/start_items/pool.rs @@ -26,7 +26,11 @@ fn gone_kinds(p: &Plan) -> Vec<&'static str> { } pub fn active(p: &Plan) -> bool { - p.fire_loop_open() || p.open.beans || !gone_kinds(p).is_empty() || p.kit.take.iter().any(|t| t.strip != Strip::Keep && t.count > 0) + p.hideout != Keep::Vanilla + || p.fire_loop_open() + || p.open.beans + || !gone_kinds(p).is_empty() + || p.kit.take.iter().any(|t| t.strip != Strip::Keep && t.count > 0) } fn kind_of<'a>(d: &'a Data, w: &World, it: ItemId) -> &'a str { @@ -146,6 +150,8 @@ pub fn base(d: &Data, w: &World, p: &Plan, vanilla: &Placement, free: &[LocId]) for t in p.kit.take.iter().filter(|t| t.strip != Strip::Keep && t.count > 0) { strip_one(&c, t, &mut out, &mut notes)?; } + + Ok((out, notes)) } @@ -274,6 +280,34 @@ mod tests { } } + #[test] + fn hideout_keys_never_exceed_four_in_a_seed() { + let d: Data = Data::load().unwrap(); + for shuffle in ["vanilla", "any_dungeon", "keysanity"] { + let s: Settings = with(&[("shuffle_hideoutkeys", Value::s(shuffle)), ("gerudo_fortress", Value::s("open"))]); + for n in 0..3 { + let g = beatable(&d, &s, &format!("hideout count {shuffle} {n}")); + let keys: usize = g.seed_file.placements.values().filter(|v| v.as_str() == "Small Key (Thieves Hideout)").count(); + assert!(keys <= 4, "{shuffle} {n} has {keys} Hideout keys, more than the four that exist"); + if shuffle != "vanilla" { + assert_eq!(keys, 4, "{shuffle} {n} has {keys} Hideout keys, expected four in the shuffled pool"); + } + } + } + let s: Settings = with(&[ + ("shuffle_hideoutkeys", Value::s("keysanity")), + ("gerudo_fortress", Value::s("open")), + (crate::key_rings::HIDEOUT_SETTING, Value::Bool(true)), + ]); + for n in 0..3 { + let g = beatable(&d, &s, &format!("hideout ring count {n}")); + let keys: usize = g.seed_file.placements.values().filter(|v| v.as_str() == "Small Key (Thieves Hideout)").count(); + let rings: usize = g.seed_file.placements.values().filter(|v| v.as_str() == crate::key_rings::HIDEOUT_RING.item).count(); + assert_eq!(keys, 0, "hideout ring {n} still places {keys} individual Hideout keys"); + assert_eq!(rings, 1, "hideout ring {n} places {rings} Hideout rings"); + } + } + #[test] fn removed_dungeon_items_never_show_up_in_a_seed() { let d: Data = Data::load().unwrap(); diff --git a/randomizer/core/src/story_skip.rs b/randomizer/core/src/story_skip.rs index 4f68012d..536d6f28 100644 --- a/randomizer/core/src/story_skip.rs +++ b/randomizer/core/src/story_skip.rs @@ -305,9 +305,9 @@ pub fn patch_gift(b: &mut Bf) -> Res<()> { let grant: usize = find(f, GIFT_GRANT)?; let show: usize = find(f, GIFT_SHOW)?; let wrapped = |i: usize| matches!(f.events[i].kind, Kind::Switch { .. }); - // A dungeon item replaces the pouch add with its credit writes (crate::gift_keys), a chain - // that already ends where the add did. - let credited: bool = action(f, grant).is_some_and(|a| a.starts_with("GameDataActor.")); + + + let credited: bool = action(f, grant).is_some_and(|a| a.starts_with("GameDataActor.")) || crate::gift_keys::is_ring_credit(f, grant); if !wrapped(grant) && !credited && action(f, grant).as_deref() != Some(POUCH_ADD) { return Err(Error::Format("story skip: the gift scene's grant is not a pouch add, the game files differ")); } @@ -919,8 +919,10 @@ fn item_get(f: &mut Flow, name: &str, g: &SceneGive, then: u16, entries: &[&str] // A small key is held up as the minigame key through the key copy, whose window names the // dungeon key (crate::gift_keys::SMALL_KEY_SHOWN). let small: bool = matches!(g.key, Some((crate::gift_keys::Item::Small, _))) && g.actor == crate::gift_keys::SMALL_KEY_ITEM; + let ring: bool = matches!(g.key, Some((crate::gift_keys::Item::Ring(_), _))); let window: String = if small { crate::item_window::key_name(ITEM_GET.1) } else { crate::item_window::name(ITEM_GET.1) }; - let entry: &str = if g.key.is_some() { &window } else { ITEM_GET.1 }; + + let entry: &str = if g.key.is_some() && !ring { &window } else { ITEM_GET.1 }; let actor: String = if small { crate::gift_keys::SMALL_KEY_SHOWN.to_string() } else { g.actor.clone() }; f.events.push(Event { name: name.to_string(), diff --git a/randomizer/logic/src/search.rs b/randomizer/logic/src/search.rs index 47fd2d91..4f577532 100644 --- a/randomizer/logic/src/search.rs +++ b/randomizer/logic/src/search.rs @@ -46,9 +46,20 @@ impl<'a> Search<'a> { } pub fn add(&mut self, i: ItemId, n: u32) { + let ring: Option<(ItemId, u32)> = self.w.ring_key(i); self.cnt[i] += n; + if let Some((key, count)) = ring { + self.cnt[key] += count * n; + } self.dirty = true; let w: &World = self.w; + if let Some((key, _)) = ring { + for s in &w.users[key] { + for a in 0..2 { + self.push(a, *s as usize, false); + } + } + } for s in &w.users[i] { for a in 0..2 { self.push(a, *s as usize, false); @@ -59,6 +70,9 @@ impl<'a> Search<'a> { pub fn remove(&mut self, i: ItemId) { if self.cnt[i] > 0 { self.cnt[i] -= 1; + if let Some((key, count)) = self.w.ring_key(i) { + self.cnt[key] = self.cnt[key].saturating_sub(count); + } } } diff --git a/randomizer/logic/src/world.rs b/randomizer/logic/src/world.rs index fe9ea823..b9cbca1b 100644 --- a/randomizer/logic/src/world.rs +++ b/randomizer/logic/src/world.rs @@ -48,6 +48,7 @@ pub struct ItemDef { pub struct Spec { pub settings: Settings, pub items: Vec, + pub rings: Vec<(String, String, u32)>, pub groups: Vec<(String, Vec)>, pub start: Vec<(String, u32)>, pub helpers: Vec, @@ -77,6 +78,7 @@ impl Spec { Spec { settings: Settings::new(), items: Vec::new(), + rings: Vec::new(), groups: Vec::new(), start: Vec::new(), helpers: Vec::new(), @@ -91,6 +93,12 @@ impl Spec { self.items.push(ItemDef { name: name.to_string(), adv, count }); } + + pub fn add_ring(&mut self, name: &str, key: &str, count: u32) { + self.add_item(name, true, 0); + self.rings.push((name.to_string(), key.to_string(), count)); + } + pub fn add_regions(&mut self, text: &str) -> Res<()> { self.regions.push(parse(text)?); Ok(()) @@ -206,6 +214,7 @@ pub struct World { pub real: Vec, pub users: Vec>, pub tod_users: Vec, + pub rings: Vec>, region_ix: HM, loc_ix: HM, } @@ -277,6 +286,12 @@ impl World { items.add(&d.name, d.adv, false)?; pool_counts.push(d.count); } + let mut rings: Vec> = vec![None; items.len()]; + for (name, key, count) in &spec.rings { + let i: ItemId = items.find(name).ok_or_else(|| E::Msg(format!("ring {name} is not an item")))?; + let k: ItemId = items.find(key).ok_or_else(|| E::Msg(format!("ring {name}: unknown key {key}")))?; + rings[i] = Some((k, *count)); + } let mut groups: HM> = HM::new(); for (g, names) in &spec.groups { let mut ids: Vec = Vec::with_capacity(names.len()); @@ -425,6 +440,7 @@ impl World { real, users, tod_users, + rings, region_ix, loc_ix, }) @@ -442,6 +458,10 @@ impl World { self.items.find(name) } + pub fn ring_key(&self, i: ItemId) -> Option<(ItemId, u32)> { + self.rings.get(i).copied().flatten() + } + pub fn pool(&self) -> Vec { let mut out: Vec = Vec::new(); for (i, c) in self.pool_counts.iter().enumerate() {