diff --git a/.achievement_data/state.json b/.achievement_data/state.json new file mode 100644 index 0000000..6939f24 --- /dev/null +++ b/.achievement_data/state.json @@ -0,0 +1 @@ +[4,1784091728,["39.16.75","39.16.105","39.16.123","39.16.60","39.16.74","39.16.137","39.16.104"],["first_birth","natural_zunchi_slave","natural_tarinai_king","self_zunchi_death","zunchi_collision_death","natural_zunchi_slave_5_generations","natural_tarinai_king_3_generations","death_50_in_10_seconds","birth_50_in_60_seconds","great_mother_1000_births","lifespan_completed","soccer_ball_death","fight_pair_danger_kill","all_non_sleep_diseased_25","colony_happy","direct_feed_33","ignite_during_birth_ritual","laxative_starvation","idle_observer_5_minutes","placed_objects_100","mechanized_industry","safe_colony_25_5_minutes","ants_alive_25","ants_killed_100","secret_collection_9_slots","pause_spam_4_in_1_second","continuous_play_1_hour","below_absolute_zero_item","undo_mass_revival","robot_cleaner_100","held_30_seconds","minimalist_happy","overprotective","self_sufficient","unplanned_city_30","sauna_cold_plunge","rain_shelter_all","medicine_ledger_all","mercury_lifespan","enemy_enemy_friend","revolution","fuel_to_fire","undo_20","redo_20","eternal_history_generation_10","king_full_satisfaction","slave_zero_satisfaction","town_doctor_50","poke_plushie_fling","chaos_seeker_666_fights","clean_freak_robot_only","true_tarinai_observer","sniper_333_shots","megalopolis","fertility_seeker_721_love_births","low_fps_single_digit","continuous_play_24_hours","sandbox_five_toilets","park_ground_changed","ground_change_4_in_1_second","ant_nest_without_tarinai","sticky_bomb_15_passes","daily_play_7_days","wire_shock_7_tarinai","information_industry","strength_in_numbers","elite_few","zunchi_overflow","comfortable_beds","stone_pillow","across_seasons","favorite_one","statistician","well_informed","lively_making","memento_mori","mad_scientist"],[["AT7UX0vQQHSjDSsx7ntrcA",115523,0,4],["AXHGXDetQkWuJ2vrhLVrsw",191206,599],["AZOq9iLdRLiVs_J1HNcdNg",26632,311131,1],["AgioecJAT9-DyKM9rBWwFg",354351,233,1],["An-kM9_1Rkuiu0eIHnJROw",24687,416999,5],["A9UhC-axRtWKy4Vw8NRLjA",225077,15],["BmyezTENRtm5ekkH3z99qg",289868,146256,5],["BsqXI2J_RTCLzl9rK-WTVQ",201094,16],["B5myaZslQwSnpkvoGpknsA",37613,1800,3],["C0tajnOTT1K0FgIfEGVsGA",256959,2973],["C4GRUxmdRbWZzHJ0V9JpsQ",17432,357474,2],["C8XqqJ5rTHa6qw-z8Y88jA",365330,744,1],["DFKBeF9-RpKfjhRhQx2ZRg",174267,14974],["DGPMjLtqRaCtHIptLtkjdw",221295,2546],["DyaOro6TQ5G_TeHnltFK0g",67643,146960],["EGSebCuwSk6FKdPePBeDOg",118168,1199,4],["EgkHNUQJQPat3FM4ZIU59w",156003,0],["EyToTt3-RX26J-6eJ-xpPw",191733,6600],["E0HXsU6-RYCO91MK9M07bw",9762,104722,4],["E2ldSdcxQN-zZ9xTBzDE1g",368929,299,2],["Gr93GoiFQkGMHKs2Mw4AaQ",97655,9130,3],["G2o3yC0MTIKMLhDk2o6YDA",245190,7797],["HYkDqmCsS8aiMrUThI4fcQ",201617,13],["Hns48Q0MQJ2H-lFEmwxfQw",23523,603,3],["HwT0Sk-XSGahzteQS7FPzQ",287737,92777,2],["H5ZDYEFvQ0e-3JC0xPTx-Q",27702,421,3],["ITRYJzo5QYaSkjLYaaJ6Yg",40636,46882,3],["ItNN0heHRqiNHc-OoGoSMA",297825,1298,1],["JuwFpfb1QJeYfGvWpzy3IA",63369,126598],["J7uf1v88T3mSFs1ptKO9RQ",120239,25],["KSZ59taVRJmYmVYVhe99hg",77159,1800,3],["KwJlifxVSh-GUDpUNABzrw",369833,308,2],["LDAWke6kRbutWe3r9dfLdQ",318649,776,1],["Li2NtIyOQpGHzFaEovEoYg",100406,0,4],["MEMut_ufQsmx1rPi45G81Q",36627,395276,2],["Mpv6WJHGTw6YwQQ70mk7BA",13479,80,3],["Nf-0jB-JQ0-UZnRWPHS98A",300640,4006,1],["Nhx8JhVfTOWAYRt1vRuQow",113724,74645],["NjK9LbETSzOX-LpfqL0nxg",255226,103273,1],["Nj7jeXEWTXa6Sm5VPRlmEg",206684,123],["NkwzEL98Rzi4GwdSd5A3ng",20301,0,3],["NuaRm_fYR7Sz8nVs4P4yCg",114763,34,4],["Nvzk_2oQQbawaZca4Pww2Q",291531,73544,1],["NxW5_hQ1SoO5iSuv66RCfg",270726,299,1],["Nx2nfW9iRpeJXcFw7IOdIA",283823,976,1],["QD38IUY8RJeCcN0xwmTyTQ",269572,9325,1],["QQx3jG6FR2-TJx80sIlCUA",241410,16],["QoCQg7HPQYKYtzZY6V5tTQ",375227,2400,2],["Q-YwoP68T6anCkkhU6gLAg",234541,3300],["RB-Tlne5T4OxgjAQO0_ysg",381794,740,2],["RB_DGMVqRV-QbX2uFDTRpA",365383,1322,1],["RVu0RBgqRbipwYNU50e9qQ",343860,0,1],["RrNxNSRsSiKVxmeMQo6lPg",433513,222,2],["R6bORyS0QYGxKejqyoB10A",303512,14,1],["SG0ktBVwR5Os_MDzYJoawQ",39040,599,3],["SfZYmhpyRZCwrqBiw9kqUA",132898,357],["SjYuiyoHTeivYcMyKoRGNg",337249,104061,5],["S5DpVCRaThahOqTSMlWPDA",89164,337690,2],["TUKrrmrET2ypgp5DaU4tlA",18426,0,3],["T9GkyS2HSqKbKoqMiC7WXg",47094,16,3],["URXE_032StGQlEl3V17HXQ",374574,2899,2],["UdLsI4uyQ_S-XN7a4N5CvQ",34688,392712,2],["UqaJ9nvhQl-eT-Bey1m8Rw",16731,420407,5],["U2UehYHxQ5248yI8fy7_iw",145756,39],["VRG1ggLhStGW9MXAb65Btw",31668,17,3],["WQ3Ku6CJTWaCLabPhA951w",363389,625,1],["W_G-e_6AT4qICRL-Hz05sA",119138,14,4],["XNVK7HGDTMiNp8dsEPgM2A",52741,13,3],["XdDGg7MrTG2ZNpPIVpk3VA",119422,14,4],["YIXXT1hTSrS0ESGYH59www",422182,1798,2],["YKJXT2URTSydN9aUmkJOKA",179869,1221],["YYaufcmaQ4GiD9Q_MZuMWw",299654,335,1],["Yads3JcpTMymeKumAQcF6Q",362480,16,1],["YkBYIYwHRYOwkX0fmeqT4w",249642,299],["ZBBiN426T3WEYxVBXituGQ",90719,15103,4],["ZHedzwwERgmbHhpZuIEoeg",110056,94,4],["ZO4ZHBKxRyu5IlOdEiaMjQ",173877,0],["Z2KTakqhSTuWysEEAKyGXA",195554,109463,1],["a7UWcDOyToOQycGTu33MeQ",214800,148558,1],["bFoT0vGfRSapP6saKj_L6g",423544,3600,2],["bP42-AJoR4CDwWnCKWHocQ",232663,300],["bcxw7HujQFi5Y1YOMwQOfA",121952,23511],["b-Q9bhMZTHGa_blAGuZseQ",341953,599,1],["cnupw5mWSfS4hwLnV1L2XA",248428,106847,1],["csNqBKPtRNe25Pr757SKaA",203517,9051],["dQ3Y_1tPRZ6oPIRWPKo4aQ",194363,0],["dqOnFoBXTlqwDr8C2mv5yw",25033,404829,2],["eKNNK69YS6-iu0qhfQ6p9A",125751,14],["eifTn_kTRgSMWj6KYbalIg",100380,14,4],["fGJd8BQqRkai1XTM6B7nEw",13459,279970,1],["fJLe4FHgS2O9b-hFtG9Ldw",344682,594,1],["gAlvRzRXTLOxqgdwcRxLQw",421603,301,2],["gMC_86VbT7uIH8B0fdKxlA",14550,0,3],["gVlK1ilNRPeMIPUAA-JRtQ",221160,13],["gcRLtucSTrGWq7WYznfTmQ",290969,899,1],["i8Ff_VXpTFORsOhh4jZHbQ",280665,51,1],["jAw6RpvST3OEMAvbeH77LA",240387,221],["j-mNs4bdSI2XqAhGb4p3Hw",88836,20,3],["kBFvt4RRSai3DmGuyfgf6w",19817,2574,3],["kUEPr6JJTz6mCwWJDLv-aQ",115199,2400,4],["mlBIJs6mT52AX2Ahpgh7sw",196651,3934],["mswKVgE5Qxqta4NAHvVkoQ",437951,14,5],["nTWtsnADSv648AxbFz4Lcg",212355,9300],["nVUbi4OmT6-J9byg8-q97g",32001,1123,3],["nxblVyMLTrSZAkfPf2FWwg",383336,26486,2],["n-SY48K2QeqzCkb7yTZPpQ",259675,1200],["n_tcf3j7S6yBYt2Y7yM85A",293624,169,1],["odJ_h7oUS1yB_7p6LB4w7w",112982,342,4],["oe139e_bR4WtnCcqSe2jBQ",332048,0,1],["o4yHwSx2SX24OE9qPkJHsw",432488,825,2],["pQFs21PfTXuXeaf1tEVdMQ",129750,4545],["qTwJtmQESIC3jAtmz_8sTg",423097,13,2],["qnK6RnesT2igW_HcZssIdA",97976,334829,2],["qs3rnavAT4acYZvaEeI5oQ",129913,1199],["qxGFhkHZTduV9YYYWyDSUg",147480,273846,2],["r75L6GPkR4uVqBqO_1aSyA",355137,2246,1],["sSCrwsqiSyqBVgz7Matzww",299588,101812,2],["s3O6OZTBRz6O0TUBQC64QA",23489,245,3],["s_uTFGOTQdKTmWoJ9Vbzpg",24710,357292,2],["tMDzFziXTJ2CYoBLWq9H9Q",8579,433201,5],["tWF1yvWnTfOaaaBAbXwtPA",29003,17,3],["taU6vA6PTjWhKC6V43YplA",24383,411287,2],["t2UqLSrEREKy0Ai8JSYKGQ",203662,113],["t7tpQzqNRV6-tLSbunsDfg",302098,133,1],["t_SyOC8gTi218xAe4vOGgw",382434,7684,2],["uAtfx_GBRvmJCP6E9UWmzg",100421,15175,4],["uU2jxY3bRBe7AtfHRFGSIA",34810,299,3],["uqFbOGx4S_6ZvjcQrWE2Bw",26634,346405,2],["v1K6sNSCRdWXvmk8Jl91sQ",20955,298322,1],["wBeR6TKiQ1SnWlxO6HjxUg",208309,1199],["wF4aj-hSTl-BSuCbVRywOA",429094,2999,2],["wK3oJUoHT5Kb0jeLIzFJJQ",184790,16],["wM8XiYo0R9SEcCkDjO2bxQ",390457,1499,2],["wQwjJN_pSSOryn69Y8lqyA",16767,418804,2],["when_J1OTpScd-vaA2i6xw",341088,309,1],["xhjNabCzQHGEWRw9eEFAYQ",101690,275766,2],["xnEBJGKVSSC7--M0K_e2JA",364391,1764,1],["yYHnh-RxQaOcASVbQj6gOg",297672,2435,1],["yp2M01VvTle5xgXu7ZNzqg",204919,14],["ys4oahR7TDm9WW5zOKyShA",30073,1310,3],["zJtKDIeiTM2oegMGMt3nvg",343271,0,1],["zLFzVsWhSTOYU6rJsMsi1Q",20602,1472,3],["zOC7w26xQYiGnLQy3x504A",57982,44,3],["zmEzLb-1Q6m08t7dLiqFdw",11424,599,3],["zn1ecYMwRNKrJukPfPFoXQ",103760,282772,2],["zsuxu35fRq6bIZCvcC3iag",106311,285,4],["0Ekuj3W8Qpm_EwKpSXYdXw",377873,19,2],["0KpzjsoqQYaN_S2X8ySd7w",22236,352889,2],["0ia10T1pSZmAKukutrEaIA",31969,87661,4],["0lcgISlzQEej3cvhI-e-Ww",289089,82410,2],["0y4SH2FXRYGK1d0FCkOUjw",378025,6741,2],["00Z1M7PFTqq9iwnnCxiZTA",269597,166,1],["1dKF4NRHRfaJtfQr4lafCg",40381,1201,3],["2Bdkm5NaSY2lY1VMj_1Mqw",69602,16,3],["2jtrVkYNQtGpp7Y2wSOwZQ",304589,74,1],["2rseIRu9RAuvUuNOsSO_-Q",26626,18,3],["28TEqRx1QuK-TmIYSLzL1Q",34802,0,3],["3E-4jv0QSPq33RbRg4B3Aw",423829,7130,2],["3XJWUCjdRgSxmd5Z1hfDcw",16826,420725,5],["3cXtHb7yRQSBcQK7yx-_zw",232365,465],["3mSl6ER2RtSj9a0p-sNDMA",430880,299,2],["4JrymWEKThuc99N1_G1_rQ",11020,430720,5],["4XM-EZ63SiSRpbvcIqdZyw",133745,183813,1],["4u-CXB7uTwuNWoFuQ2ZO9g",196903,14],["5aQrgazaTe2oNgyFnFVOFA",25453,8280,3],["5c9NjVEiSOGVeFiQ9tdHYg",217415,3322],["5woLhtEbSPuhPazSSQoluA",197842,0],["6kdvBVYWSuuyehSCCPGLYw",11195,237,3],["6ryKJq12TO-2vFdLKAIPXw",100122,163,4],["7587mqPLR3iJGXGBXjcDIQ",194177,56975],["8M_zxblPSkGw-_mE0gJUXQ",364739,2101,1],["9OZ_7xz9SkS56dk0cpJsLA",279830,659,1],["9UnXYYzZSYiFRDOzfNeCvw",264541,6248,1],["9gX-Lr9aTTKqMIA4Mb5MGg",28665,254163,1],["9pgiN8b5R8CzMX_G28g_Xg",388466,3300,2],["9uEITVHeQXegRVD6lXnz8w",297708,5964,1],["90eBgHt_S0Gai4x7q3f8eA",10519,253386],["92hhaxj2R1mlus6Ck9XBPQ",268366,15,6],["-Haa3Cb8RzO-mee5e4tggA",147060,1287],["-Rrwi9qrTv2pEbUgjIPivw",142099,14],["-3NMp6qyR9q05KN8ZX48Dg",33123,33796,3],["_MZl_4kLSDGUuDuNMl1-6g",369100,2265,2],["_QIygAxARMO5xTL3TO8SKg",90452,14,3],["_66f6qhySiOVSH5VcwD-kQ",293656,137,1],["_7nqDabvQF2tbBmkp4eb6Q",386660,0,2]],[[0,1,191271,2,26643,3,354359,4,24701,5,225088,6,289885,7,201106,8,37620,9,256968,10,17452,11,365338,12,174277,13,221305,14,67654,15,118185,17,191745,18,9776,19,369026,20,97667,21,245351,22,201626,23,23539,24,287749,25,27715,26,40652,28,63416,29,120261,30,77482,31,369844,32,318670,34,36639,35,13497,36,301783,37,113723,38,358493,39,206694,41,114776,42,291542,43,270735,45,269660,46,241420,47,375235,48,234562,49,381817,50,365395,52,433544,53,303521,54,39051,55,132912,56,337258,57,89223,59,47106,60,374592,61,34699,62,16742,63,145791,64,31682,65,363398,66,119148,67,52752,68,119433,69,422209,70,179877,72,362490,73,249681,74,90750,75,110092,77,195567,78,214810,79,423559,80,232673,81,121976,82,341963,83,248473,84,209959,86,25044,87,125762,88,100391,89,13473,90,344691,91,421843,93,221169,94,290981,95,280684,96,240401,97,88854,98,20420,99,115231,100,196666,101,437964,102,212360,103,32024,104,383388,105,259692,106,293635,107,112992,109,432574,111,423110,112,97987,113,129925,114,147489,115,355186,116,299605,117,23525,118,24722,119,20,120,29018,121,24421,122,203672,123,302108,124,382456,125,100417,126,34821,127,26661,128,20967,129,208332,130,429106,131,184801,132,390470,133,16796,134,341114,135,101701,136,364515,137,297724,138,204929,139,30097,141,20613,142,58021,143,11514,144,103781,145,106348,146,377892,147,22247,148,31993,149,289102,150,379181,151,269607,152,40388,153,69615,154,304597,155,26641,157,424098,158,16839,159,232374,160,430897,161,11034,162,192807,163,196695,164,25878,165,217502,167,11258,168,100136,169,194187,170,364747,171,279840,172,266280,173,28677,174,388528,175,297712,176,10531,177,268378,178,147110,179,142110,180,33135,181,369117,182,90463,183,293665],[1,1,191403,2,26877,4,25011,6,290244,8,38012,10,135101,11,365564,12,174521,13,221461,14,70866,15,118434,17,194565,18,10436,19,369151,21,245755,25,27750,26,40966,28,63838,30,78953,31,369987,34,271072,36,302091,42,292625,45,269918,47,375662,48,234981,49,382343,50,365969,56,337683,61,35564,62,17369,65,363850,70,180343,73,249848,74,93618,77,281773,78,214997,81,145234,83,248720,84,210906,86,25873,89,13762,90,344778,98,21616,99,115359,100,196869,102,214588,103,33124,106,293788,109,432827,113,130388,114,419890,115,355381,116,300912,118,24984,119,25211,124,385030,126,35004,128,21266,129,208665,130,429479,135,377244,139,30472,141,20849,144,290828,147,374711,149,371387,150,380038,157,425942,158,17350,159,232638,161,11255,169,251142,172,266492,173,200146,174,388714,175,298220,176,116422,180,33438,181,370575],[2,1,191761,2,26936,4,25652,6,290128,10,135093,11,365556,12,174506,13,222661,14,204836,15,119256,17,194663,18,112037,21,245876,26,41195,28,63729,36,302040,42,292786,45,269974,47,375721,48,234981,50,366237,56,337503,61,35520,62,17526,65,363886,70,180169,74,96379,77,282412,81,145315,83,248754,84,211047,86,25686,89,13752,90,344804,99,115637,100,197049,102,216835,113,130997,114,419917,115,355380,118,25605,119,25371,124,383289,128,21230,130,429474,135,377269,139,30496,141,20917,144,385343,150,379732,158,17595,159,232666,161,11354,171,280197,172,266472,173,200160,174,389034,175,298714,176,116572,181,370591],[5,74,101510,89,120349,128,22252,173,200261],[6,2,27153,12,174657,14,207834,89,13796,128,21666,173,200632],[7,1,191426,4,26737,6,290782,8,38242,9,259927,14,83478,23,24000,25,28120,30,78409,32,319011,34,38178,37,188014,43,270914,47,376773,49,382530,54,39411,61,35165,62,18098,74,91322,77,283158,81,122210,82,342359,83,249109,89,15076,102,212507,104,408595,105,260129,115,356759,121,25152,124,382604,127,27380,128,55608,129,209435,133,108888,135,147785,136,365613,137,299395,141,21485,149,289208,152,41570,157,424893,158,17870,161,280009,162,235865,170,364915,172,268642,173,113688,175,297802,176,10914,181,369796],[8,1,191304,2,27344,4,24911,6,290372,8,37848,9,257230,11,365879,12,174714,14,67718,17,197179,18,113098,21,245454,23,23612,25,27763,26,41186,30,78269,32,318871,34,36704,37,187874,42,294092,47,375996,48,235366,49,382263,54,39237,57,89275,61,34845,62,16821,74,90789,77,195597,78,294671,82,342519,83,248882,86,25562,89,14016,90,345085,100,198235,102,213131,104,408208,105,259742,112,98505,115,357048,119,267855,121,24568,124,382481,127,26894,128,22228,129,209359,132,391324,133,108196,136,365559,137,298989,141,21239,148,114644,149,290977,150,379324,157,424728,158,17014,161,11623,162,235545,164,27402,165,217591,167,11431,172,266558,173,28743,174,390487,175,297945,176,10852,181,369155,183,293764],[9,4,24947,14,124595,21,251727,34,254051,89,204437,121,24568,133,108196,158,20008,172,268084],[10,10,374646,11,365856,18,29044,21,246093,36,302622,42,293318,45,270168,61,35664,70,181083,74,94416,77,282919,84,211479,89,14055,99,116043,102,218148,115,355704,116,303469,124,384432,128,55963,130,431869,157,430786,158,24354,172,265911,173,282338,174,390520],[11,4,26736,17,192182,34,120809,36,304372,47,376752,48,237261,49,382325,61,426657,62,17177,74,92754,77,283423,83,249108,100,197742,102,213730,112,98720,114,420746,124,385160,128,318806,136,365447,137,299353,144,289095,149,290481,158,20965,160,431153,161,280037,172,264711,173,114102,175,300912],[12,1,191425,4,24722,6,290787,8,38527,10,374316,14,121713,17,196675,18,107315,20,97778,21,252728,23,24000,25,28120,30,78592,32,319011,34,108438,36,303508,37,113790,42,291912,47,376820,49,382397,50,365551,54,39407,56,337608,57,90476,61,206402,62,16919,74,91648,77,281947,78,294736,81,122083,82,342093,83,353761,84,211929,89,43353,94,291137,96,240608,100,197078,102,212515,103,32514,105,260264,107,113267,113,130585,114,419848,116,300962,124,382645,127,27423,128,55609,132,391032,133,108887,135,147784,136,365614,137,299469,143,11706,144,104301,145,106594,147,374763,149,289257,150,384351,151,269757,152,41479,157,425607,158,18012,161,110764,162,235879,168,100284,172,270247,173,113699,175,297801,176,10593,178,147214,181,370718],[13,4,24758,14,71230,34,242398,48,235358,61,35471,74,98685,133,108887,158,78115],[14,45,273422,78,215806,84,204504,110,132675,116,401030,124,383690,130,431406,136,365236,158,74280,175,298584],[16,4,26004,8,38458,14,210165,17,196587,18,10744,20,98085,25,27833,42,291833,47,376752,48,236419,54,39421,57,303665,62,18071,74,91316,77,301630,78,294675,81,122023,83,355044,94,291093,96,240572,102,213445,104,383590,115,357109,116,398245,118,380402,124,384746,128,56573,135,376985,137,299172,148,32382,157,425513,158,17750,161,11805,175,297873,181,369640],[17,3,354469,4,25296,6,290190,12,175855,14,103020,17,194491,28,64429,30,78286,31,369999,34,182984,54,39586,55,133085,57,302318,61,207064,62,179559,74,92764,77,282434,78,286253,82,342039,83,248781,89,42902,100,197667,102,212649,109,432657,112,98249,113,130070,114,420504,116,300601,118,25397,121,26268,124,383302,126,35081,130,431627,132,391584,136,365374,137,299921,143,11632,157,429460,158,21084,161,11375,173,113883,175,300479],[18,4,25332,10,135105,11,365623,12,175107,14,71139,17,196976,18,112078,21,245597,36,304490,42,292808,45,272914,48,234998,56,346890,61,206011,70,180164,73,249874,74,99353,77,284595,78,215864,81,145286,86,429778,89,13788,90,344982,98,21613,99,115373,100,198070,102,212467,105,259888,115,355780,119,25912,121,26268,124,388453,128,21255,130,429684,141,20897,144,384877,149,291763,150,384742,158,24245,162,288310,165,217575,172,267542,175,299709],[19,1,191505,4,25153,6,290163,8,37859,9,258622,13,222651,14,124567,17,195544,18,107317,21,251485,23,23627,25,27916,28,188921,30,78400,32,319421,34,36844,37,187526,42,292712,47,376156,48,236882,49,382399,50,365450,57,302393,61,34956,62,17794,74,91304,77,281875,78,363130,81,122066,82,342083,83,249043,84,208552,89,43348,96,240575,102,212853,104,408403,105,260336,109,432658,113,130646,114,419593,116,300144,118,25369,119,267176,121,24824,124,382580,127,26983,128,57118,129,209100,130,431893,132,391901,133,108754,136,365494,137,298902,139,30309,143,11760,144,288492,145,106522,147,374823,148,116020,149,289201,152,40754,157,425760,158,17343,161,279984,170,366547,172,266672,173,113460,174,390196,175,297850,176,116964,181,369630],[20,4,25189,121,24824,124,385693,133,108754],[21,2,26996,61,427115,89,195346,157,428408,158,263423,162,287847,172,267224,173,281557],[22,14,123728,17,197312,18,107323,21,252670,47,377566,62,17096,74,91943,77,281723,83,354448,100,198850,102,213072,107,113311,116,304590,124,382583,127,372792,132,391115,136,365580,137,300102,150,384682,152,41478,158,22009,172,269722,173,201023,175,297768],[23,74,92072,77,302595,102,213092,124,384683,158,106247,172,269734,175,300252],[25,1,191404,14,210559,74,103507,77,282901,78,214910,82,342291,83,249655,102,212392,124,384532,127,112599,133,108407,149,289120,175,298129,181,369126],[26,12,185477,14,109479,17,195329,21,248783,42,295126,45,273163,56,346839,74,96996,77,208550,84,207107,89,110513,102,215942,110,134283,116,304075,119,110526,121,114968,124,386037,128,60621,133,108407,144,386532,148,117825,150,381627,157,429459,158,25016,175,303068],[27,61,36271,121,114968,124,383305,133,434195,139,30359,149,290550,175,302397],[28,102,216662,124,382614,175,297813],[29,1,191381,2,26831,4,25093,6,290187,8,38238,10,296441,11,365547,12,174667,13,223097,14,71264,15,118514,17,194670,18,10718,19,369203,20,98030,21,245525,23,24040,25,27853,26,41154,28,63954,30,77655,32,319016,34,36880,36,302068,42,291863,43,270947,45,269762,47,375812,48,235044,50,365896,54,39410,55,133254,56,337622,57,89600,61,35319,62,16966,65,363856,69,423612,70,180530,73,249892,74,91305,77,281807,81,122103,83,248967,84,211240,86,26562,90,344834,94,291135,96,240590,98,22085,99,115666,100,197074,102,212540,103,32485,104,383811,107,113262,109,432692,112,98804,113,130302,114,419910,115,355419,116,303556,118,25022,119,526,121,25203,124,382636,126,35057,127,26920,128,21320,129,208926,130,429477,132,391434,133,109367,135,377050,136,365057,137,298037,139,30386,141,20839,143,11694,144,103933,148,114947,149,289297,150,379630,152,41539,157,424904,158,17243,159,232762,161,11410,162,287928,164,28962,165,217992,170,365437,171,280205,172,265906,173,28954,174,389148,175,297884,176,10921,181,369297],[30,4,25129,121,25203,133,109367,161,369733],[31,10,374525,12,176382,13,221895,14,126836,18,10417,21,246095,25,28086,30,78065,32,319287,37,188289,42,292307,45,270035,47,377041,50,366703,56,338039,57,90141,61,207037,70,180845,74,93795,78,215776,83,249727,84,204362,89,107481,99,115724,100,199494,102,214010,110,130215,114,420164,115,356298,116,301335,119,0,124,383030,127,27602,130,429954,136,364827,141,21112,157,427514,158,72072,170,366834,171,280483,172,265218,175,300421,176,263900],[33,1,191776,10,296506,11,365621,34,38079,36,302337,42,293115,47,375844,62,59047,65,364009,77,282254,81,145459,115,355837,118,122093,124,387234,128,21571,130,429714,158,19455,173,200446,174,389493],[34,8,38404,25,28065,57,302660,61,34870,74,92335,83,250320,102,213816,105,260325,116,300730,124,386317,144,289116,158,22018],[35,4,25269,6,290038,8,38275,13,222496,17,195112,18,10633,25,27809,28,64123,30,77500,34,254918,36,303374,42,360305,45,276602,48,235550,57,303544,61,36191,74,92915,83,248885,94,291731,99,115630,100,199950,102,219571,113,130782,116,401290,118,25594,121,432761,124,383293,127,27750,128,318631,132,391465,137,298306,139,30513,141,21378,148,118915,157,424086,172,270124,174,389200,175,299106],[36,4,25305,121,432761],[37,57,302377,74,92225,102,213565,119,261,124,382877,158,22256,172,266074,175,297740],[38,45,272277,74,94416,84,211479,102,218148,124,384432,158,110089,172,265911],[39,74,97963,77,281739,102,213091,124,382613,136,365592,158,173209,172,269542,173,281466,175,299583],[40,74,105068],[41,4,25170,6,289906,12,174728,14,67955,17,195667,18,113027,25,27722,50,365707,54,39168,57,90303,62,17228,69,423455,74,93501,77,301283,89,15351,91,421743,95,280710,99,116177,102,215121,103,32636,109,432665,113,129984,115,356679,116,400156,121,25726,124,384916,132,390794,135,377118,136,365993,139,31379,143,11571,145,106322,147,22462,158,17208,159,232523,161,284364,162,235523,173,113389,175,299541,176,116451],[42,4,25206,74,94427,102,216172,121,25726,124,384484,175,297822],[43,124,384494],[44,2,27065,4,24998,8,37896,9,258677,10,296542,11,365657,12,174379,14,67808,17,195704,18,112952,21,245429,23,23733,25,27777,26,41035,34,36980,36,302570,37,187908,42,292948,45,269903,47,375938,48,235017,54,39380,57,304103,61,35232,62,16865,74,90988,77,282572,80,232782,83,249042,86,25894,89,13885,90,344901,100,197788,102,214872,105,259819,112,98560,114,421048,115,355470,119,268540,121,24838,124,388670,127,26880,128,21985,129,208847,130,430084,141,21325,144,385312,148,116181,150,381354,157,425400,158,17056,161,11575,162,235759,164,28303,165,218031,172,266620,173,28827,174,389351,175,299217,176,263299],[45,4,25034,50,365924,74,105201,83,355113,99,115884,110,130804,112,98230,121,24838,137,298117,158,22765,172,265327],[46,137,299323,158,22601],[47,4,24994,13,223105,15,119001,28,189088,32,319329,48,235877,50,366471,56,337483,61,426414,74,90941,78,285331,83,249081,86,25500,89,43893,90,345028,102,213712,115,355381,116,400930,121,284262,124,386720,128,56235,129,209262,137,297767,144,385207,157,426525,158,21129,161,284250,172,265124,180,33620],[48,4,25030,49,381894,60,374700,69,423497,74,97521,75,110145,80,232716,102,213657,118,121940,119,30130,121,284262,141,22071,161,369609,169,250908,171,279948],[49,14,204027,102,221572,158,17815,175,299731],[52,42,291797,61,36074,74,97029,83,354951,102,213336,127,373039,128,318977,144,380529,173,281527,175,298219],[53,74,93052,83,353710,129,209051,158,255175,172,269548],[54,14,119904,21,248936,34,108044,61,207416,74,95588,89,14524,128,58042,157,427025,158,18504,172,268247,175,301597],[55,1,191428,2,337581,4,441091,6,290458,9,257426,10,374408,12,174844,14,118370,15,118168,17,192183,19,369078,21,245638,31,370134,32,319005,34,101422,36,301967,37,188018,42,291882,45,270154,47,376752,50,365565,60,374729,61,206787,71,299651,74,103186,77,283094,78,294682,81,122391,82,342350,84,203514,86,429769,89,192464,90,345160,99,116281,100,196668,102,212862,104,383348,105,259936,114,420753,115,355426,118,380896,121,111372,124,382565,127,372529,128,317960,129,209107,132,390869,133,107924,136,365542,137,298946,144,384220,148,114234,149,289184,150,379157,157,424868,158,106762,161,280010,162,235590,165,217561,172,266631,173,200315,174,388467,175,297857,181,369188,183,293788],[56,121,111372,133,107924],[57,6,289972,114,420957,119,266958,121,111565,127,372077,144,288507,158,110162,175,302496],[58,17,197366,21,245231,74,104124,78,215230,102,213041,121,111565,124,384598,144,287805,158,173028,165,217445,172,269648,175,297908],[59,34,391437,61,114991,65,363441,74,105537,78,215231,89,106995,90,344794,102,212810,124,384583,136,365953,158,196543,175,297902],[60,14,123957,18,107350,21,252949,36,303740,49,382413,56,346880,74,102675,77,301840,78,215467,82,342336,84,212308,94,291699,100,198904,102,215489,107,113320,114,420022,124,384639,127,372776,136,365686,150,384747,158,106330,173,201096,175,299916,176,116916],[61,1,191420,13,221449,17,197118,18,113400,32,318997,34,194687,42,291861,48,236805,57,302135,61,206823,62,179418,69,422282,77,281930,78,363173,81,122369,83,250206,100,199717,102,212500,113,130376,114,419958,116,302518,118,381733,124,382618,133,108810,135,376961,144,103912,145,106400,147,374707,149,289246,154,304637,157,424849,158,353670,161,279995,172,269968,173,113543,175,297846,181,369686],[62,133,108810],[63,1,191363,14,127000,24,288037,28,189890,34,365376,48,236230,56,441217,57,302789,74,105340,78,284879,96,240556,102,213420,104,384238,124,385272,135,377004,137,298932,148,118495,158,107956,161,110547,170,366328,173,113261,175,303255],[65,2,337650,4,441098,6,290343,32,318924,34,372242,42,294133,47,375872,49,382321,61,427163,77,281660,78,294667,83,353649,89,282739,90,345104,104,408130,115,357049,119,267398,121,432547,124,382456,127,372515,128,317930,132,391156,133,430633,136,365533,137,298941,149,289151,150,379391,157,424757,158,272882,161,279952,162,287535,172,266559,173,281659,174,390786,175,297783,181,369141,183,293771],[66,36,304038,42,292535,45,270412,50,366698,56,338296,57,302887,69,423947,78,285653,114,421210,115,356053,116,302761,121,431688,124,383151,128,318191,130,431526,133,430633,136,364820,144,385684,157,429858,158,273730,172,265210,175,298518],[67,3,354577,4,440718,6,290151,10,374475,11,365914,31,369952,32,319012,34,373125,36,302051,42,291840,43,270912,45,269845,47,375384,49,382019,50,365552,57,304793,60,374837,61,427278,69,422650,77,281802,78,294678,82,342332,83,353757,86,428257,94,291103,104,384609,106,293733,109,432623,114,419903,115,355827,116,299864,118,380748,119,267188,121,284856,124,382605,127,372765,128,318014,130,430679,132,390903,134,341283,136,365614,137,297904,144,289098,147,374717,149,289252,157,424893,158,273017,161,279922,170,364913,171,280210,172,268962,175,297805,181,369750],[68,6,290183,10,374344,19,368988,27,299118,32,319041,34,271673,36,303683,42,291901,43,270914,44,284640,45,269651,47,376863,49,382406,50,365594,56,337726,57,302995,62,436784,71,299742,77,282733,78,285959,82,342332,83,353823,86,329345,90,344859,91,421617,94,291406,104,383983,114,419928,115,355154,116,299868,121,283727,124,382755,127,292292,128,318045,130,430698,132,391737,134,341392,136,364394,137,297941,144,289066,147,374832,149,289418,150,379152,154,304658,157,424484,158,273073,160,430905,161,283747,170,364972,171,280265,172,264794,173,282819,174,388508,175,299623],[69,10,296402,11,365566,34,365234,36,302688,43,270772,47,375632,49,381976,57,302134,61,426392,65,363478,78,294665,83,354920,89,282426,94,291007,106,293677,115,355666,116,300288,118,380568,121,432498,123,302226,124,382445,130,429727,132,390515,136,365522,137,299237,147,374645,149,290945,157,424893,158,273019,161,279942,162,287388,170,365279,171,280084,172,267250,173,282165,174,390615,175,297916,181,369369],[70,10,374721,11,366069,36,303579,42,292886,45,270377,57,304625,77,284531,86,429861,89,284239,115,356053,116,302978,121,432498,124,384000,128,318581,130,431496,136,365520,144,385719,157,430156,158,276314,172,268248,175,300409],[71,118,380826,124,386975,158,283967],[73,45,271543,89,282703],[74,6,290345,34,380603,61,427400,77,282057,104,408098,115,357053,124,384549,127,372524,132,391057,133,430683,136,365533,137,298936,144,383554,149,289152,158,272891,161,279950,172,267329,175,297791,181,369145],[75,133,430683,149,292107,158,349944],[76,132,391517]]] \ No newline at end of file diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 7c69165..0000000 --- a/.gitignore +++ /dev/null @@ -1,9 +0,0 @@ -.tmp-edge-profile/ -__pycache__/ -*.pyc - -# Local browser smoke/probe artifacts. -*probe*.html -*probe*.png -*smoke*.html -*smoke*.png diff --git a/.htaccess b/.htaccess index 1a8ccd5..fedc16b 100644 --- a/.htaccess +++ b/.htaccess @@ -1,3 +1,5 @@ +AddType application/manifest+json .webmanifest + ExpiresActive On ExpiresByType text/html "access plus 0 seconds" @@ -21,15 +23,22 @@ Header set Pragma "no-cache" Header set Expires "0" + + Header set Cache-Control "public, max-age=2592000, immutable" + Header set Cache-Control "no-cache, no-store, must-revalidate" Header set Pragma "no-cache" Header set Expires "0" - - Header set Cache-Control "public, max-age=2592000, immutable" - AddOutputFilterByType DEFLATE text/html text/css application/javascript application/json text/plain + + +# Never serve hidden server-data paths. + + RewriteEngine On + RewriteRule (^|/)\. - [R=404,L] + diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..6f3a291 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "liveServer.settings.port": 5501 +} \ No newline at end of file diff --git a/ACHIEVEMENT_AUDIT.md b/ACHIEVEMENT_AUDIT.md deleted file mode 100644 index 5f3a086..0000000 --- a/ACHIEVEMENT_AUDIT.md +++ /dev/null @@ -1,268 +0,0 @@ -# 実績システム再監査レポート v39.16.78 - -対象: 全72実績、解除イベント、判定順序、進捗リセット、保存・復元、Undo/Redo、サーバー同期 -方針: 前回重点対象だった「自分のずんち」「敵の敵は味方」だけでなく、これまで大きく取り上げていなかった実績を再度コード経路から監査した。明確な不具合は修正し、ゲームデザイン判断が必要な条件は変更していない。 - -## 1. 今回新たに確定・修正した不具合 - -### 1.1 「ミニマリスト」: プレイヤー設置物情報が保存されなくなる - -`ミニマリスト` は「現在存在するプレイヤー設置物が10個以下」を判定するため、各アイテムの `_achievementPlayerPlaced` を必要とする。 - -旧実装では、この情報を保存する条件が実質的に `無計画都市` の未解除状態へ依存していた。そのため、`無計画都市` を先に解除した後にセーブ・ロードすると、既存アイテムのプレイヤー設置情報が失われ、`ミニマリスト` の物数判定が過少になる可能性があった。 - -**修正:** `無計画都市` と `ミニマリスト` のどちらかが未解除なら、プレイヤー設置情報を保存する。30秒削除用の設置時刻は従来どおり `無計画都市` に必要な場合だけ保存する。 - ---- - -### 1.2 「サウナ水風呂」: 高温開始時刻が更新され続ける - -条件は「暑すぎる状態になった個体を15秒以内に寒すぎる状態へ移す」だが、旧実装は高温状態を評価するたびに開始時刻を現在時刻へ更新していた。 - -このため、長時間高温に置いた後でも、寒冷へ移した直前の評価時刻との差だけで15秒以内と判定され得た。 - -**修正:** 快適域外の高温状態へ**入った瞬間**だけ開始時刻を記録し、連続して高温にいる間は更新しない。高温状態を離れてから再び入った場合は新しい試行として時刻を記録する。 - ---- - -### 1.3 「抵抗器じゃない」: 致死感電した7体目がカウントされない - -旧実装では感電ダメージを与えた後に実績カウントを行っていた。感電が致死になると対象は死亡済みになり、`recordWireShock` の生存チェックで除外されるため、7体目がその感電で死亡すると解除できない場合があった。 - -**修正:** 有効な感電を確認した時点で、ダメージ適用より先に実績カウントを行う。致死・非致死のどちらでも、その感電自体は1体分として扱う。 - ---- - -### 1.4 実績リセット後に隠れた途中進捗が残る - -全実績リセット後も、World・たりない・アイテム本体に直接保持された一部の途中状態が残っていた。そのため、リセット直後に少ない追加操作だけで再解除できる実績があった。 - -**修正したリセット対象:** - -- 同一個体への直接給餌回数・直接治療回数 -- サウナ開始時刻・直前高温状態 -- たりない保持開始時刻 -- 喧嘩餅から喧嘩開始までの一時情報 -- 粘着爆弾の受け渡し回数 -- `無計画都市` 用の配置時刻 -- 自然奴隷・自然王の世代進捗 - -`ミニマリスト` が現在の配置物を正しく識別するため、既存アイテムの「プレイヤーが配置した物か」という事実自体はリセットで消していない。 - ---- - -### 1.5 「監視カメラ」: Undo/Redo・地面変更が介入になっていない - -配置・削除・給餌・つつく・射撃などは観察タイマーをリセットしていた一方、Undo、Redo、有効な地面変更は世界状態を変更する操作なのに観察タイマーをリセットしていなかった。 - -**修正:** 成功したUndo/Redo、および実際に地面種別が変わった操作を介入として記録する。 - ---- - -## 2. 前回重点対象の修正状態 - -### 「あぁ^~ たまらねぇぜ」 - -現在の条件は次の経路で成立する。 - -`おしり鋲でずんち蓄積 → おしり鋲を抜いて排出 → 排出ずんちが本人から一度離れる → バウンス柵等で反射・加速 → 本人へ帰還して致死衝突` - -- 生成直後の本人との重なりは衝突扱いしない。 -- 本人から一度離れた後に帰還した衝突だけを自己帰還として扱う。 -- 非致死では解除しない。 -- バウンス柵による反射・加速は資格を失わせない。 -- 停止済み・プレイヤー保持済みの排出ずんちは対象外。 -- 致死処理で本人の生存IDが解放されても、ダメージ前に所有者一致を保持するため解除可能。 - -### 「敵の敵は味方」 - -30体以上の状態で稼いだ連続数は、生存たりないが30体未満になった時点で0へ戻る。危険カテゴリのアイテムによるたりないへのダメージでも従来どおりリセットする。 - -前回ユーザー確認済みの「無傷」の範囲、戦闘ペア危険死の期限、機械化産業の履歴AND条件は現行仕様のまま変更していない。 - ---- - -## 3. これまで大きく取り上げていなかった実績の再監査結果 - -### 生態・繁殖 - -- `はじめての繁殖`、`ベビーブーム`、`大いなる母` は実際の繁殖成功イベントから接続されている。 -- `天寿`、`水銀で天寿` は最終確定した死亡理由を受けた後に判定される。 -- `25体全員が病気` は睡眠病だけを除外し、ずんち病・爆発病・喧嘩病を対象としている。 -- `管理された楽園` は6日目以降から連続1ゲーム日を計測する。 -- `安全第一` は25体以上を300ゲーム秒維持し、天寿以外の死亡で再計測する。天寿後に25体を下回れば人数条件によって停止する。 -- `自給自足` は20体以上・複製機なし・直接給餌なしを600ゲーム秒維持するフィールド内条件。 -- `雨宿り完了` は現行の雨天である小雨時に、パラソル・巣箱・土管の保護判定を使う。 -- `町のお医者さん` は応急手当を使った回数ではなく、実際にHPが1以上回復した回数だけを累計する。 -- `豊穣ヲ希求スル者` はラブ餅の影響下で成立した繁殖だけを累計する。 - -**追加の到達不能・イベント未接続は確認されなかった。** - -### 実験・危険行動 - -- `6番目の大量絶滅` は同一Worldの10ゲーム秒ローリング区間で死亡50件。 -- `豆野、殺ッカーやろうぜ!` は通常ボールの速度条件を満たした致死衝突から直接接続される。 -- `ヘコヘコ中に着火` は着火処理が繁殖儀式状態を消す前に判定される。 -- `下剤中の餓死` は死亡フレームの下剤状態を保持して判定する。 -- `物理法則を下側に超越` はアイテム位置の実温度計算を走査しており、温度効果の重畳で到達可能。 -- `おくすり手帳全埋め` は現行仕様どおり11種類を対象とし、鎖・王冠は除外する。 -- `革命` は王の喧嘩死と、直前0.1ゲーム秒以内の奴隷による喧嘩ダメージを照合する。 -- `火に油` は喧嘩餅を受けた個体が30ゲーム秒以内に参加する喧嘩開始を判定する。 -- `五体満足` / `零体満足` は状態効果付与時と自然ステータス変化時の双方から再評価される。 -- `混沌ヲ希求スル者` は喧嘩餅影響下の喧嘩開始だけを永続累計する。 -- `命のバトン` は同じ生存中の粘着爆弾の受け渡し回数を保存・復元する。 -- `情報化産業` は別々の2基盤を電線類で直接つなぎ、信号が実際に伝達された経路から解除される。 - -**追加の確定不具合は「抵抗器じゃない」の致死感電順序だけで、修正済み。** - -### 建築・環境 - -- `物でいっぱい` はプレイヤー配置イベントを永続累計し、リンク類の配置も配置として数える。 -- `清掃業者` はロボット掃除機による有効な清掃200回のフィールド内進捗で、現行ドキュメントと一致する。 -- `潔癖症` は生存たりない0、生存アリ0、生存アイテムがロボット掃除機のみ、かつ条件を満たす稼働掃除機が存在する場合に成立する。死亡たりないは死亡直後に非表示となり定期圧縮されるため、画面上の死体残留との矛盾は確認されなかった。 -- `メガロポリス` は100体・複製機10・草ベッド/巣箱/土管合計15の境界値で評価される。 -- `砂場` は生存中のトイレ5個で成立する。 -- `そこ公共空間だよ?` は公園フィールドで実際に地面変更が成立した時だけ解除する。 -- `破格の工事費用` は壁時計1秒以内の有効な地面変更4回を数える。 - -**追加の確定不具合は「ミニマリスト」の保存メタデータだけで、修正済み。** - -### 操作・継続 - -- `秘密のコレクション` は9スロットすべてに実セーブハッシュがあることを確認する。 -- `何やってるの?` は空フィールドへのクリックだけを壁時計1秒内に4回数える。 -- `見なかったことにしよう` は1回のUndo前後で死亡個体が10体以上減った場合に成立する。 -- `やっぱなし` / `やっぱあり` は成功したUndo/Redoだけを永続累計する。 -- `割とふわふわ` は共通の「つつく」対象判定からぬいぐるみを飛ばした場合に成立する。 -- `狙撃手` は命中ではなく発砲333回を永続累計する。 -- `スペックがたりない` は有効な計測FPSが10未満になった場合で、非表示タブ由来の異常なフレーム間隔を除外する。 -- `毎日たりない観察` はローカル暦の日付単位の7日連続起動。 -- `寝ろ` / `めっちゃたりない観察` は壁時計の連続経過で、現行仕様どおりタブ非表示時間も継続として扱う。 -- `真・たりない観察` は自身以外の71実績が解除済みかを判定する。 - -**追加の確定不具合は「監視カメラ」の介入漏れと、全実績リセット後の隠れ進捗残留で、修正済み。** - ---- - -## 4. 仕様確認が必要な曖昧点 — 現在は未変更 - -以下は実装が壊れているとは断定できず、表示文から複数の解釈が成立するため、回答を受けるまで条件変更を行っていない。 - -### Q1. 「ずんちどれい」「たりない王」の「出現」範囲 - -現行は**喧嘩戦績による自然変身だけ**で解除する。 - -- 鎖を付けて奴隷化 → 対象外 -- 王冠で王化 → 対象外 -- 奴隷同士から生まれた生来の奴隷 → 対象外 - -候補: - -- **A: 現行どおり** — 喧嘩戦績による変身だけ -- **B: 人工付与以外** — 喧嘩戦績変身 + 生来の奴隷を対象。鎖・王冠は除外 -- **C: 文字どおり全出現** — 鎖・王冠を含め、状態になった時点で解除 - -### Q2. 「末代までの恥」「華麗なる王族」の「○代連続」 - -現行は**同じ家系でなくても、自然変身した個体の世代番号が連番なら成立**する。例えば無関係な家系の2代・3代・4代・5代・6代に自然奴隷が1体ずついれば5代連続になる。 - -候補: - -- **A: 現行どおり** — 世界内の世代番号の連続 -- **B: 直系家系限定** — 親子関係を辿って同じ系譜で連続して状態が続く必要がある - -Q1で生来の奴隷を対象にする場合、Q2の奴隷5代判定にもその出生を含めるかを合わせて決める必要がある。 - -### Q3. 「過保護」の「薬で治療」 - -現行は、薬カテゴリの直接使用なら効果の善悪を問わず治療回数に加算する。対象には応急手当だけでなく、睡眠薬、下剤、プロテイン、ニテロプ、弾薬、水銀、巨大化薬、小型化薬なども含まれる。 - -候補: - -- **A: 現行どおり** — 薬カテゴリの直接使用3回 -- **B: 治療系アイテムだけ** — 対象薬を明示的に限定 -- **C: 実際に有益な回復が発生した使用だけ** - -### Q4. 「無計画都市」の「削除する操作を累計30回」 - -現行は**操作回数ではなく、30秒以内に削除された対象物1個につき1回**進む。範囲削除1回で対象物を10個消した場合、最大10進む。 - -候補: - -- **A: 現行どおり** — 削除した対象物数を数える -- **B: 削除コマンド単位** — クリック/範囲削除の1実行を1回として数える -- **C: 連続削除ジェスチャ単位** — 押している間の連続削除を1回として数える - -### Q5. 「監視カメラ」の5分と「見るだけ」の意味 - -現行は**300ゲーム秒**。高速化すれば実時間5分より早く解除できる。今回、世界を変更するUndo/Redo・地面変更も介入として追加したが、UI操作、セーブ、速度変更、ポーズ、空クリックなど世界を直接変更しない操作はタイマーを止めない。 - -時間基準: - -- **A: 現行どおり300ゲーム秒** -- **B: 実時間5分** - -「見るだけ」の入力基準: - -- **1: 現行どおり世界への介入だけでリセット** -- **2: ほぼすべてのユーザー操作でリセット** - -例: `Q5 = A1` のように指定可能。 - -### Q6. 「抵抗器じゃない」のセーブ/Undo跨ぎ - -現行の「同じ1本」はランタイム中の同一電線オブジェクト。セーブロードやUndo/RedoでWorldが再構築されると、1~6体までの途中人数は失われる。 - -候補: - -- **A: 現行どおり** — 7体すべてを同じランタイム中に感電させる -- **B: 同じ保存上の電線なら継続** — セーブロード後も電線ごとの途中人数を保存する - -### Q7. 「害虫駆除」の「アリを倒す」主体 - -現行は**アリが死亡した事実をすべて累計**する。プレイヤーの危険アイテムだけでなく、たりないとの戦闘、設備・環境など別要因で死亡しても1体として数える。 - -候補: - -- **A: 現行どおり** — 死亡したアリをすべて数える -- **B: プレイヤー由来の撃破だけ** -- **C: プレイヤーまたはたりない陣営が倒した場合だけ** - ---- - -## 5. 前回ユーザー確認済みの仕様 — 変更なし - -以下は前回の確認により現行仕様を維持している。 - -- 戦闘ペア危険死: 第1死亡から第2死亡まで同一World内で明示的な時間制限なし。 -- 機械化産業: ロープ・棒・ばねの配置履歴と信号作動履歴のAND。現在同時に存在する必要なし。 -- 敵の敵は味方: 「無傷」は危険カテゴリ由来のたりないへのダメージをリセット対象とし、あらゆるダメージを禁止する意味ではない。 - ---- - -## 6. 検証結果 - -v39.16.78 に対して以下を実行し、すべて成功した。 - -- JavaScript全ファイル・監査スクリプトの `node --check` -- 全72実績の定義・カテゴリUI・同期監査 -- プレイスタイル実績の境界値・リセット範囲・永続化・フック監査 -- 「あぁ^~ たまらねぇぜ」専用の生成直後除外 / 離脱 / 帰還 / 致死・非致死回帰テスト -- サウナ開始時刻、実績リセット、監視介入、ミニマリスト保存情報、致死感電の追加回帰テスト -- 実績イベント統合監査 -- サーバー状態・旧形式移行・並行同期監査 -- 全体回帰監査 `scripts/regression_check.py` -- Python監査スクリプトのコンパイル確認 -- `achievement_api.php` のPHP構文確認 - -結果はすべて `[OK]`。今回の再監査で新たに確認した**確定不具合は5系統で、すべて修正済み**。上記Q1~Q7は仕様回答待ちのため、v39.16.78では現行挙動を維持している。 - - -## Confirmed specification decisions (39.16.78) -- ずんちどれい / たりない王: birth-status appearances also qualify. -- 末代までの恥 / 華麗なる王族: only a direct qualifying parent-child lineage counts. -- 過保護: a treatment counts only when the direct use actually improves the health need. -- 無計画都市: one deletion operation counts once, even if area deletion removes multiple objects. -- 監視カメラ: requires 3 uninterrupted game days; gameplay operations are interventions. -- 抵抗器じゃない: partial wire progress remains nonpersistent across save/load and Undo. -- 害虫駆除: only player-caused ant deaths count. diff --git a/AI_MAP.md b/AI_MAP.md deleted file mode 100644 index 820acb1..0000000 --- a/AI_MAP.md +++ /dev/null @@ -1,105 +0,0 @@ -# tarinai_ AI map - -Purpose: static Japanese browser simulation/game. Optimize context by reading this file only after `README.md`, then open the relevant subsystem files. For exact file expansion, use `scripts/ai_inventory.ps1` or `scripts/ai_inventory.py`. - -## Architecture - -- Entrypoint: `index.html` defines the app shell, canvas, dialogs, right panels, and exact script order. -- Runtime style: plain browser JS, global IIFEs, exports on `window`, no bundler/module loader. -- Version/cache: `app_manifest.json`, `js/version.js`, generated `service-worker.js`, and `index.html` query params share `39.16.78`. -- Main loop: `js/main.js` initializes assets/audio/world/UI/save, then drives update/render. -- Performance/display settings: `js/perf_profiler.js` owns manual visual settings and profiler buckets; display tiers affect rendering/visuals, not simulation-quality branches. -- Update order: `js/system_order.js` calls phase facades from `js/simulation_systems.js`. -- Command path: UI/input emits command objects; `js/command_dispatcher.js` routes tool, pointer, selection, save, reset, and UI intents. -- Persistence: save files are schema/codec/storage/coordinator modules; snapshot/history modules keep world restoration and stats consistent. - -## Subsystem Map - -- Core/bootstrap: `js/version.js`, `js/event_bus.js`, registries, `js/data.js`, `js/ground_types.js`, `js/health.js`, `js/main.js`, `js/debug_tools.js`, `js/perf_profiler.js`. -- Rendering/assets/audio: `js/assets.js`, `js/audio.js`, `js/render.js`, `js/tarinai_render.js`, `js/item_render_runtime.js`, `js/sound_pack.js`. -- Simulation phases: `js/sim_core.js`, `js/simulation*.js`, `js/world_update*.js`, `js/system_order.js`. -- World domain: `js/world*.js`, `js/weather_system.js`; covers state, camera/view, environment, combat/effects, placement/history, tools, family/social, ants, spatial budgets. -- Creature domain: `js/tarinai*.js`; covers state, identity, needs, actions, forced behavior, social life, item effects, disease/nests, movement/update pipeline, rendering. -- Item/structure domain: `js/item*.js`, `js/items.js`, `js/structures.js`, `js/structure_lifecycle.js`; covers definitions, spawning defaults, lifecycle, dynamic behavior, rendering. -- Physics/mechanics: `js/physics*.js`, `js/mechanical_system.js`, `js/constraint_system.js`, `js/collision_footprint_system.js`. -- UI/input: `js/ui*.js`, `js/text_catalog.js`, `js/command_dispatcher.js`; covers panels, tools, selected creature, logs, charts, family tree, mouse/touch, dialogs, labels. -- Family tree: `js/family_graph.js`, `js/ui_family_*.js`; data transform, layout, paths, async rendering, validation. -- Save/history: `js/save*.js`, `js/snapshot_system.js`, `js/restore_coordinator.js`, `js/history_system.js`. -- Scripts: `scripts/generate_app_files.py`, `scripts/generate_item_icons.py`, `scripts/regression_check.py`, `scripts/ai_inventory.py`, `scripts/ai_inventory.ps1`. - -## File Pattern Semantics - -- `*_pipeline.js`: ordered runner/facade for update or lifecycle work. -- `*_step_*.js`: narrow pipeline step wrapper. -- `*_system.js`: domain service, phase service, or compatibility facade. -- `*_runtime.js`: stable runtime-facing facade around split modules. -- `*_registry.js`: definition registry and lookup/normalization helpers. -- `world_*`: world-owned behavior; `tarinai_*`: creature-owned behavior; `item_*`: item-owned behavior; `ui_*`: DOM/input/panel behavior. -- `assets/sprites/tarinai_*.webp`: creature visual state sprites; numeric prefix is stable asset ID/order. -- `assets/ui/tool_*`: tool palette icons; `assets/ui/favicon*`, `apple-touch-icon`, `ecology_*` are app/help icons. -- `assets/objects/*`: field object sprites for ants, zunchi, pushpin, oshibyo, genkotsu, plushie. -- `assets/sounds/voice_*`: creature voice samples; `shoot_*`, `major_damage_*`, `firecracker_*` are SFX. - -## Task-Oriented Read Sets - -- UI/layout bug: `index.html`, relevant `css/*.css`, `js/ui_bind.js`, `js/ui_layout_dialogs.js`, matching `js/ui_*.js`. -- Tool behavior: `js/command_dispatcher.js`, `js/world_tool_actions.js`, `js/item_registry.js`, relevant `js/item_*` or `js/tarinai_item_*`. -- Creature behavior: `js/tarinai.js`, `js/tarinai_update_pipeline.js`, relevant `js/tarinai_*`, `js/system_order.js`. -- World/environment/combat: matching `js/world_*`, `js/simulation_*`, `js/system_order.js`. -- Fire/burning behavior: `js/fire_runtime_system.js`, `js/item_dynamic_tool_system.js`, relevant item definitions, `js/world_combat_effects.js`, and nearby environment helpers. -- Performance/crowding: `js/perf_profiler.js`, `js/item_update_scheduler.js`, `js/tarinai_update_policy.js`, `js/constraint_system.js`, `js/world_spatial_budget.js`, and render/detail code. -- Save/load: `js/save_schema.js`, `js/save_codec.js`, `js/save_system.js`, `js/snapshot_system.js`, `js/restore_coordinator.js`. -- Family tree: `js/world_family_social.js`, `js/family_graph.js`, `js/ui_family_*.js`. -- Static app/cache/version: `app_manifest.json`, `scripts/generate_app_files.py`, `service-worker.js`, `js/version.js`, `index.html`. - -## Invariants - -- Preserve `index.html` script order unless all dependent manifests/generated files are updated together. -- Keep `app_manifest.json`, `js/version.js`, `service-worker.js`, and cache query versions synchronized. -- Keep intentional global exports for compatibility with regression checks and browser runtime; remove public facades only after repo-wide caller checks. -- Prefer focused edits in the owning subsystem; split modules are intentional compatibility boundaries. -- Avoid reintroducing `simulationQualityTier` branches unless a real simulation-quality setting is restored; current quality controls are visual/detail controls. -- `High` display quality may include quality-preserving optimizations, but should not reduce simulation cadence, object limits, or visible fidelity in a noticeable way. -- Save format compatibility with old text saves is not required when intentionally shortening/replacing save hash text; keep current save/load internally consistent instead. -- Run `node --check js/*.js` and `python scripts/regression_check.py` for behavior changes. - -## Current Maintenance Notes - -This section records current boundaries only. Version-by-version cleanup history and completed work logs are intentionally omitted. - -### Live Compatibility Surfaces - -- Ordered global-IIFE loading is still part of the app contract; check repo-wide callers before removing bare globals or facade objects. -- Keep public event names with active listeners: `audio:play`, `selection:changed`, `tool:selected`, `world:phase`, `log:entry`, and `tool:placed`. Telemetry-only emit calls should stay removed. -- Save compatibility with old exported text is not required, but the current save/load round-trip must remain internally consistent. -- Tool icon ownership is `TOOL_DEFINITIONS.icon`; UI code converts asset paths for CSS variables. Avoid restoring CSS-local `url(...)` definitions. -- Shared geometry/display/domain helpers should stay in their owning helper modules unless a dedicated namespace migration is being done. - -### Open Architecture Candidates - -- Full namespace migration for behavior/action/needs/tool helpers. This requires rewriting many bare global call sites and updating regression contracts. -- Effect-specific spatial indexing, fuller delta-history storage, and high-speed collision partitioning. These need new indexes or semantics beyond cleanup. -- UI/text-side meaning consolidation, including labels, wrapping/measurement helpers, and duplicated scalar helpers such as `num`, `finiteOr`, `isObject`, and `clonePlain`. -- Further `World.prototype` reduction is possible, but only for helpers proven not to be runtime-facing canvas/UI/tool APIs. - -## Current Feature Routing - -- Achievement system: `js/achievements.js`, `achievement_api.php`, `js/save_schema.js`, `js/save_codec.js`, `js/snapshot_system.js`, and achievement audit scripts. Current save schema is `49`; current app/cache version is `39.16.78`. -- Achievement UI: `index.html` achievement dialog, `css/components.css` achievement rows/toast styles, and `js/achievements.js` DOM rendering. -- Achievement spell payload: `TarinaiAchievements.exportSpellState()`, `snapshot.g.s`, `save_system.js` spell export inclusion, and `save_codec.js` achievement metadata readers/writers. -- Logic board: `js/circuit_board_system.js`, `js/signal_system.js`, signal-related item definitions/metadata, and the generated circuit editor markup/styles. -- Shared play: `js/seesaw_system.js`, tarinai action/need modules, placement preview, and item/structure definitions. -- Reset presets: `js/world_reset_presets.js`; UI reset selection is in `js/ui_layout_dialogs.js`; social archive reset/fallback routing touches `js/world_family_social.js`. -- Physics tool icons and previews: `js/ui_tools.js`, `js/render.js`, `js/placement_preview_system.js`, `js/physics_shape_editor_system.js`, and `js/item_tool_metadata.js`. - -## Cleanup Candidate Audit - resolved - -The previous cleanup candidate queue has been applied or adjusted. Current state: - -- Version/docs routing was aligned to `39.16.78`; `js/version.js` build identity now matches the app version, and `README.md` no longer points at an older cache-query script URL. -- One-version and overlapping audit scripts from the candidate list were removed; the broad audit suite remains `scripts/achievement_audit.js`, `scripts/playstyle_achievement_audit.js`, `scripts/achievement_integration_audit.py`, `scripts/achievement_server_state_audit.py`, and `scripts/regression_check.py`. -- Shared scalar/object/clone/hash/text helpers now live on `TarinaiCoreHelpers` in `js/deterministic_helpers.js`; action, behavior, structure, snapshot, save, geometry, physics, seesaw, placement-preview, circuit, and signal code route repeated helper logic through that shared surface or through `TarinaiGeometry`. -- UI HTML escaping is owned by `js/ui_helpers.js`; consumers bind explicitly to `TarinaiUIHelpers.htmlEscape`, and `index.html` loads `ui_helpers.js` before the consumers that need it. -- `js/achievements.js` uses `renderIfDialogOpen()` for progress refreshes instead of repeating the hidden-dialog check at each event recorder. -- `js/world_placement_log.js` uses shared close/backdrop binding for editor dialogs; deeper editor extraction can still be done as feature work, but the repeated close process from the cleanup list is removed. -- `FILES.json` now includes JavaScript audit scripts and newer core bootstrap files (`domain_ids`, deterministic helpers, item registries/definitions) in machine routing. diff --git a/BUILD_NOTE.txt b/BUILD_NOTE.txt deleted file mode 100644 index 55074fa..0000000 --- a/BUILD_NOTE.txt +++ /dev/null @@ -1,262 +0,0 @@ -tarinai_compact_save_stage4 -- Save schema 33 omits standard item amounts and stores only an optional non-standard block base plus per-item differences. -- Relationship targets are sorted and delta-encoded within each Tarinai row. -- World seeds use a canonical 64-bit hexadecimal identity and occupy exactly 8 bytes in the binary save. -- The binary header contains one schema byte; its high bit signals whether a string table follows. Empty string tables and the duplicate snapshot version are omitted. -- Deflate state is folded into the low bit of the frame-length varuint, eliminating the separate compression byte. -- 15-bit text conversion uses arithmetic Unicode range mapping instead of a 32768-character string and reverse Map. -- Binary schema 51 is the current save format; schemas 49 and 50 remain readable. Achievement payload v6 stores 72 unlock bits and persistent statistician progress while v5 remains importable. -- Version: 39.16.94 -- CompressionStream and DecompressionStream are drained concurrently to avoid browser backpressure stalls. - -- Load confirmation uses the in-game dialog; fan wind is realtime; zunchi tool preview opacity, carried plushie depth, and blanket grass rules were corrected. - -- Passive spring: removed time-driven oscillation; force now depends on extension/compression and relative endpoint velocity. -- Signal effects use the exported TarinaiEffect constructor. -- Pressure-switch placement/editor overlays display the configured detection radius. - -- v39.16.18: removed redundant physics normalization, dirty-marking, compaction, pickup, and collision bookkeeping; unified one-way-fence and bounce corrections while retaining debug diagnostics and defensive recovery paths. - -- Earlier mechanism pass: stronger passive spring, persistent detector ranges, robot-cleaner signal power, and electric shock effect. - -- v39.16.17: fixed the undefined bodyFor reference in mechanical one-way-fence contact handling by using the canonical body velocity helper. - -- v39.16.16: link rendering no longer depends on midpoint spatial visibility; bounce fences launch Tarinai without shock damage; passive springs are more under-damped and elastic. - -- v39.16.16: population chart includes per-bucket births/deaths; rotators accept signed motor speed; champion personality bonuses inherit through descendants; champion-pair mate weighting is moderately reduced. -- v39.16.16: colony population chart records births/deaths, rotators accept negative motor speed, champion personality boosts inherit through descendants, champion-pair mating is slightly reduced, and one-way fence previews/pathfinding honor the passable direction. - -- v39.16.16: one-way fences allow Tarinai forward crossing in swept collision; chart legend dots toggle series; wire tools attach to Tarinai/ants; energized living endpoints panic and take damage; selected data reports electrocution. - -- v39.16.19: added direct food/medicine giving by placement or pinched drop, with a give overlay, stronger food-gift personality change, and heart bursts; removed unused collision reasons and duplicate constraint projection dirty checks. - -- v39.16.20: localized the direct-feeding personality reason, normalized electrocution deaths to the Japanese electrocution label, added detector-controlled gate fences, made chart legend labels fully clickable, and escaped non-ASCII runtime source. - -- v39.16.21: hid pinch overlays for rope/rod/spring/wire connection items and added detector time schedules with a dual-thumb range control, overnight ranges, and persistent copy/save state. - -- v39.16.22: shortened detector copy, removed the time-range explanatory hint, cascaded connection-item removal when any endpoint disappears, and repaired detached plushies so they return to a living owner or disappear with a missing owner. - -- v39.16.23: excluded transient splat effects from all connection endpoint selection and renamed the user-facing feeding need from the formal feeding term to the appetite label. -- v39.16.25: added toilet-seeking before normal defecation; renamed rain shelter to parasol; added sunny +3.5C and unsheltered rain -3.5C felt-temperature corrections; parasols neutralize both and block sunbathing. Pet food, first aid, and sedative remain included. - -- v39.16.29: replaced toilet-seeking with walkable toilet sand that immediately removes poop spawned on its surface; added a parasol ground shadow and explicit hot-sun/cold-rain temperature-seeking targets; fixed null candidate temperatures being interpreted as 0C. - -- v39.16.29: aligned parasol placement overlay with its shade, made toilet sand absorb rain water, expanded Happy/Athletic/War presets, simplified Athletic rotators, and reserved their full rotation envelope from fences. - -- v39.16.30: added a few bounce fences to War, reduced ordinary-fence restitution, restored ball collisions for visible sleeping Tarinai, moved nest-box tooltips closer, allowed movable-item placement overlap, and fixed delete-tool target lookup. - -- v39.16.31: unified in-world tooltip spacing, added the Hair Trigger preset, and replaced physics-category line-like tool icons with distinct semantic silhouettes. - -- v39.16.35: moved snap-mode switching to a dedicated operation control with Free/20px/40px/60px cycling, removed F/G from size badges, allowed valid placement against the field top edge, and standardized preset descriptions with Japanese full stops. - -- v39.16.37: unified biological/environmental conditions into the detector, removed the standalone sensor and relay types with no save migration, folded temperature/limits, moved secondary controls into the header menu, preserved tool mode while browsing tarinai data, and added five-second mobile selection tips. - -- v39.16.38: detector numeric sliders match the time-control presentation; colony settings are unified; display settings are inline; meter colors, snap control, range-delete icon, and ant chart defaults are revised. - -- v39.16.39: restored the compact sticky operation palette, added exact-match panel search, reorganized colony settings/stats, and refreshed range-delete and mechanism icons. -- v39.16.40: moved partial panel search to the header with previous/next navigation and tooltip text indexing; localized snap mode labels; simplified bounce-fence and reciprocator icons; matched expanded colony settings to the chart background. - -39.16.41: Added local achievements and optional self-hosted shared unlock percentage API. - -39.16.42: Expanded achievements to ten conditions, added local/shared reset, rapid-event windows, generation streaks, and special collision tracking. - -39.16.44: Expanded achievements to fifteen conditions, changed rapid deaths to 50 in 10 seconds, moved conditions into game tooltips, added toast-to-button absorption, and added colony disease/happiness, cumulative hand feeding, ritual ignition, and laxative-starvation achievements. - -39.16.44: Audited all achievements; fixed impossible slave generation tracking, persisted generation runs, queued simultaneous unlock toasts, hardened launched-zunchi stop detection, and preserved laxative-at-death timing. - -39.16.45: Added seven play-style achievements for passive observation, fifty world placements, detector automation, rope/rod/spring coverage, a five-minute death-free 25-Tarinai colony, 25 live ants, and 30 cumulative ant kills; persisted world-scoped timers and placement progress. - -39.16.46: Revised achievement naming and disclosure UI, replaced achievement tooltips with inline post-unlock descriptions and horizontal shared-rate bars, merged detector automation plus link coverage into 機械化産業, changed placement and ant-kill goals to persistent totals of 100, and made direct-feeding progress reset with the field. - -39.16.47: Added 大いなる母 and 喧嘩両成敗, renamed five achievements, revised five revealed descriptions, and added a debug-only all-achievements button. - -39.16.48: Corrected the zunchi-slave fight-record threshold text to 30%; fixed wire placement totals, danger-kill attribution for 喧嘩両成敗, partial legacy link migration, strict player-ID validation, post-unlock storage writes, and debug-only unlock isolation from shared statistics. - -39.16.49: Added additive client-to-server full-state synchronization for automatic aggregate recovery after server-side achievement data loss. - -39.16.51: Expanded achievements from 27 to 43 with history, cleanup, care, ecology, temperature, weather, medicine, combat, and ant-experiment conditions; persisted the required reset-scoped metadata in a new incompatible save schema; made nest-box and pipe occupants weather-protected; and added false-positive guards for time-zero markers and stale ant damage attribution. - -39.16.52: Reorganized achievements into four collapsible categories, removed achievement tooltips, surfaced pre-unlock disclosures in the achievement UI, and replaced native browser confirmations with a shared in-game dialog. - - -39.16.53: Renamed the four achievement categories to 生態/実験/建築/その他, moved unlocked achievements to the top of their own categories, disclosed four additional conditions before unlock, raised 大いなる母 to 3333 births, and moved achievement unlock toasts to the upper-left. - -39.16.54: Added 真・たりない観察, 悠久の歴史, 五体満足, and 零体満足; disclosed 悠久の歴史 before unlock; reduced achievement overhead by skipping closed-dialog list rebuilds, caching category mappings, debouncing pending sync, and retaining periodic full recovery sync. - -39.16.55: Added 町のお医者さん and 割とふわふわ; changed ベビーブーム to 30 births per minute and 管理された楽園 to one uninterrupted happy in-game day from play day 6; repaired shared つつく targeting, damage, plushie fling, and hover overlay; corrected manual rotator/reciprocator push direction; tightened tool/limit typography; reduced periodic achievement scans; and changed server aggregate writes to compact v2 JSON with legacy-state migration. -39.16.56: Added 混沌ヲ希求スル者 and 潔癖症; made fight progress persistent; revised ミニマリスト, おくすり手帳全埋め, and 清掃業者; and made achievement-rate bars visible on unlocked cards. - -39.16.57: Compactly embeds unlocked achievements and persistent achievement progress in exported spell saves; spell loads merge achievements without erasing local progress and resync restored unlocks to the server. - -39.16.59: Replaced JSON-string achievement metadata in spell/save binaries with a sparse binary schema; achievement unlock masks are raw bits, progress is bit-packed, timestamps use minute deltas, and old v39.16.57 spells remain readable. -39.16.60: Added persistent sniper, megalopolis, and love-mochi fertility achievements; changed chaos progress to fight-mochi-influenced fights only; extended compact spell progress without migrating obsolete generic fight counts; omitted completed achievement counters from spell metadata; and tightened population-limit labels/layout. - -39.16.62: Expanded achievements from 54 to 59 with single-digit FPS, 24-hour continuous play, five toilet-sand placements, park-ground editing, and four ground changes per second; revised safety, observation, and empty-click conditions; moved the two observation achievements to the bottom of その他; and expanded binary achievement masks to eight bytes while retaining schemas 41–43. - -39.16.63: Fixed achievement progress typography and tab-switch observation continuity; added アリ観察 and 命のバトン; persisted sticky-bomb pass counts; aligned sauna/enemy-ant conditions; removed obsolete spell compatibility; current exports use schema 45 and achievement payload v4. - -## v39.16.64 -- Added 毎日たりない観察 and 抵抗器じゃない. -- Daily streak state is carried by achievement payload v5 and binary schema 46. -- Achievement aggregate JSON migrates compact v2/verbose input to compact v3 automatically under the API file lock. - -## v39.16.65 -- Re-audited the not-yet-deployed shared achievement server with generated randomized unlock data instead of a fixed production sample. -- Shared summaries are read-only; only POST session/unlock/sync/reset calls register or update players, and GET mutations are rejected. -- State writes now use a separate lock file plus atomic same-directory replacement, preserving the previous state across interrupted writes. -- Invalid or structurally unknown JSON returns `storage_corrupt` without overwriting the source file. -- `completionistEligible: false` now prevents `true_tarinai_observer` from being re-added by the same sync payload. -- The randomized server audit covers 32 v2/verbose migrations and 72 concurrent player syncs with exact semantic comparison. - -## v39.16.66 -- Added seesaw cooperative play and friendship growth. -- Added circuit-board editor with positioned input/output terminals and AND/OR/NOT gates. -- Added electrical control for fan, stove, dry ice, and duplicator. -- Added connectable-item and circuit-terminal highlights while wiring. -- Save snapshot/schema: 38/47. - -## v39.16.67 -- Circuit board editor now uses a grid canvas with direct gate placement and cursor-drawn wiring. -- Legacy circuit layouts are intentionally not converted. -- Colony state evaluates every two in-game hours; growing populations cannot be classified as Weakened. -- Seesaw action selection, fixed orientation, and placement preview were corrected. - -## v39.16.68 -- Seesaw leisure can start at a lower boredom threshold, and a waiting rider raises the second rider's action priority. -- Active paired play is shown as 「シーソーをしている。」 in selected Tarinai data. -- Seesaws render in the low/back item layer instead of covering Tarinai sprites. -- AND/OR gate input pins and gate outputs are snapped to the same 40px circuit-editor grid used by cursor wiring. - -## v39.16.69 -- Circuit-board internal wiring now uses straight grid segments with explicit branch junctions and unlimited fan-out per terminal. -- Removed OR and added a one-input/one-output rectifier; internal logic parts rotate in 90-degree steps. -- Circuit-board external terminal counts and positions are editable; the board footprint and default terminal spacing were expanded. -- Detector numeric conditions now use a dual-thumb minimum/maximum range plus direct numeric inputs. -- Seesaw riders render slightly above the seat surface. -- Save snapshot/schema: 39/48. Older saves are intentionally unsupported. - - -## v39.16.70 -- The default circuit-board grid is now 10x6, one quarter of the previous editor area, with a correspondingly smaller world footprint. -- Circuit-board width and height are editable; the board world size follows the grid dimensions. -- Input/output terminal count is limited by board height, and every external terminal can be dragged independently onto the left, right, top, or bottom edge. -- Branch junctions can be moved directly; all connected straight segments follow the junction. -- NOT and rectifier bodies are visually smaller while their pins remain on grid intersections. -- Existing external wires follow terminal positions after a board resize or terminal move. -- Seesaw action reasons now use play-specific wording instead of inheriting unrelated fulfillment reasons such as bed demand. -- Save snapshot/schema: 40/49. Older saves are intentionally unsupported. - - -## v39.16.71 -- Circuit-board external terminals are now placed directly with IN/OUT terminal tools; the +/- terminal-count controls were removed. -- Disconnected external terminals are dimmed in the circuit-board editor; connected terminals retain their signal colors and cannot be deleted until their world wire is removed. -- Placement previews no longer use the generic ellipse fallback: circle items use circles, obstacle/mechanical items use their collision footprints, and special items use dedicated shapes. -- Detector, wire, insulated wire, and circuit board moved from the Physics palette section to a new Electrical section. -- Clicking a detector dual-range track outside either thumb teleports the nearer thumb to the clicked value. -- Save snapshot/schema remains 40/49; the persisted circuit-board v4 structure is unchanged. - - -## v39.16.72 -- Circuit-board default grid is 10x10 and both dimensions can grow to 20x20; the world footprint scales proportionally in both axes. -- AND gate body height is two grid cells. Compact one-input parts can be placed one grid row from the top/bottom edges when their rotated pins remain in bounds. -- Placement previews prefer shared occupancy/collision footprints; the dedicated seesaw preview was removed and circuit boards use their rectangular board footprint. -- Internal combinational feedback loops are explicitly detected and forced OFF; a NOT self-loop is unstable and does not provide power. -- Save snapshot/schema remains 40/49; the persisted circuit-board v4 structure is unchanged. - - -## v39.16.73 -- Circuit-board editing shows placement ghosts for pending internal parts and terminals. -- Q/E rotates pending internal parts by 90 degrees before placement. -- The ON constant source is documented in the editor. -- Wire and insulated-wire palette silhouettes render correctly in the Electrical category. -- Save snapshot/schema remains 40/49. - - -## v39.16.76 -- Removed the circuit-board OFF constant source. -- Added the achievement 「情報化産業」 for transmitting an active signal directly from one circuit board output to another circuit board input through wire or insulated wire. -- Extended the 8-byte achievement mask to use its final bit, supporting all 64 current achievements. -- Save snapshot/schema remains 40/49. - - -## v39.16.78 -- Fixed 「あぁ^~ たまらねぇぜ」: burst zunchi no longer treat their spawn overlap with the owner as a collision. -- A burst zunchi now becomes eligible only after it has cleared the owner once; a later fatal return collision unlocks the achievement, including routes that reflect and accelerate on a bounce fence. -- Preserved the existing nonfatal, stopped, and player-held disqualification behavior. -- Fixed ミニマリスト placement-origin metadata so it remains saveable after 無計画都市 has already unlocked. -- Fixed サウナ水風呂 to measure 15 seconds from genuine entry into a hot state instead of refreshing the hot timestamp on every hot evaluation. -- Fixed 抵抗器じゃない so a Tarinai killed by the qualifying shock still counts before death clears its live state. -- Achievement reset now clears reset-scoped hidden per-Tarinai and per-item progress, including care counts, sauna state, held duration, fight-mochi metadata, sticky-bomb pass count, and quick-delete timestamps. -- Undo/Redo and valid ground changes now reset 監視カメラ observation progress as world interventions. -- Added route-level and secondary regression coverage for these achievement paths. Ambiguous achievement semantics identified by the renewed audit remain unchanged pending explicit specification. - -39.16.78: Applied confirmed achievement semantics: birth-status slave/king appearances count; dynasty achievements require direct parent-child qualifying lineage; Overprotective treatment counts only actual beneficial health recovery; Unplanned City counts deletion operations rather than removed objects; Surveillance Camera requires 3 uninterrupted game days and resets on gameplay interventions; wire-shock partial progress remains nonpersistent; Pest Control counts only player-caused ant deaths. - - -## v39.16.80 -- Optimized Tarinai social-neighbor scans with squared-distance filtering, nearest-N partial selection, pair-deduplicated symmetric work, cached personality profiles, and shared disease spread logic. -- Added personality-derived crowd comfort bounds. Overcrowded Tarinai flee toward less crowded space with the specified behavior text; undercrowded Tarinai become stressed and approach the nearest living Tarinai with the specified loneliness text. - - -## v39.16.85 -- Replaced Undo/Redo object snapshots and recursive patch history with the existing synchronous binary save codec payload. -- Exposed binary snapshot encode/decode helpers from TarinaiSaveCodec for internal history reuse without Base32768 text conversion or asynchronous compression. -- Replaced JSON.stringify-based duplicate detection with a compact dual 32-bit fingerprint over the encoded history bytes. -- Unified Undo and Redo stack movement through a shared history transition path while preserving synchronous behavior and the 48-entry limit. -- Added binary-history regression coverage for storage shape, duplicate suppression, Undo restoration, and Redo restoration. - - -## v39.16.85 -- Render stack optimization: static visible stacks are cached by static spatial generation and camera region, while dynamic stacks reuse previous-frame order before insertion sorting and are merged linearly. -- Link rendering now uses dedicated AABB spatial cells instead of per-frame full type-bucket fallback scans. -- Carried plushies render at owner-relative positions without mutating simulation coordinates during rendering. -- Fixed render culling radii are cached on eligible static entities. -- Render-layer sort keys are computed once per stack insertion. - - -## v39.16.85 -- Reduced fixed render cost by skipping the fallback full-screen gradient whenever the transformed field fully covers the viewport. -- Cached full-screen fallback gradients and rebuilt atmospheric full-screen lighting at 8 Hz instead of constructing multiple full-screen gradients every frame. -- Reused dynamic render-layer entries, sort maps, and previous-order ID arrays to reduce per-frame garbage collection as population grows. - - -## v39.16.86 -- Removed social crowd-retreat selection and the overcrowded colony-state distance scan. -- Removed the unconditional three-second full terrain-cache invalidation; cached terrain now refreshes only from real terrain changes, with splat fading invalidating local chunks. -- Throttled structure dependency safety sweeps, staggered item/ant compaction, and stopped timer-only item bucket rebuilds. -- Deferred periodic statistics UI refreshes and collapsed population statistics into a single pass. -- Ordinary item additions/removals no longer invalidate the full terrain cache unless cached terrain items actually changed. - -## v39.16.88 -- Large-save restore uses an adaptive non-damaging settling phase for dense loaded populations, preventing synthetic body-overlap and obstacle-correction impulses from cascading into impact deaths. -- Duplicator loading takes priority over direct feeding when a Tarinai overlaps the machine. -- Save schema 50 explicitly stores elapsed completed days; total simulation time is restored monotonically and seasons/climate derive from elapsed days. Schema 49 spells remain readable. - - -## v39.16.89 -- Moved the ずんちどれい and たりない王 population-chart toggles to immediately after 死亡数. -- Removed the 12-second periodic Tarinai runtime-cache full sweep that caused large-population performance regressions. -- Runtime relationship/cache cleanup is now scheduled only after accumulated deaths reach max(20, floor(living population * 15%)), then runs once during the next Tarinai compaction and resets its counter. - - -## v39.16.90 -- Added eight playstyle-survey achievements: 数こそ力, 少数精鋭, 踩屎感, 快適な寝床, 石に枕す, 季節を越えて, 推し, and 統計学者. -- 数こそ力 unlocks at 100 living Tarinai. 少数精鋭 requires 1-25 living Tarinai continuously for five game days and discloses its condition/progress before unlock. -- 統計学者 counts 30 statistics-tab or chart-series visibility button presses in persistent achievement state, so field resets do not clear its progress. -- Achievement spell payload v6 and binary save schema 51 expand the unlock mask from 64 to 72 achievements while retaining v5/schema 49-50 read compatibility. -- Updated the Item lifecycle pipeline regression to validate local bucket/spatial invalidation when passive serving-food decay actually changes its visual footprint. - - -## v39.16.94 -- Removed previous-order render Maps and custom insertion sorting; dynamic visible lists now use native Array.sort after culling. -- Removed the shared route cache while retaining actor-local route throttling. -- Disabled detailed performance counters in normal play; diagnostics remain available only in explicit debug/perf mode. -- Isolated obstacle-query cache invalidation to routing-obstacle generations instead of generic spatial movement. -- Replaced per-frame full Tarinai spatial-grid rebuilds with cell-crossing incremental updates. -- Added sustained hysteresis to automatic performance-profile transitions to prevent rapid quality oscillation. -- Death-reference cleanup now executes in bounded per-frame chunks after the existing adaptive death threshold. - -## v39.16.94 -- Fixed dense-population birth regression caused by incremental Tarinai spatial-grid bucket ordering interacting with an early 20-candidate contact cutoff. Contact interactions now consider the complete already-fetched local candidate set while retaining only the nearest bounded interaction list. -- Moved the "季節を越えて" achievement from the ecology category to "その他". -39.16.96: UI input/limits/zoom refinements, infection chance reduced to one-third, 75 achievements, grass spatial/hot-path optimization, summer flat temperature bonus removed. diff --git a/FILES.json b/FILES.json deleted file mode 100644 index 22c5608..0000000 --- a/FILES.json +++ /dev/null @@ -1,191 +0,0 @@ -{ - "purpose": "Token-efficient machine-readable routing for tarinai_. Use scripts/ai_inventory.py for exact current file expansion.", - "version": "39.16.98", - "entrypoints": { - "app": "index.html", - "runtime": "js/main.js", - "update_order": "js/system_order.js", - "manifest": "app_manifest.json", - "service_worker": "service-worker.js" - }, - "read_strategy": { - "default": [ - "README.md" - ], - "architecture": [ - "README.md", - "AI_MAP.md" - ], - "exact_inventory": [ - "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/ai_inventory.ps1 -All", - "python scripts/ai_inventory.py --all" - ], - "machine_routing": [ - "FILES.json" - ] - }, - "groups": [ - { - "id": "root", - "patterns": [ - ".gitignore", - ".htaccess", - "app_manifest.json", - "favicon.ico", - "index.html", - "README.md", - "AI_MAP.md", - "GAME_FEATURES.md", - "FILES.json", - "service-worker.js", - "achievement_api.php", - ".achievement_data/.htaccess" - ], - "meaning": "Repo/app shell metadata, server/static cache config, docs, manifest, entrypoint." - }, - { - "id": "css", - "patterns": [ - "css/*.css" - ], - "meaning": "Base, layout, panel, component, and mobile responsive styling." - }, - { - "id": "scripts", - "patterns": [ - "scripts/*.js", - "scripts/*.py", - "scripts/*.ps1" - ], - "meaning": "Generators, regression checks, version-specific audits, and token-aware AI inventory tooling." - }, - { - "id": "core", - "patterns": [ - "js/version.js", - "js/event_bus.js", - "js/domain_ids.js", - "js/registry_base.js", - "js/disease_registry.js", - "js/sound_pack.js", - "js/deterministic_helpers.js", - "js/item_tool_metadata.js", - "js/item_tool_definitions.js", - "js/item_visual_definitions.js", - "js/item_food_definitions.js", - "js/item_effect_definitions.js", - "js/item_registry.js", - "js/data.js", - "js/ground_types.js", - "js/health.js", - "js/input_mode_manager.js", - "js/main.js", - "js/math.js", - "js/perf_profiler.js", - "js/debug_tools.js", - "js/update_step_pipeline_runner.js", - "js/burn_motion_util.js" - ], - "meaning": "Bootstrap, shared constants/helpers, registries, config, profiling/debug." - }, - { - "id": "assets_runtime", - "patterns": [ - "js/assets.js", - "js/audio.js", - "js/render.js", - "js/tarinai_render.js", - "js/item_render_runtime.js" - ], - "meaning": "Image/audio loading and canvas rendering." - }, - { - "id": "simulation", - "patterns": [ - "js/sim_core.js", - "js/simulation*.js", - "js/system_order.js" - ], - "meaning": "Simulation primitives, concrete systems, phase ordering." - }, - { - "id": "world", - "patterns": [ - "js/world*.js", - "js/weather_system.js" - ], - "meaning": "World state/view/update/tools/environment/combat/family/social/ants." - }, - { - "id": "physics", - "patterns": [ - "js/physics*.js", - "js/mechanical_system.js", - "js/constraint_system.js", - "js/collision_footprint_system.js" - ], - "meaning": "Geometry, collisions, constraints, mechanical item behavior." - }, - { - "id": "items", - "patterns": [ - "js/item*.js", - "js/items.js", - "js/structures.js", - "js/structure_lifecycle.js", - "js/circuit_board_system.js" - ], - "meaning": "Item/structure registry, lifecycle, dynamic behavior, rendering." - }, - { - "id": "tarinai", - "patterns": [ - "js/tarinai*.js", - "js/ants.js", - "js/seesaw_system.js" - ], - "meaning": "Creature state/actions/needs/social life/item effects/disease/rendering plus ant actor model." - }, - { - "id": "save", - "patterns": [ - "js/save*.js", - "js/snapshot_system.js", - "js/restore_coordinator.js", - "js/history_system.js" - ], - "meaning": "Snapshot schema/codec/storage/restore/history." - }, - { - "id": "ui", - "patterns": [ - "js/ui*.js", - "js/text_catalog.js", - "js/command_dispatcher.js", - "js/family_graph.js", - "js/achievements.js" - ], - "meaning": "DOM UI, input, tools, selected panel, logs, charts, family tree, text labels, command routing." - }, - { - "id": "assets", - "patterns": [ - "assets/sprites/tarinai_*.webp", - "assets/ui/tool_*", - "assets/ui/favicon*", - "assets/ui/apple-touch-icon.png", - "assets/ui/ecology_*.webp", - "assets/objects/*", - "assets/sounds/*" - ], - "meaning": "Creature sprites, UI/tool icons, field object images, voice/SFX samples." - } - ], - "conventions": { - "*_pipeline.js": "ordered runner/facade", - "*_step_*.js": "pipeline stage wrapper", - "*_system.js": "domain service or compatibility facade", - "*_runtime.js": "stable runtime-facing facade", - "*_registry.js": "definition lookup/normalization" - } -} diff --git a/GAME_FEATURES.md b/GAME_FEATURES.md deleted file mode 100644 index 89ef423..0000000 --- a/GAME_FEATURES.md +++ /dev/null @@ -1,100 +0,0 @@ -# tarinai_ Game Features - -`tarinai_` is an observation sandbox about small creatures called tarinai. The player shapes a field with food, medicine, furniture, hazards, machines, weather, and ground choices, then watches how the colony reacts. The game is about cause and effect: small changes in the environment can alter movement, stress, disease, relationships, reproduction, accidents, cleanup, and survival. - -## Core Play - -The player starts by choosing a field and ground, then places objects or uses direct tools on the colony. Tarinai continue acting on their own while the player observes, edits the environment, removes problems, or creates new ones. The colony panel, event log, selected-tarinai data, and family tree help explain what is happening without taking control away from the simulation. - -The game supports quiet observation and chaotic experiments. A player can build a comfortable habitat with beds, food, grass, and cleaning tools, or create a dangerous machine field with rotators, fences, stones, pins, explosions, ants, and poison. - -## Tarinai - -Tarinai are autonomous creatures with HP, needs, stress, personality, age, family links, diseases, item effects, and behavior states. They choose actions from their current condition and surroundings instead of following a fixed script. Hunger can make them seek grass or food, sleepiness can make them find a bed, fear can make them flee, and social state can make them follow, fight, avoid, or approach another tarinai. - -Each tarinai has individual tendencies. Aggressive tarinai fight more easily, social tarinai seek others more often, nervous tarinai react strongly to danger, and inherited traits can make children resemble their parents. Selecting a tarinai shows health, needs, stress, effects, relations, inventory, family information, and the reason for its current behavior. - -Tarinai can be damaged by hazards, pushed by physics objects, carried by ants, attached to links, blocked by fences, affected by medicine, frightened by accidents, comforted by habitat items, or preserved when outside the active field. Some objects can become emotionally important, so losing them may cause panic. - -## Food And Consumables - -Grass is both food and habitat material. Tarinai can eat it, feel comfort near it, gather it for simple beds, and interact with it through ground and weather systems. Water can be drunk, can appear from rain, and can be generated or copied by tools. - -Sweet food helps satisfy hunger and can support recovery in some cases. Love mochi makes reproduction behavior more likely for a while, while fight mochi pushes the colony toward conflict. Zunda juice clears item effects, making it useful after medicine or special consumables have changed a tarinai too much. - -Medicine changes the simulation more aggressively than normal food. Sleep drugs push tarinai toward sleep or sleep disease, laxatives create repeated zunchi and reduce food benefit, protein makes a stronger permanent mode with lower disease risk, and niteropu makes a weaker permanent mode with higher disease risk. Ammo creates temporary speed and impact danger. Mystery drugs choose from eligible effects unpredictably. Mercury changes lifespan, while giant and dwarf drugs reshape size, movement, power, and ongoing damage risk. - -## Habitat And Cleanup - -Zunchi is waste, but it is also part of the ecology. It affects hygiene and disease risk and can fertilize grass. Beds and nest boxes give tarinai safer or better sleep options, reduce stress around resting areas, and help recovery. Balls give tarinai something to play with and can also become part of physics experiments. - -Robot cleaners are mobile cleanup items. They scan for selected target types, pursue matching waste or corpses, and remove them on contact. The water hose gives the player direct cleanup control by washing dirt, zunchi, corpses, stains, and similar field problems. Signboards are editable objects that can be inspected after placement, useful for labeling areas or experiments. - -## Physics And Machines - -Physics items turn the field into a mechanical sandbox. Ropes connect two targets with a flexible link that can go slack but should not stretch freely. Rods create a rigid connection. Springs connect targets with elastic motion, allowing linked objects to pull back and oscillate. - -Fences block movement and can be rotated for layout control. Gates can be opened or closed after placement. One-way fences allow passage from one direction while blocking the opposite direction. Bounce fences launch colliding targets more strongly than normal fences, which makes them useful for traps or kinetic experiments. - -Rotators are editable mechanical shapes that spin and push nearby targets. Their shape and speed can create conveyors, crushers, traps, or chaotic collision fields. Reciprocators move back and forth along a line, so they can shove objects repeatedly. Poison blocks are custom hazard shapes that damage on contact. - -## Electrical And Automation - -Detectors, wires, insulated wires, and circuit boards are grouped in the Electrical tool category. Normal energized wire can hurt living targets on contact, while insulated wire is safer for incidental contact. Detectors can sense target ranges or time windows and send signals; clicking either dual-range track moves the nearer thumb directly to the clicked value. Circuit-board external input and output terminals are placed directly on the board edge, can be moved around all four sides, and appear dim in the editor until a world wire is actually connected. - -## Danger Tools - -Danger tools create immediate or ongoing pressure. Stones are heavy objects that become dangerous when dropped, thrown, or moved by machines. Genkotsu creates a large impact on the ground. Firecrackers cause explosions, with flame variants adding fire while respecting active-fire limits. - -Pushpins can roll, lodge in tarinai, cause panic, and deal continuous damage. Oshibyo blocks zunchi while lodged and releases stored zunchi when removed. Shooting is a direct attack tool that can hit tarinai, ants, items, pins, balloons, or placed objects depending on the target under the aim point. - -Ant nests introduce an enemy system. Ants search for tarinai, carry captured targets back to the nest, and can be shot or killed. Worker ants and queen ants have separate HP values, and ant counts are shown through colony statistics. - -## Operation Tools - -The observe tool selects tarinai or compatible objects and opens their data. The add tool introduces new tarinai. Poke applies a small interaction or push, while pinch lets the player drag tarinai and some objects. Copy duplicates placed items with their settings so setups can be repeated quickly. The operation palette also provides a dedicated snap control shared by placement and pinch movement; it cycles through Free, 20px, 40px, and 60px. - -Undo and redo reverse or reapply placement and edit actions. Delete removes a specific object or stain, while area delete removes many nearby targets at once. These tools let the player repair a field after experiments without resetting the whole colony. - -## Grounds And Environment - -Fields define the playable space and boundary style. Grounds change the character of the colony: sand, dirt, concrete, blanket, foot massage, ice, and laboratory-style surfaces can affect movement, stress, comfort, and grass behavior. Ground choice matters because tarinai react not only to objects, but also to the surface they live on. - -Weather changes the field over time. Rain can create water and affect comfort, shade can protect from weather or sun, and temperature changes how tarinai experience the environment. Grass, zunchi, splats, corpses, ant corpses, rain drops, and stains all feed into hygiene, disease, cleanup, rendering, and observation. - -## Colony Statistics - -The colony panel summarizes population, sick tarinai, juveniles, elders, deaths, mood, temperature, population limits, and object limits. Graph tabs show population, needs, and environment. Total ants are included in the environment statistics so active ant pressure can be read alongside other field signals. - -The event panel records important simulation events such as birth, death, fights, accidents, weather, grass changes, and relation changes. The family tree shows parent-child structure, generations, inherited stats, personality tags, and family links. - -## Save, Display, And Performance - -Manual save and restore use browser storage. Reset returns to field selection and starts a new state. Service worker caching can keep the static app shell available after the first successful load when the browser supports it. - -Display settings control effects, shadows, drawing detail, and quality choices for crowded scenes. Crowded fields are an intended part of the sandbox, so the game uses spatial lookup, scheduling, cached drawing, and incremental maintenance systems to keep large colonies and many objects playable. - - -## Achievement system (v39.16.78) -- Sixty-four achievements track reproduction, natural status changes, generation runs, rapid population events, special deaths, colony conditions, individual care, autonomous ecology, history usage, cleanup, rapid deletion, temperature transitions, weather shelter, medicine-category completion, combat reversals, circuit-board signaling, and ant-related play styles. -- Locked rows reveal only the configured condition allowlist; all others show `???`. There are no achievement tooltips. 大いなる母, めっちゃたりない観察, 敵の敵は味方, 混沌ヲ希求スル者, and 豊穣ヲ希求スル者 include local progress percentages, and unlocked achievements are sorted first inside each category. -- Each achievement row behaves as a horizontal bar chart. Its background fill visualizes the optional global completion percentage from 0–100%, and the global achiever count is displayed beside it. -- `物でいっぱい` requires 100 cumulative player placements across field resets. `害虫駆除` requires 100 cumulative ant kills across field resets. -- `餌やりじいさん` requires 33 direct feedings in one field; resetting the field resets this progress. -- `機械化産業` replaces the former detector-automation and link-craftsman achievements and unlocks only when both requirements are met. -- v39.16.56 adds 混沌ヲ希求スル者 and 潔癖症, raises 清掃業者 to 200, starts ミニマリスト from day 6, excludes chain/crown from おくすり手帳全埋め, and keeps shared-rate bars visible after unlock. -- v39.16.54 added 真・たりない観察, 悠久の歴史, 五体満足, and 零体満足. v39.16.55 added 町のお医者さん for 50 effective first-aid recoveries and 割とふわふわ for flinging a plushie with つつく. ベビーブーム now requires 30 births in one minute; 管理された楽園 starts tracking from play day 6 and requires one uninterrupted happy in-game day. -- Local unlocks and persistent totals live in browser storage. Field-scoped direct-feeding, cleaner, self-sufficiency, enemy-ant, generation, observation, safety, and per-entity/item progress follow current-format saves where applicable. Nest-box and pipe occupants block rain/weather effects and count as sheltered for 雨宿り完了. -- Achievement evaluation is primarily event-driven; periodic world scans skip completed or irrelevant conditions. The server writes compact v3 achievement aggregate JSON while migrating older aggregate formats on read. -- v39.16.78 fixes achievement edge paths found by a renewed 64-condition audit: Minimalist placement metadata survives unrelated unlocks, Sauna/Cold-Plunge uses true hot-entry timing, lethal qualifying wire shocks count before death cleanup, reset clears hidden reset-scoped progress, and Undo/Redo/ground changes interrupt passive observation. Ambiguous semantics are intentionally unchanged pending specification. - -### Achievement spell persistence (v39.16.78) -- Exported spells compactly include non-debug achievement unlocks, unlock times, and persistent progress. -- Loading a spell merges achievements and keeps the greater progress instead of erasing local achievement data. -- Restored unlocks are queued for the existing server recovery synchronization. Save slots remain world-only. - -- Spell achievement metadata uses a sparse binary encoding: raw unlock bits, bit-packed persistent progress, minute-delta unlock timestamps, and sparse per-entity state. Binary save schema 51 is current; schemas 49 and 50 remain readable. Achievement payload v6 stores 72 unlock bits and statistician progress, while legacy payload v5 remains importable. -- v39.16.60: Added 狙撃手, メガロポリス, and 豊穣ヲ希求スル者; restricted 混沌ヲ希求スル者 to fight-mochi-influenced fights; extended compact achievement spell progress and omitted counters for already-unlocked achievements. -- v39.16.62: Added five achievements for low FPS, uninterrupted 24-hour play, toilet-sand placement, park-ground editing, and rapid ground changes. 寿命 deaths are excluded from 安全第一 failures, empty-field clicks replace pause-button clicks for 何やってるの?, and the two long observation achievements are last in その他. - -- v39.16.63: Added アリ観察 and 命のバトン; stabilized progress-row typography; continuous-play observation no longer resets on tab changes; corrected sauna wording and enemy-ant streak reset behavior; obsolete spell formats are rejected. diff --git a/README.md b/README.md index ea6631c..8b20754 100644 --- a/README.md +++ b/README.md @@ -1,112 +1,60 @@ -# tarinai_ +# たりない観察 v39.18.6 -AI-first entrypoint for a static browser simulation/game. Keep this file small; read deeper docs only when needed. +## 実績システム -## Read Strategy +実績定義は `js/achievement_catalog.js` を唯一のカタログとして管理します。表示名、説明、カテゴリ、未解除時の公開設定、同期可能な進捗条件、累積上限は、クライアントと `achievement_api.php` が同じカタログから読み取ります。 -- Start here for architecture, script order constraints, and where to look next. -- For game mechanics, UI, items, and tarinai behavior, read `GAME_FEATURES.md`. -- For subsystem work, read `AI_MAP.md` plus only the matching files. -- For exact file inventory, run `powershell -NoProfile -ExecutionPolicy Bypass -File scripts/ai_inventory.ps1 -All` or narrow it: `powershell -NoProfile -ExecutionPolicy Bypass -File scripts/ai_inventory.ps1 ui`. Python equivalent: `python scripts/ai_inventory.py --all`. -- For machine-readable routing, read `FILES.json`. -- Avoid loading all assets into context; asset filenames are mostly self-describing and grouped by glob. +累積進捗の正規データは端末・タブ別の増加台帳です。表示用 `progress` に同じ累積値を重複保存しません。旧形式の重複カウンターと `synced` 一覧は読込時だけ移行し、現行形式では保存しません。 -## Runtime Shape +「敵の敵は味方」は実績画面の「生態」カテゴリに掲載されます。 -- v39.16.37 changes: biological and environmental conditions are unified into the detector; the standalone sensor and relay are removed; temperature and limits are folded; ecology, sound, display settings, and credits are in the header menu; reset remains outside in red; tarinai-data navigation preserves the active tool; mobile tool descriptions appear at the top for five seconds. Snap mode remains Free/20px/40px/60px, top-edge placement is fixed, and preset descriptions end with punctuation. -- v39.16.38 changes: detector numeric controls use value-labelled sliders like the time control; colony temperature and limits share one Colony settings fold; display settings use an inline menu matching sound settings; HP/stress meter colors are fixed; the snap control follows Clear with a faint grid icon; area-delete has a new icon; the Ant chart series is renamed and hidden initially. -- v39.16.55 changes: expanded the achievement set to 49 with 町のお医者さん and 割とふわふわ; changed ベビーブーム to 30 births per minute and 管理された楽園 to one happy in-game day from play day 6; restored shared poke targeting/highlights and plushie fling; corrected manual rotator/reciprocator push direction; tightened tool/limit UI; reduced periodic achievement scans; and introduced compact achievement aggregate storage. -- v39.16.52 changes: reorganized achievements into collapsible categories, removed achievement tooltips, and moved confirmation flows into the game UI. Previous v39.16.51 changes: expanded the achievement set to 43 with sixteen play-style and special-action conditions; added persistent Undo/Redo and quick-delete counters, field-local cleaner/automation-free ecology progress, individual care/temperature/fight tracking, complete medicine-category collection, protected rain shelter in nest boxes and pipes, and stricter ant-kill attribution. -- v39.16.49 changes: added additive full-state synchronization so shared achievement aggregates can be rebuilt as players return after server data loss. -- v39.16.48 changes: corrected the zunchi-slave threshold text to 30%; repaired wire placement counting, danger-kill attribution, partial legacy link migration, UUID validation, and debug-only achievement isolation. -- v39.16.47 changes: Two achievements are added (大いなる母 and 喧嘩両成敗); five names and five revealed descriptions are revised; `?debug=1` exposes an all-achievements button. -- v39.16.46 changes: achievement names and presentation are revised; conditions are revealed only after unlock; shared completion rates render as horizontal background bars; automation and link coverage merge into 機械化産業; placement and ant-kill targets are persistent totals of 100; direct feeding resets with the field. -- v39.16.45 changes: seven play-style achievements add passive observation, cumulative placement, detector automation, link-tool coverage, safe large-colony operation, ant population, and ant elimination measurements. World-scoped timers and placement counts persist in current-format saves. -- No bundler; `index.html` loads ordered global-IIFE scripts with `?v=39.16.78`. -- v39.16.31 changes: all in-world tooltips use the closer offset; Hair Trigger adds a central bounce-fence ball enclosure with Tarinai and pet-food duplicators outside; physics tools use distinct icons. -- v39.16.29 changes: parasol placement preview now uses the exact shade center and footprint; toilet sand absorbs rain-created water drops. Happy adds parasols, water balloons, and toilet sand beneath each duplicator; Athletic uses fence-safe single-bar rotators and water balloons; War adds rotating fans. -- v39.16.19 changes: food and medicine can be given directly by placement or pinched drop, with a dedicated overlay, food heart bursts, and stronger personality effects; unused collision reasons and duplicate constraint projection dirty checks were removed. -- Mutable runtime lives on `window`; primary entities are `World`, `Tarinai`, items, structures, ants, family graph, weather, and save snapshots. -- Update loop: `main.js` creates the world/UI loop; `World.update` delegates to `TarinaiSystemOrder.update`; `system_order.js` runs named phases. -- UI loop: pointer/tool/UI intents go through `command_dispatcher.js`; canvas drawing is in render modules; side panels are `ui_*.js`. -- Generated/static app shell: `app_manifest.json`, `service-worker.js`, `FILES.json`, and `js/version.js` must stay version-aligned. +## ローカル保存 -## File Routing +実績状態とサーバー資格情報は、通常保存、予備保存、同一タブ保存、IndexedDBへ世代付きで保存します。起動時は同じ世代の状態を追加方向に統合し、明示的な実績リセット時だけ世代を進めます。 -- `index.html`: DOM shell, CSS/JS load order, panels/dialogs/canvas. -- `css/*.css`: base/layout/panel/components/mobile styling. -- `js/domain_ids.js`, `js/item_type_catalog.js`, `js/data.js`, `js/ground_types.js`: stable domain ids, current item-type save catalog, core config, field/ground definitions. -- `js/world*.js`: world state, view, update phases, tools, placement, combat, environment, family/social, ants. -- `js/tarinai*.js`: creature state, needs, actions, behavior, social life, item effects, update pipeline, rendering. -- `js/item*.js`, `js/structures*.js`: item registry/runtime/lifecycle/dynamic behavior/rendering plus structures. -- `js/simulation*.js`, `js/system_order.js`, `js/sim_core.js`: concrete update systems and phase ordering. -- `js/ui*.js`, `js/text_catalog.js`, `js/command_dispatcher.js`: DOM UI, input, selected panel, logs, charts, family tree, tools, labels. -- `js/save*.js`, `js/snapshot_system.js`, `js/restore_coordinator.js`, `js/history_system.js`: persistence and history. -- `js/physics*.js`, `js/mechanical_system.js`, `js/constraint_system.js`, `js/collision_footprint_system.js`: geometry, mechanics, constraints, collisions. -- `assets/sprites/tarinai_*.webp`: creature state sprites. -- `assets/ui/tool_*`: tool palette icons; other `assets/ui/*` are app/help icons. -- `assets/objects/*`: field object images. -- `assets/sounds/*`: voice and SFX samples. -- `scripts/*`: generators, regression checks, and AI inventory. +v39.18.6は、v39.18.0以前の実績保存、旧ワールド実績メタデータ、実績スペルv9・v10、旧バイナリセーブを読み込めます。旧データは現行形式へ正規化され、新規保存には廃止済みフィールドを書きません。 -## Conventions +## サーバー同期 -- `*_pipeline` = ordered runner/facade. -- `*_step_*` = pipeline stage wrapper. -- `*_system` = domain service or compatibility facade. -- `*_runtime` = stable runtime-facing facade. -- `*_registry` = definition lookup/normalization. -- Many split files preserve regression contracts; do not collapse them casually. +同期プロトコルはv5です。 -## Checks +- 解除状態と途中進捗を追加型で統合 +- 同じ端末台帳の再送を重複加算しない +- リセット要求の再送を無害化 +- 古いサーバーバックアップから新しいローカル世代を復旧 +- 古い端末からリセット前の状態を復活させない +- プレイヤーIDと所有秘密鍵を耐久保存から復旧 -- Syntax: `node --check js/*.js` -- Regression: `python scripts/regression_check.py` -- Inventory sanity: `powershell -NoProfile -ExecutionPolicy Bypass -File scripts/ai_inventory.ps1 -All` +共有達成率は、サーバーがゲームシミュレーションを再実行した検証値ではなく、クライアント端末の報告値です。UIでは共有値を「達成率」「達成人数」と表示します。 + +## 旧サーバーデータの自動移行 + +データディレクトリ、またはアプリ直下の `.achievement_data` に旧コンパクト形式の `state.json`(スキーマ4)がある場合、最初のAPI要求時に現行形式へ自動移行します。環境変数で新保存先を指定した場合や、v39.18.1が空の現行保存先を先に作成済みの場合も検出します。 + +- 原本は `legacy-backup/` へSHA-256付きで保存 +- 旧プレイヤーIDから決定的なUUIDを生成 +- プレイヤー数、解除実績、解除時刻、実績別集計を移行 +- 旧データに存在しない途中進捗は0から開始 +- `legacy-v4-migration.json` に完了件数を記録 +- 中断時は次のAPI要求で冪等に再開 +- 切替中にコピー元の旧 `state.json` が更新された場合も、内容ハッシュを再確認して追加方向で再取込 +- ファイルサイズとmtimeが同じ更新もSHA-256比較で検出 + +旧ブラウザーに22文字のプレイヤーIDが残っている場合、クライアントはUUIDへ上書きする前に専用領域へ退避し、初回セッションで一度だけ新しい所有秘密鍵へ引き継ぎます。引継ぎ済みの旧IDを別の秘密鍵で再取得することはできません。 + +旧版から直接v39.18.6へ更新したブラウザーは自動引継ぎできます。v39.18.1を既に起動して旧22文字IDがブラウザーから失われている場合、サーバーデータだけから端末との本人対応を再構成することはできません。解除履歴と共有集計自体は正常に移行されます。 + +## 実績APIの保存先 + +本番環境では、PHP実行ユーザーが書き込める非公開ディレクトリを用意し、環境変数 `TARINAI_ACHIEVEMENT_DATA_DIR` に絶対パスを設定してください。未設定時は、HTTP公開ディレクトリ外の安定したユーザーデータ領域を使用します。 -### v39.16.16 -Colony birth/death chart lines, reverse rotators, champion-trait inheritance, reduced champion-pair mating, and directional one-way-fence routing. +## PHP組み込みサーバーでの起動 +PHP組み込みサーバーは `.htaccess` を解釈しません。旧 `.achievement_data/state.json` には引継ぎ用IDが含まれるため、必ず同梱のルーターを使用してください。 -- v39.16.39 changes: restored the compact sticky operation palette, added exact-match right-panel search, reorganized colony settings, and refreshed tool icons. +```sh +./start_server.sh 8000 +``` - -## Achievement system (v39.16.78) -- Sixty-four local achievements cover biological events, special deaths, colony conditions, individual care, passive ecology, Undo/Redo behavior, rapid deletion, cleaner use, temperature transitions, medicine-category completion, weather shelter, combat reversals, circuit-board signaling, and ant-related play styles. -- Locked entries show the configured pre-unlock disclosure directly in the row; all other locked entries show `???`. 大いなる母, めっちゃたりない観察, and 敵の敵は味方 show local progress percentages. Unlocked entries appear first within each category. -- Each entry is a horizontal completion-rate bar whose background fill reflects the optional shared global unlock percentage; the shared achiever count appears beside the percentage. -- v39.16.64 adds 毎日たりない観察(7 calendar days) and 抵抗器じゃない(7 distinct tarinai shocked by one energized bare wire). v39.16.54 added 真・たりない観察, 悠久の歴史, 五体満足, and 零体満足. v39.16.55 added 町のお医者さん for 50 effective first-aid recoveries and 割とふわふわ for flinging a plushie with つつく; both are event-driven and 町のお医者さん is disclosed before unlock. v39.16.56 added two achievements, persistent fight progress, stricter robot-only evaluation, revised thresholds, and unlocked-card rate bars. v39.16.60 adds three achievements and restricts the chaos counter to fight-mochi-influenced fights. -- Persistent totals include 物でいっぱい, 害虫駆除, 大いなる母(3333体), 無計画都市, やっぱなし, and やっぱあり. Field-local progress includes 餌やりじいさん, 清掃業者, 自給自足, and 敵の敵は味方; applicable field-local metadata follows current-format saves. -- `自動化の第一歩` and `リンク職人` are retired and replaced by `機械化産業`, which requires both detector-driven activation and rope/rod/spring coverage. Existing players with both retired achievements migrate automatically. -- Optional same-origin PHP API aggregates anonymous player counts and global unlock percentages. Raw aggregate data is stored under `.achievement_data/state.json` in compact v3 positional arrays. Compact v2 and the prior verbose object are accepted only as migration inputs and are automatically rewritten under a separate server lock with atomic file replacement on the next API read. UUIDs are binary/base64url encoded, achievement IDs are indexed, timestamps are delta-coded, and repeated game versions use a dictionary. -- On startup, shared-stat refresh, achievement-screen opening, and every five minutes, the client sends its complete non-debug unlock set with original local timestamps. Ordinary unlock bursts send only unsynchronized records after a short debounce. The server adds only missing records, so a lost `state.json` is rebuilt incrementally as players return without overwriting surviving records. - -### Shared achievement percentage deployment -- Upload `achievement_api.php` and the hidden `.achievement_data` directory with the game. -- PHP must be enabled, and `.achievement_data` must be writable by the PHP process. -- On a static-only host, local unlocks still work; the global percentage is shown as unavailable. -- Set `window.TARINAI_ACHIEVEMENT_API` before `achievements.js` to use a different same-origin endpoint. -- The current release tracks sixty-four achievement IDs, supports per-player reset, and accepts additive bulk synchronization for automatic recovery after aggregate-data loss. A separate backup remains necessary to recover players who never return. -- `python3 scripts/achievement_server_state_audit.py` creates deterministic randomized achievement histories at runtime; it does not require or modify a production `state.json`. -- v39.16.60 changes: achievement metadata in spells is now encoded as sparse binary data instead of embedded JSON; unlock masks, progress, timestamps, per-entity counters, and placement metadata are compactly packed and spell data is accepted only from the current format. -- v39.16.60: Added 狙撃手, メガロポリス, and 豊穣ヲ希求スル者; restricted 混沌ヲ希求スル者 to fight-mochi-influenced fights; extended compact achievement spell progress and omitted counters for already-unlocked achievements. -- v39.16.62: Added スペックがたりない, 寝ろ, 砂場, そこ公共空間だよ?, and 破格の工事費用; 寿命 deaths no longer reset 安全第一; 何やってるの? now uses empty-field clicks; and save schema 44 expands the achievement mask while decoding schemas 41–43. - -- v39.16.63: Fixed achievement progress text weight and continuous-play tab switching; added アリ観察 and 命のバトン; corrected サウナ水風呂 and 敵の敵は味方 condition mismatches; save/spell data accepts only schema 45 and achievement payload v4. -- v39.16.64: Added 毎日たりない観察 and 抵抗器じゃない; introduced calendar-day streak persistence; and migrated server aggregate JSON to compact v3 positional data automatically on read. -- v39.16.65: Hardened pre-deployment server migration with read-only summaries, POST-only mutations, corruption-safe decoding, atomic writes under a separate lock, completionist eligibility filtering, and seeded randomized/concurrent migration audits. - -- v39.16.66: Added two-user seesaw play, an editable AND/OR/NOT circuit board with positioned terminals, signal control for fan/stove/dry ice/duplicator, and wire-target highlighting. - -- v39.16.67: Replaced the circuit-board dropdown editor with direct grid placement and cursor-drawn wiring; changed colony-state evaluation to every two in-game hours and excluded growing populations from Weakened; fixed seesaw action selection, fixed its orientation, and matched the placement overlay to its shape. -- v39.16.69: Reworked circuit-board wiring into straight grid segments with branches and multi-connect terminals; removed OR and added a rectifier; made internal parts rotatable and external terminal count/positions editable; expanded board terminal spacing; changed detector numeric conditions to min/max dual sliders with number inputs; and raised seesaw riders slightly above the seats. -- v39.16.68: Fixed seesaw participation so idle/bored Tarinai can initiate play and a waiting rider strongly recruits a partner; selected data reports active play as 「シーソーをしている。」; moved seesaws behind sprite layers; and aligned all two-input circuit gate pins to the 40px wiring grid. -- v39.16.70: Reduced the default circuit-board footprint to one quarter of the previous area; made grid width/height editable; made external terminals movable on all four edges with a height-dependent count limit; made branch junctions movable; reduced NOT/rectifier body sizes; and corrected seesaw action-reason text. - -- v39.16.71: Replaced circuit-board terminal +/- controls with direct IN/OUT terminal placement and erasing, dimmed terminals without external world wires, removed generic elliptical placement previews, added an Electrical tool category for detector/wires/circuit board, and made detector range-track clicks move the nearest thumb. - -- v39.16.72: Circuit boards now default to 10x10 with a 20x20 maximum, AND uses a two-cell height, compact gates can sit closer to top/bottom edges, placement previews follow occupancy footprints more directly, and unstable internal logic loops are explicitly forced OFF. -- v39.16.73: Circuit-board editing now shows placement ghosts for internal parts and terminals, Q/E rotates the pending internal part by 90 degrees, ON constant sources are explained in the editor, and wire/insulated-wire palette silhouettes render correctly after the Electrical category move. -- v39.16.78: Fixed 「あぁ^~ たまらねぇぜ」 so burst zunchi ignore their spawn overlap with the owner, arm only after clearing the owner once, and unlock on a later fatal return collision including bounce-fence reflections. The renewed achievement audit also fixes ミニマリスト save metadata, サウナ水風呂 hot-entry timing, lethal wire-shock counting, reset-scoped hidden progress cleanup, and 監視カメラ intervention gaps for Undo/Redo and ground changes. -- v39.16.76: Removed the circuit-board OFF constant part and added the 「情報化産業」 achievement for carrying an active signal directly from one circuit board to another over wire or insulated wire. +Windowsでは `start_server.bat 8000` を使用します。本番環境では引き続き `TARINAI_ACHIEVEMENT_DATA_DIR` をHTTP公開ディレクトリ外へ設定してください。 diff --git a/achievement_api.php b/achievement_api.php index d439797..22fbb63 100644 --- a/achievement_api.php +++ b/achievement_api.php @@ -4,89 +4,63 @@ declare(strict_types=1); header('Content-Type: application/json; charset=utf-8'); header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0'); header('X-Content-Type-Options: nosniff'); +header('Referrer-Policy: no-referrer'); +header('X-Frame-Options: DENY'); + +function load_achievement_catalog(): array { + $path = __DIR__ . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . 'achievement_catalog.js'; + $raw = @file_get_contents($path); + if (!is_string($raw)) throw new RuntimeException('achievement_catalog_unavailable'); + $prefix = 'window.TARINAI_ACHIEVEMENT_CATALOG = '; + $trimmed = trim($raw); + if (!str_starts_with($trimmed, $prefix) || !str_ends_with($trimmed, ';')) { + throw new RuntimeException('achievement_catalog_invalid'); + } + $json = substr($trimmed, strlen($prefix), -1); + try { $catalog = json_decode($json, true, 512, JSON_THROW_ON_ERROR); } + catch (JsonException) { throw new RuntimeException('achievement_catalog_invalid'); } + if (!is_array($catalog) || !is_array($catalog['definitions'] ?? null)) { + throw new RuntimeException('achievement_catalog_invalid'); + } + return $catalog; +} + +$achievementCatalog = load_achievement_catalog(); +$achievementDefinitions = []; +$achievementIds = []; +$progressRules = []; +foreach ($achievementCatalog['definitions'] as $definition) { + if (!is_array($definition)) continue; + $id = (string)($definition['id'] ?? ''); + if ($id === '' || isset($achievementDefinitions[$id])) throw new RuntimeException('achievement_catalog_invalid'); + $achievementDefinitions[$id] = $definition; + $achievementIds[] = $id; + if (is_array($definition['progress'] ?? null)) $progressRules[$id] = $definition['progress']; +} +define('ACHIEVEMENT_IDS', $achievementIds); +define('ACHIEVEMENT_DEFINITIONS', $achievementDefinitions); +define('PROGRESS_RULES', $progressRules); +define('COMPLETIONIST_ID', (string)($achievementCatalog['completionistId'] ?? 'true_tarinai_observer')); +define('CATALOG_REVISION', (string)($achievementCatalog['revision'] ?? 'unknown')); +define('ADDITIVE_PROGRESS_CAPS', is_array($achievementCatalog['additiveProgressCaps'] ?? null) ? $achievementCatalog['additiveProgressCaps'] : []); +define('MEDICINE_LEDGER_TYPES', is_array($achievementCatalog['medicineLedgerTypes'] ?? null) ? array_values($achievementCatalog['medicineLedgerTypes']) : []); +define('LINK_PROGRESS_TYPES', is_array($achievementCatalog['linkProgressTypes'] ?? null) ? array_values($achievementCatalog['linkProgressTypes']) : []); +define('MAD_SCIENTIST_TARGET', max(1, (int)($progressRules['mad_scientist']['target'] ?? 10))); -const ACHIEVEMENT_IDS = [ - 'first_birth', - 'natural_zunchi_slave', - 'natural_tarinai_king', - 'self_zunchi_death', - 'natural_zunchi_slave_5_generations', - 'natural_tarinai_king_3_generations', - 'death_50_in_10_seconds', - 'birth_50_in_60_seconds', - 'great_mother_1000_births', - 'lifespan_completed', - 'soccer_ball_death', - 'fight_pair_danger_kill', - 'all_non_sleep_diseased_25', - 'colony_happy', - 'direct_feed_33', - 'ignite_during_birth_ritual', - 'laxative_starvation', - 'idle_observer_5_minutes', - 'placed_objects_100', - 'mechanized_industry', - 'safe_colony_25_5_minutes', - 'ants_alive_25', - 'ants_killed_100', - 'secret_collection_9_slots', - 'pause_spam_4_in_1_second', - 'continuous_play_1_hour', - 'below_absolute_zero_item', - 'undo_mass_revival', - 'robot_cleaner_100', - 'held_30_seconds', - 'minimalist_happy', - 'overprotective', - 'self_sufficient', - 'unplanned_city_30', - 'sauna_cold_plunge', - 'rain_shelter_all', - 'medicine_ledger_all', - 'mercury_lifespan', - 'enemy_enemy_friend', - 'revolution', - 'fuel_to_fire', - 'undo_20', - 'redo_20', - 'eternal_history_generation_10', - 'king_full_satisfaction', - 'slave_zero_satisfaction', - 'town_doctor_50', - 'poke_plushie_fling', - 'chaos_seeker_666_fights', - 'clean_freak_robot_only', - 'true_tarinai_observer', - 'sniper_333_shots', - 'megalopolis', - 'fertility_seeker_721_love_births', - 'low_fps_single_digit', - 'continuous_play_24_hours', - 'sandbox_five_toilets', - 'park_ground_changed', - 'ground_change_4_in_1_second', - 'ant_nest_without_tarinai', - 'sticky_bomb_15_passes', - 'daily_play_7_days', - 'wire_shock_7_tarinai', - 'information_industry', - 'strength_in_numbers', - 'elite_few', - 'zunchi_overflow', - 'comfortable_beds', - 'stone_pillow', - 'across_seasons', - 'favorite_one', - 'statistician', - 'well_informed', - 'lively_making', - 'memento_mori', -]; -const DATA_DIR_NAME = '.achievement_data'; -const DATA_FILE_NAME = 'state.json'; -const LOCK_FILE_NAME = 'state.lock'; -const STATE_SCHEMA_VERSION = 3; const MAX_REQUEST_BYTES = 131072; +const RATE_WINDOW_SECONDS = 60; +const RATE_READ_LIMIT = 240; +const RATE_SESSION_IP_LIMIT = 120; +const RATE_WRITE_IP_LIMIT = 600; +const RATE_PLAYER_WRITE_LIMIT = 120; +const QUALIFY_MIN_ACTIVITY = 2; +const QUALIFY_MIN_AGE_SECONDS = 30; +const SESSION_COOKIE_NAME = 'tarinai_achievement_session_v2'; +const SESSION_COOKIE_MAX_AGE = 31536000; +const IDENTITY_ISSUE_WINDOW_SECONDS = 86400; +const IDENTITY_ISSUE_LIMIT_PER_IP = 512; +const SYNC_PROTOCOL_VERSION = 5; + function respond(array $payload, int $status = 200): never { http_response_code($status); @@ -95,280 +69,962 @@ function respond(array $payload, int $status = 200): never { } function valid_player_id(string $value): bool { - return preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i', $value) === 1; + return preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i', $value) === 1; } -function empty_state(): array { - return ['players' => [], 'unlocks' => []]; +function valid_player_secret(string $value): bool { + return preg_match('/^[0-9a-f]{64}$/i', $value) === 1; } -function compact_player_id(string $value): string { - $hex = str_replace('-', '', strtolower($value)); - if (strlen($hex) !== 32 || !ctype_xdigit($hex)) return ''; - $binary = hex2bin($hex); - if ($binary === false) return ''; - return rtrim(strtr(base64_encode($binary), '+/', '-_'), '='); +function client_ip(): string { + return substr((string)($_SERVER['REMOTE_ADDR'] ?? 'unknown'), 0, 128); } -function expand_player_id(string $value): string { - if (strlen($value) !== 22 || preg_match('/^[A-Za-z0-9_-]{22}$/', $value) !== 1) return ''; - $binary = base64_decode(strtr($value, '-_', '+/') . '==', true); - if ($binary === false || strlen($binary) !== 16) return ''; - $hex = bin2hex($binary); - return substr($hex, 0, 8) . '-' . substr($hex, 8, 4) . '-' . substr($hex, 12, 4) . '-' . substr($hex, 16, 4) . '-' . substr($hex, 20, 12); +function directory_has_achievement_data(string $path): bool { + return is_file($path . DIRECTORY_SEPARATOR . 'state.json') + || is_file($path . DIRECTORY_SEPARATOR . 'summary.json') + || is_file($path . DIRECTORY_SEPARATOR . 'session-key.json') + || is_dir($path . DIRECTORY_SEPARATOR . 'players'); } -function detect_state_format(mixed $value): string { - if (!is_array($value)) return 'invalid'; - if ($value === []) return 'empty'; - if (array_is_list($value)) { - return (($value[0] ?? null) === STATE_SCHEMA_VERSION - && isset($value[1], $value[2], $value[3], $value[4]) - && is_array($value[2]) && is_array($value[3]) && is_array($value[4])) - ? 'v3' : 'invalid'; +function copy_directory_tree(string $source, string $target): void { + ensure_directory($target); + $items = @scandir($source); + if (!is_array($items)) throw new RuntimeException('storage_unavailable'); + foreach ($items as $name) { + if ($name === '.' || $name === '..') continue; + $from = $source . DIRECTORY_SEPARATOR . $name; + $to = $target . DIRECTORY_SEPARATOR . $name; + if (is_dir($from)) copy_directory_tree($from, $to); + elseif (is_file($from) && !is_file($to) && !@copy($from, $to)) throw new RuntimeException('storage_write_failed'); } - if (($value['v'] ?? null) === 2 && isset($value['p'], $value['u']) && is_array($value['p']) && is_array($value['u'])) { - return 'v2'; - } - if (array_key_exists('players', $value) || array_key_exists('unlocks', $value)) return 'verbose'; - return 'invalid'; } -function normalize_state(mixed $value): array { - if (!is_array($value)) return empty_state(); - $players = []; - $unlocks = []; - - // v3 positional form: [version, baseTime, versions, players, unlocks]. - if (($value[0] ?? null) === STATE_SCHEMA_VERSION && isset($value[1], $value[2], $value[3], $value[4]) - && is_array($value[2]) && is_array($value[3]) && is_array($value[4])) { - $baseTime = max(1, (int)$value[1]); - $versions = array_map(static fn($entry): string => substr((string)$entry, 0, 32), $value[2]); - $playerIds = []; - foreach ($value[3] as $row) { - if (!is_array($row) || !isset($row[0]) || !is_string($row[0])) continue; - $id = expand_player_id($row[0]); - if (!valid_player_id($id)) continue; - $firstSeen = $baseTime + max(0, (int)($row[1] ?? 0)); - $lastSeen = $firstSeen + max(0, (int)($row[2] ?? 0)); - $versionIndex = max(0, (int)($row[3] ?? 0)); - $playerIds[] = $id; - $players[$id] = [ - 'firstSeen' => max(1, $firstSeen), - 'lastSeen' => max(1, $lastSeen), - 'gameVersion' => $versions[$versionIndex] ?? '', - ]; - } - foreach ($value[4] as $row) { - if (!is_array($row) || count($row) < 3) continue; - $achievementIndex = (int)$row[0]; - $achievementId = ACHIEVEMENT_IDS[$achievementIndex] ?? ''; - if ($achievementId === '') continue; - $records = []; - $count = count($row); - for ($i = 1; $i + 1 < $count; $i += 2) { - $playerIndex = (int)$row[$i]; - if (!isset($playerIds[$playerIndex])) continue; - $records[$playerIds[$playerIndex]] = $baseTime + max(0, (int)$row[$i + 1]); - } - if ($records) $unlocks[$achievementId] = $records; - } - // v2 is an on-read migration source and is always rewritten as v3. - } elseif (($value['v'] ?? null) === 2 && isset($value['p'], $value['u']) && is_array($value['p']) && is_array($value['u'])) { - $playerIds = []; - foreach ($value['p'] as $row) { - if (!is_array($row) || !isset($row[0]) || !is_string($row[0]) || !valid_player_id($row[0])) continue; - $id = strtolower($row[0]); - $playerIds[] = $id; - $players[$id] = [ - 'firstSeen' => max(1, (int)($row[1] ?? 1)), - 'lastSeen' => max(1, (int)($row[2] ?? ($row[1] ?? 1))), - 'gameVersion' => substr((string)($row[3] ?? ''), 0, 32), - ]; - } - foreach ($value['u'] as $achievementId => $flat) { - if (!is_string($achievementId) || (!in_array($achievementId, ACHIEVEMENT_IDS, true) && !in_array($achievementId, ['signal_automation_first', 'link_craftsman'], true)) || !is_array($flat)) continue; - $records = []; - $count = count($flat); - for ($i = 0; $i + 1 < $count; $i += 2) { - $playerIndex = (int)$flat[$i]; - if (!isset($playerIds[$playerIndex])) continue; - $records[$playerIds[$playerIndex]] = max(1, (int)$flat[$i + 1]); - } - if ($records) $unlocks[$achievementId] = $records; - } - } else { - $rawPlayers = isset($value['players']) && is_array($value['players']) ? $value['players'] : []; - foreach ($rawPlayers as $id => $player) { - if (!is_string($id) || !valid_player_id($id) || !is_array($player)) continue; - $players[strtolower($id)] = [ - 'firstSeen' => max(1, (int)($player['firstSeen'] ?? 1)), - 'lastSeen' => max(1, (int)($player['lastSeen'] ?? ($player['firstSeen'] ?? 1))), - 'gameVersion' => substr((string)($player['gameVersion'] ?? ''), 0, 32), - ]; - } - $rawUnlocks = isset($value['unlocks']) && is_array($value['unlocks']) ? $value['unlocks'] : []; - foreach ($rawUnlocks as $achievementId => $records) { - if (!is_string($achievementId) || (!in_array($achievementId, ACHIEVEMENT_IDS, true) && !in_array($achievementId, ['signal_automation_first', 'link_craftsman'], true)) || !is_array($records)) continue; - foreach ($records as $id => $timestamp) { - $normalizedId = strtolower((string)$id); - if (!isset($players[$normalizedId])) continue; - $unlocks[$achievementId][$normalizedId] = max(1, (int)$timestamp); - } - } - } - - $legacySignal = isset($unlocks['signal_automation_first']) && is_array($unlocks['signal_automation_first']) - ? $unlocks['signal_automation_first'] : []; - $legacyLinks = isset($unlocks['link_craftsman']) && is_array($unlocks['link_craftsman']) - ? $unlocks['link_craftsman'] : []; - if ($legacySignal && $legacyLinks) { - if (!isset($unlocks['mechanized_industry']) || !is_array($unlocks['mechanized_industry'])) { - $unlocks['mechanized_industry'] = []; - } - foreach ($legacySignal as $playerId => $signalTime) { - if (!isset($legacyLinks[$playerId])) continue; - $unlocks['mechanized_industry'][$playerId] = max((int)$signalTime, (int)$legacyLinks[$playerId]); - } - } - unset($unlocks['signal_automation_first'], $unlocks['link_craftsman']); - - return ['players' => $players, 'unlocks' => $unlocks]; +function legacy_state_snapshot(string $path): ?array { + if (!is_file($path)) return null; + $bytes = @file_get_contents($path); + if (!is_string($bytes) || trim($bytes) === '') throw new RuntimeException('legacy_state_unreadable'); + return [ + 'path' => $path, + 'bytes' => $bytes, + 'hash' => hash('sha256', $bytes), + 'size' => strlen($bytes), + 'mtime' => max(0, (int)@filemtime($path)), + ]; } -function compact_state(array $state): array { - $playerIds = array_keys($state['players']); - sort($playerIds, SORT_STRING); - $playerIndex = []; - $timestamps = []; - $versionCounts = []; - foreach ($playerIds as $id) { - $player = is_array($state['players'][$id] ?? null) ? $state['players'][$id] : []; - $timestamps[] = max(1, (int)($player['firstSeen'] ?? 1)); - $timestamps[] = max(1, (int)($player['lastSeen'] ?? ($player['firstSeen'] ?? 1))); - $version = substr((string)($player['gameVersion'] ?? ''), 0, 32); - $versionCounts[$version] = ($versionCounts[$version] ?? 0) + 1; +function remember_legacy_state_source(string $target, array $source): void { + atomic_write_json($target . DIRECTORY_SEPARATOR . 'legacy-v4-source.json', [ + 'schema' => 1, + 'sourcePath' => (string)$source['path'], + 'sourceHash' => (string)$source['hash'], + 'sourceSize' => (int)$source['size'], + 'sourceMtime' => (int)$source['mtime'], + 'copiedAt' => time(), + ]); +} + +function copy_legacy_state_snapshot(string $target, array $source): void { + atomic_write_bytes($target . DIRECTORY_SEPARATOR . 'state.json', (string)$source['bytes']); + remember_legacy_state_source($target, $source); +} + +function migrate_legacy_data_root(string $target, array $legacyRoots): void { + $targetCurrent = is_file($target . DIRECTORY_SEPARATOR . 'summary.json') + || is_file($target . DIRECTORY_SEPARATOR . 'session-key.json') + || is_dir($target . DIRECTORY_SEPARATOR . 'players'); + $targetStatePath = $target . DIRECTORY_SEPARATOR . 'state.json'; + $targetState = legacy_state_snapshot($targetStatePath); + + $candidates = []; + $stateCandidates = []; + foreach ($legacyRoots as $legacy) { + $path = rtrim((string)$legacy, DIRECTORY_SEPARATOR); + if ($path === '' || $path === $target || !is_dir($path) || !directory_has_achievement_data($path)) continue; + $directoryMtime = max( + (int)@filemtime($path), + (int)@filemtime($path . DIRECTORY_SEPARATOR . 'state.json'), + (int)@filemtime($path . DIRECTORY_SEPARATOR . 'summary.json') + ); + $candidates[$path] = $directoryMtime; + $snapshot = legacy_state_snapshot($path . DIRECTORY_SEPARATOR . 'state.json'); + if ($snapshot !== null) $stateCandidates[$path] = $snapshot; } - foreach ($state['unlocks'] as $achievementId => $records) { - if (!is_string($achievementId) || !in_array($achievementId, ACHIEVEMENT_IDS, true) || !is_array($records)) continue; - foreach ($records as $timestamp) $timestamps[] = max(1, (int)$timestamp); - } - $baseTime = $timestamps ? min($timestamps) : 1; - uksort($versionCounts, static function (string $a, string $b) use ($versionCounts): int { - $countOrder = ($versionCounts[$b] ?? 0) <=> ($versionCounts[$a] ?? 0); - return $countOrder !== 0 ? $countOrder : strcmp($a, $b); + arsort($candidates, SORT_NUMERIC); + uasort($stateCandidates, static function (array $a, array $b): int { + $mtime = ((int)$b['mtime']) <=> ((int)$a['mtime']); + if ($mtime !== 0) return $mtime; + return ((int)$b['size']) <=> ((int)$a['size']); }); - $versions = array_keys($versionCounts); - if (!$versions) $versions = ['']; - $versionIndex = array_flip($versions); - $players = []; - foreach ($playerIds as $index => $id) { - $playerIndex[$id] = $index; - $player = is_array($state['players'][$id] ?? null) ? $state['players'][$id] : []; - $firstSeen = max(1, (int)($player['firstSeen'] ?? 1)); - $lastSeen = max($firstSeen, (int)($player['lastSeen'] ?? $firstSeen)); - $version = substr((string)($player['gameVersion'] ?? ''), 0, 32); - $row = [compact_player_id($id), $firstSeen - $baseTime, $lastSeen - $firstSeen]; - $indexValue = (int)($versionIndex[$version] ?? 0); - if ($indexValue !== 0) $row[] = $indexValue; - $players[] = $row; + // When a compact source was copied into a private current root, keep + // comparing the original source on later requests. This captures final + // writes made by the legacy server during cut-over instead of freezing the + // first copied snapshot forever. + if ($targetState !== null && $stateCandidates) { + $sourceMarker = read_json_file($target . DIRECTORY_SEPARATOR . 'legacy-v4-source.json', []); + $migrationMarker = read_json_file($target . DIRECTORY_SEPARATOR . 'legacy-v4-migration.json', []); + $preferredPath = (string)($sourceMarker['sourcePath'] ?? ''); + $source = $preferredPath !== '' && isset($stateCandidates[dirname($preferredPath)]) + ? $stateCandidates[dirname($preferredPath)] + : reset($stateCandidates); + if (is_array($source) && !hash_equals((string)$targetState['hash'], (string)$source['hash'])) { + $trackedSource = $preferredPath !== '' && (string)$source['path'] === $preferredPath; + $targetIsLastImportedSnapshot = hash_equals( + strtolower((string)($migrationMarker['sourceHash'] ?? '')), + strtolower((string)$targetState['hash']) + ); + $sourceIsNotOlder = (int)$source['mtime'] >= (int)$targetState['mtime']; + if ($trackedSource || $targetIsLastImportedSnapshot || $sourceIsNotOlder) { + copy_legacy_state_snapshot($target, $source); + $targetState = $source; + } + } + return; } - $unlocks = []; - foreach (ACHIEVEMENT_IDS as $achievementIndex => $achievementId) { - $records = $state['unlocks'][$achievementId] ?? null; - if (!is_array($records) || !$records) continue; - $pairs = []; - foreach ($records as $id => $timestamp) { - if (!isset($playerIndex[$id])) continue; - $pairs[] = [$playerIndex[$id], max(1, (int)$timestamp) - $baseTime]; - } - usort($pairs, static fn(array $a, array $b): int => $a[0] <=> $b[0]); - if (!$pairs) continue; - $row = [$achievementIndex]; - foreach ($pairs as [$indexValue, $timestampDelta]) { - $row[] = $indexValue; - $row[] = max(0, $timestampDelta); - } - $unlocks[] = $row; + if (!$candidates) return; + + // A prior current build may already have created an empty summary/player + // tree. Copy the newest compact source into it so the importer can merge it + // without discarding current records. + if ($targetCurrent) { + $source = $stateCandidates ? reset($stateCandidates) : null; + if (is_array($source)) copy_legacy_state_snapshot($target, $source); + return; } - return [STATE_SCHEMA_VERSION, $baseTime, $versions, $players, $unlocks]; + + $sourcePath = (string)array_key_first($candidates); + ensure_directory(dirname($target)); + if (isset($stateCandidates[$sourcePath])) { + copy_directory_tree($sourcePath, $target); + remember_legacy_state_source($target, $stateCandidates[$sourcePath]); + return; + } + if (!file_exists($target) && @rename($sourcePath, $target)) { + // A separate compact source may coexist with a current-format legacy + // directory. Merge the compact snapshot as well. + $stateSource = $stateCandidates ? reset($stateCandidates) : null; + if (is_array($stateSource)) copy_legacy_state_snapshot($target, $stateSource); + return; + } + copy_directory_tree($sourcePath, $target); + $stateSource = $stateCandidates ? reset($stateCandidates) : null; + if (is_array($stateSource) && !is_file($targetStatePath)) copy_legacy_state_snapshot($target, $stateSource); } -function encode_compact_state(array $state): string { +function data_root(): string { + $configured = trim((string)(getenv('TARINAI_ACHIEVEMENT_DATA_DIR') ?: '')); + if ($configured !== '') { + $target = rtrim($configured, DIRECTORY_SEPARATOR); + migrate_legacy_data_root($target, [ + __DIR__ . DIRECTORY_SEPARATOR . '.achievement_data', + dirname(__DIR__) . DIRECTORY_SEPARATOR . '.achievement_data', + ]); + return $target; + } + + $documentRoot = realpath((string)($_SERVER['DOCUMENT_ROOT'] ?? '')); + $publicRoot = is_string($documentRoot) && $documentRoot !== '' ? $documentRoot : __DIR__; + $installPath = realpath(__DIR__) ?: __DIR__; + $installKey = substr(hash('sha256', $installPath), 0, 16); + $legacyParent = dirname($publicRoot); + $legacyRoots = [ + $legacyParent . DIRECTORY_SEPARATOR . '.tarinai-achievements-' . $installKey, + __DIR__ . DIRECTORY_SEPARATOR . '.achievement_data', + $publicRoot . DIRECTORY_SEPARATOR . '.achievement_data', + ]; + $globbed = glob($legacyParent . DIRECTORY_SEPARATOR . '.tarinai-achievements-*', GLOB_ONLYDIR); + if (is_array($globbed)) $legacyRoots = array_merge($legacyRoots, $globbed); + + // Keep local-server data independent of the ZIP extraction directory and + // listening port. This makes upgrades and side-by-side extracted versions + // share one persistent achievement identity and server record. + $xdg = trim((string)(getenv('XDG_DATA_HOME') ?: '')); + $home = trim((string)(getenv('HOME') ?: getenv('USERPROFILE') ?: '')); + if ($xdg !== '') $target = rtrim($xdg, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'tarinai-observer' . DIRECTORY_SEPARATOR . 'achievements'; + elseif ($home !== '') $target = rtrim($home, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . '.tarinai-observer' . DIRECTORY_SEPARATOR . 'achievements'; + else $target = $legacyParent . DIRECTORY_SEPARATOR . '.tarinai-achievements'; + try { - return json_encode(compact_state($state), JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE | JSON_THROW_ON_ERROR); - } catch (JsonException $error) { - throw new RuntimeException('storage_encode_failed', 0, $error); + migrate_legacy_data_root($target, $legacyRoots); + return $target; + } catch (RuntimeException) { + // Hosted environments may not permit writes under HOME. The fallback + // remains outside the document root and is stable across sibling builds. + $fallback = $legacyParent . DIRECTORY_SEPARATOR . '.tarinai-achievements'; + migrate_legacy_data_root($fallback, $legacyRoots); + return $fallback; } } -function decode_stored_state(string $contents): array { - if (trim($contents) === '') return [empty_state(), 'empty']; +function ensure_directory(string $path): void { + if (!is_dir($path) && !mkdir($path, 0770, true) && !is_dir($path)) throw new RuntimeException('storage_unavailable'); +} + + +function protect_data_root(string $path): void { + ensure_directory($path); + $rules = "Options -Indexes\n\n Require all denied\n\n\n Deny from all\n\n"; + $htaccess = $path . DIRECTORY_SEPARATOR . '.htaccess'; + if (!is_file($htaccess)) @file_put_contents($htaccess, $rules, LOCK_EX); + $index = $path . DIRECTORY_SEPARATOR . 'index.html'; + if (!is_file($index)) @file_put_contents($index, '', LOCK_EX); +} + +function read_json_file(string $path, array $fallback): array { + if (!is_file($path)) return $fallback; + $raw = file_get_contents($path); + if (!is_string($raw)) throw new RuntimeException('storage_unavailable'); + if (trim($raw) === '') return $fallback; try { - $decoded = json_decode($contents, true, 512, JSON_THROW_ON_ERROR); + $value = json_decode($raw, true, 128, JSON_THROW_ON_ERROR); } catch (JsonException $error) { throw new RuntimeException('storage_corrupt', 0, $error); } - $format = detect_state_format($decoded); - if ($format === 'invalid') throw new RuntimeException('storage_corrupt'); - return [normalize_state($decoded), $format]; + return is_array($value) ? $value : $fallback; } -function atomic_write_state(string $dataPath, string $encoded): void { - $dataDir = dirname($dataPath); - $tempPath = tempnam($dataDir, DATA_FILE_NAME . '.tmp.'); - if ($tempPath === false) throw new RuntimeException('storage_unavailable'); - $handle = @fopen($tempPath, 'wb'); - if ($handle === false) { - @unlink($tempPath); - throw new RuntimeException('storage_unavailable'); - } +function atomic_write_json(string $path, array $value): void { + ensure_directory(dirname($path)); + try { + $encoded = json_encode($value, JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE | JSON_THROW_ON_ERROR); + } catch (JsonException $error) { + throw new RuntimeException('storage_encode_failed', 0, $error); + } + $temp = tempnam(dirname($path), basename($path) . '.tmp.'); + if ($temp === false) throw new RuntimeException('storage_unavailable'); + $handle = @fopen($temp, 'wb'); + if ($handle === false) { @unlink($temp); throw new RuntimeException('storage_unavailable'); } try { - $length = strlen($encoded); $offset = 0; + $length = strlen($encoded); while ($offset < $length) { $written = fwrite($handle, substr($encoded, $offset)); if ($written === false || $written === 0) throw new RuntimeException('storage_write_failed'); $offset += $written; } if (!fflush($handle)) throw new RuntimeException('storage_write_failed'); - if (function_exists('fsync') && !fsync($handle)) throw new RuntimeException('storage_write_failed'); + if (function_exists('fsync')) @fsync($handle); } catch (Throwable $error) { - fclose($handle); - @unlink($tempPath); - throw $error; + fclose($handle); @unlink($temp); throw $error; } fclose($handle); - @chmod($tempPath, 0664); - if (!@rename($tempPath, $dataPath)) { - @unlink($tempPath); - throw new RuntimeException('storage_write_failed'); - } + @chmod($temp, 0660); + if (!@rename($temp, $path)) { @unlink($temp); throw new RuntimeException('storage_write_failed'); } } -function build_summary(array $state): array { - $total = count($state['players']); - $achievements = []; - foreach (ACHIEVEMENT_IDS as $id) { - $unlocked = isset($state['unlocks'][$id]) && is_array($state['unlocks'][$id]) - ? count($state['unlocks'][$id]) - : 0; - $percentage = $total > 0 ? round(($unlocked / $total) * 100, 1) : 0.0; - $achievements[$id] = [ - 'unlockedPlayers' => $unlocked, - 'percentage' => $percentage, - ]; + +function atomic_write_bytes(string $path, string $bytes): void { + ensure_directory(dirname($path)); + $temp = tempnam(dirname($path), basename($path) . '.tmp.'); + if ($temp === false) throw new RuntimeException('storage_unavailable'); + $handle = @fopen($temp, 'wb'); + if ($handle === false) { @unlink($temp); throw new RuntimeException('storage_unavailable'); } + try { + $offset = 0; + $length = strlen($bytes); + while ($offset < $length) { + $written = fwrite($handle, substr($bytes, $offset)); + if ($written === false || $written === 0) throw new RuntimeException('storage_write_failed'); + $offset += $written; + } + if (!fflush($handle)) throw new RuntimeException('storage_write_failed'); + if (function_exists('fsync')) @fsync($handle); + } catch (Throwable $error) { + fclose($handle); @unlink($temp); throw $error; } + fclose($handle); + @chmod($temp, 0660); + if (!@rename($temp, $path)) { @unlink($temp); throw new RuntimeException('storage_write_failed'); } +} + +function valid_legacy_player_id(string $value): bool { + return preg_match('/^[A-Za-z0-9_-]{22}$/', $value) === 1; +} + +function legacy_player_uuid(string $legacyId): string { + if (!valid_legacy_player_id($legacyId)) throw new RuntimeException('legacy_state_invalid'); + $decoded = base64_decode(strtr($legacyId, '-_', '+/') . '==', true); + if (!is_string($decoded) || strlen($decoded) !== 16) throw new RuntimeException('legacy_state_invalid'); + $bytes = $decoded; + $bytes[6] = chr((ord($bytes[6]) & 0x0f) | 0x40); + $bytes[8] = chr((ord($bytes[8]) & 0x3f) | 0x80); + $hex = bin2hex($bytes); + return substr($hex, 0, 8) . '-' . substr($hex, 8, 4) . '-' . substr($hex, 12, 4) . '-' . substr($hex, 16, 4) . '-' . substr($hex, 20, 12); +} + +/** + * Imports the compact schema-4 state.json used by the pre-credential server. + * The source remains untouched and is copied byte-for-byte into legacy-backup. + * Player writes are deterministic and idempotent, so a process interruption is + * safely resumed on the next request before the completion marker is written. + */ +function migrate_legacy_compact_state_v4(string $root, string $summaryPath): ?array { + $sourcePath = $root . DIRECTORY_SEPARATOR . 'state.json'; + if (!is_file($sourcePath)) return null; + $markerPath = $root . DIRECTORY_SEPARATOR . 'legacy-v4-migration.json'; + $marker = read_json_file($markerPath, []); + $sourceSize = max(0, (int)@filesize($sourcePath)); + $sourceMtime = max(0, (int)@filemtime($sourcePath)); + $sourceRaw = @file_get_contents($sourcePath); + if (!is_string($sourceRaw) || trim($sourceRaw) === '') throw new RuntimeException('legacy_state_unreadable'); + $sourceHash = hash('sha256', $sourceRaw); + if (($marker['status'] ?? '') === 'complete' + && hash_equals((string)($marker['sourceHash'] ?? ''), $sourceHash)) { + $marker['sourceSize'] = $sourceSize; + $marker['sourceMtime'] = $sourceMtime; + atomic_write_json($markerPath, $marker); + return $marker; + } + // If the legacy server wrote a final update during cut-over, import the + // changed snapshot again. The merge is grow-only and deterministic. + + try { + $data = json_decode($sourceRaw, true, 256, JSON_THROW_ON_ERROR); + } catch (JsonException $error) { + throw new RuntimeException('legacy_state_invalid', 0, $error); + } + if (!is_array($data) || count($data) !== 6 || ($data[0] ?? null) !== 4) throw new RuntimeException('legacy_state_invalid'); + $baseTimestamp = $data[1] ?? null; + $versions = $data[2] ?? null; + $catalogIds = $data[3] ?? null; + $playerRows = $data[4] ?? null; + $unlockRows = $data[5] ?? null; + if (!is_int($baseTimestamp) || $baseTimestamp < 946684800 || !is_array($versions) || !$versions + || !is_array($catalogIds) || !is_array($playerRows) || !is_array($unlockRows)) { + throw new RuntimeException('legacy_state_invalid'); + } + foreach ($versions as $version) { + if (!is_string($version) || $version === '' || strlen($version) > 32) throw new RuntimeException('legacy_state_invalid'); + } + if (array_values($catalogIds) !== array_values(ACHIEVEMENT_IDS)) throw new RuntimeException('legacy_catalog_mismatch'); + + $perPlayerUnlocks = array_fill(0, count($playerRows), []); + $legacyCounts = array_fill_keys(ACHIEVEMENT_IDS, 0); + $seenAchievements = []; + $unlockAssignments = 0; + foreach ($unlockRows as $unlockRow) { + if (!is_array($unlockRow) || count($unlockRow) < 3 || count($unlockRow) % 2 !== 1) throw new RuntimeException('legacy_state_invalid'); + $achievementIndex = $unlockRow[0] ?? null; + if (!is_int($achievementIndex) || $achievementIndex < 0 || $achievementIndex >= count(ACHIEVEMENT_IDS) + || isset($seenAchievements[$achievementIndex])) throw new RuntimeException('legacy_state_invalid'); + $seenAchievements[$achievementIndex] = true; + $achievementId = ACHIEVEMENT_IDS[$achievementIndex]; + $seenPlayers = []; + for ($offset = 1; $offset < count($unlockRow); $offset += 2) { + $playerIndex = $unlockRow[$offset] ?? null; + $timeOffset = $unlockRow[$offset + 1] ?? null; + if (!is_int($playerIndex) || $playerIndex < 0 || $playerIndex >= count($playerRows) + || isset($seenPlayers[$playerIndex]) || !is_int($timeOffset) || $timeOffset < 0) { + throw new RuntimeException('legacy_state_invalid'); + } + $timestamp = $baseTimestamp + $timeOffset; + if ($timestamp < 946684800) throw new RuntimeException('legacy_state_invalid'); + $seenPlayers[$playerIndex] = true; + $perPlayerUnlocks[$playerIndex][$achievementId] = $timestamp; + $legacyCounts[$achievementId]++; + $unlockAssignments++; + } + } + + $backupPath = $root . DIRECTORY_SEPARATOR . 'legacy-backup' . DIRECTORY_SEPARATOR . 'state-v4-' . $sourceHash . '.json'; + if (!is_file($backupPath)) atomic_write_bytes($backupPath, $sourceRaw); + $backupRaw = @file_get_contents($backupPath); + if (!is_string($backupRaw) || !hash_equals($sourceHash, hash('sha256', $backupRaw))) throw new RuntimeException('legacy_backup_failed'); + + atomic_write_json($markerPath, [ + 'schema' => 1, + 'status' => 'in_progress', + 'sourceSchema' => 4, + 'sourceHash' => $sourceHash, + 'sourceSize' => $sourceSize, + 'sourceMtime' => $sourceMtime, + 'startedAt' => time(), + 'expectedPlayers' => count($playerRows), + 'expectedUnlockAssignments' => $unlockAssignments, + 'backup' => basename(dirname($backupPath)) . '/' . basename($backupPath), + ]); + + $legacyIdsSeen = []; + $migratedPlayerIds = []; + foreach ($playerRows as $index => $row) { + if (!is_array($row) || count($row) < 3 || count($row) > 4) throw new RuntimeException('legacy_state_invalid'); + $legacyId = $row[0] ?? null; + $firstOffset = $row[1] ?? null; + $duration = $row[2] ?? null; + $versionIndex = $row[3] ?? 0; + if (!is_string($legacyId) || !valid_legacy_player_id($legacyId) || isset($legacyIdsSeen[$legacyId]) + || !is_int($firstOffset) || $firstOffset < 0 || !is_int($duration) || $duration < 0 + || !is_int($versionIndex) || $versionIndex < 0 || $versionIndex >= count($versions)) { + throw new RuntimeException('legacy_state_invalid'); + } + $legacyIdsSeen[$legacyId] = true; + $playerId = legacy_player_uuid($legacyId); + if (isset($migratedPlayerIds[$playerId])) throw new RuntimeException('legacy_player_collision'); + $migratedPlayerIds[$playerId] = true; + $claimHash = hash('sha256', $legacyId); + $path = player_path($root, $playerId); + if (is_file($path)) { + $existingRaw = read_json_file($path, []); + $existingClaimHash = strtolower((string)($existingRaw['legacyClaimHash'] ?? '')); + if ($existingClaimHash !== '' && !hash_equals($existingClaimHash, $claimHash)) throw new RuntimeException('legacy_player_collision'); + if ($existingClaimHash === '' && (string)($existingRaw['ownerHash'] ?? '') !== '') throw new RuntimeException('legacy_player_collision'); + $player = normalize_player($existingRaw, $playerId); + } else { + $player = default_player($playerId, '', $baseTimestamp + $firstOffset); + } + $player['schema'] = 5; + $player['legacyClaimHash'] = $claimHash; + $player['legacyClaimedAt'] = max(0, (int)($player['legacyClaimedAt'] ?? 0)); + $player['firstSeen'] = min((int)$player['firstSeen'], $baseTimestamp + $firstOffset); + $player['lastSeen'] = max((int)$player['lastSeen'], $baseTimestamp + $firstOffset + $duration); + $player['activityCount'] = max(2, (int)$player['activityCount']); + $player['qualified'] = true; + if ((string)$player['gameVersion'] === '') $player['gameVersion'] = $versions[$versionIndex]; + // A later explicit reset must remain authoritative if migration is + // resumed after the player has already advanced to a newer generation. + if ((int)$player['generation'] === 0) { + foreach ($perPlayerUnlocks[$index] as $achievementId => $timestamp) { + if (!isset($player['unlocked'][$achievementId])) $player['unlocked'][$achievementId] = $timestamp; + else $player['unlocked'][$achievementId] = min((int)$player['unlocked'][$achievementId], $timestamp); + } + } + reconcile_completionist($player['unlocked'], $player['lastSeen']); + atomic_write_json($path, $player); + } + + $verifiedAssignments = 0; + foreach ($playerRows as $index => $row) { + $legacyId = (string)$row[0]; + $playerId = legacy_player_uuid($legacyId); + $player = normalize_player(read_json_file(player_path($root, $playerId), []), $playerId); + if (!hash_equals(hash('sha256', $legacyId), (string)$player['legacyClaimHash'])) throw new RuntimeException('legacy_migration_verify_failed'); + if ((int)$player['generation'] === 0) { + foreach ($perPlayerUnlocks[$index] as $achievementId => $timestamp) { + if (!isset($player['unlocked'][$achievementId]) || (int)$player['unlocked'][$achievementId] > $timestamp) { + throw new RuntimeException('legacy_migration_verify_failed'); + } + $verifiedAssignments++; + } + } + } + if ($verifiedAssignments !== $unlockAssignments) throw new RuntimeException('legacy_migration_verify_failed'); + + $summary = repair_summary_cache($root, $summaryPath); + if ((int)$summary['totalPlayers'] < count($playerRows)) throw new RuntimeException('legacy_migration_verify_failed'); + foreach ($legacyCounts as $achievementId => $count) { + if ((int)($summary['counts'][$achievementId] ?? 0) < $count) throw new RuntimeException('legacy_migration_verify_failed'); + } + $complete = [ + 'schema' => 1, + 'status' => 'complete', + 'sourceSchema' => 4, + 'sourceHash' => $sourceHash, + 'sourceSize' => $sourceSize, + 'sourceMtime' => $sourceMtime, + 'completedAt' => time(), + 'migratedPlayers' => count($playerRows), + 'migratedUnlockAssignments' => $unlockAssignments, + 'summaryPlayers' => (int)$summary['totalPlayers'], + 'backup' => basename(dirname($backupPath)) . '/' . basename($backupPath), + ]; + atomic_write_json($markerPath, $complete); + return $complete; +} + +function with_lock(string $path, int $mode, callable $callback): mixed { + ensure_directory(dirname($path)); + $handle = @fopen($path, 'c'); + if ($handle === false || !flock($handle, $mode)) { + if (is_resource($handle)) fclose($handle); + throw new RuntimeException('storage_locked'); + } + try { return $callback(); } finally { flock($handle, LOCK_UN); fclose($handle); } +} + +function player_path(string $root, string $playerId): string { + $bucket = substr(hash('sha256', $playerId), 0, 2); + return $root . DIRECTORY_SEPARATOR . 'players' . DIRECTORY_SEPARATOR . $bucket . DIRECTORY_SEPARATOR . hash('sha256', $playerId) . '.json'; +} + +function default_summary(): array { return [ - 'ok' => true, - 'totalPlayers' => $total, - 'achievements' => $achievements, + 'schema' => 1, + 'totalPlayers' => 0, + 'counts' => array_fill_keys(ACHIEVEMENT_IDS, 0), ]; } -$method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET'); +function normalize_summary(array $summary): array { + $out = default_summary(); + $out['totalPlayers'] = max(0, (int)($summary['totalPlayers'] ?? 0)); + $counts = is_array($summary['counts'] ?? null) ? $summary['counts'] : []; + foreach (ACHIEVEMENT_IDS as $id) $out['counts'][$id] = max(0, (int)($counts[$id] ?? 0)); + return $out; +} + +function default_progress_state(): array { + return [ + 'progress' => [ + 'linkTypes' => [], + 'signalActivated' => false, + 'medicineTypes' => [], + 'dailyPlayStreak' => 0, + 'dailyPlayLastDay' => 0, + 'mysteryDrugTarinaiIds' => [], + ], + 'ledger' => [ + 'base' => array_fill_keys(array_keys(ADDITIVE_PROGRESS_CAPS), 0), + 'shards' => array_fill_keys(array_keys(ADDITIVE_PROGRESS_CAPS), []), + ], + ]; +} + +function progress_counter_value(array $progressState, string $key): int { + $cap = (int)(ADDITIVE_PROGRESS_CAPS[$key] ?? 0); + if ($cap <= 0) return 0; + $base = bounded_int($progressState['ledger']['base'][$key] ?? 0, 0, $cap); + $shards = is_array($progressState['ledger']['shards'][$key] ?? null) ? $progressState['ledger']['shards'][$key] : []; + $sum = $base; + foreach ($shards as $value) $sum += bounded_int($value, 0, $cap); + return min($cap, $sum); +} + +function bounded_int(mixed $value, int $minimum, int $maximum): int { + if (!is_int($value) && !is_float($value) && !is_string($value)) return $minimum; + if (!is_numeric($value)) return $minimum; + $numeric = (float)$value; + if (!is_finite($numeric)) return $minimum; + return max($minimum, min($maximum, (int)floor($numeric))); +} + +function unique_allowed_strings(mixed $input, array $allowed): array { + if (!is_array($input)) return []; + $lookup = array_fill_keys($allowed, true); + $out = []; + foreach ($input as $value) { + $text = (string)$value; + if (isset($lookup[$text])) $out[$text] = true; + } + return array_keys($out); +} + +function normalize_progress_state(mixed $input): array { + $out = default_progress_state(); + if (!is_array($input)) return $out; + $progressSource = is_array($input['progress'] ?? null) ? $input['progress'] : []; + $ledgerSource = is_array($input['ledger'] ?? null) ? $input['ledger'] : []; + $baseSource = is_array($ledgerSource['base'] ?? null) ? $ledgerSource['base'] : []; + $shardsSource = is_array($ledgerSource['shards'] ?? null) ? $ledgerSource['shards'] : []; + + foreach (ADDITIVE_PROGRESS_CAPS as $key => $rawCap) { + $cap = max(0, (int)$rawCap); + $base = bounded_int($baseSource[$key] ?? 0, 0, $cap); + $shards = []; + $rawShards = is_array($shardsSource[$key] ?? null) ? $shardsSource[$key] : []; + foreach ($rawShards as $actorId => $rawValue) { + $id = substr((string)$actorId, 0, 160); + if ($id === '' || preg_match('/[\x00-\x1F\x7F]/', $id) === 1) continue; + $value = bounded_int($rawValue, 0, $cap); + if ($value > 0) $shards[$id] = max((int)($shards[$id] ?? 0), $value); + } + $total = min($cap, $base + array_sum($shards)); + // Protocol v4 and older duplicated additive counters in progress. Read + // them as a one-time migration floor, but never emit them again. + $legacyFloor = bounded_int($progressSource[$key] ?? 0, 0, $cap); + if ($legacyFloor > $total) { + $base = min($cap, $base + ($legacyFloor - $total)); + $total = $legacyFloor; + } + if ($total >= $cap) { + $base = $cap; + $shards = []; + } + $out['ledger']['base'][$key] = $base; + $out['ledger']['shards'][$key] = $shards; + } + + $out['progress']['linkTypes'] = unique_allowed_strings($progressSource['linkTypes'] ?? [], LINK_PROGRESS_TYPES); + $out['progress']['signalActivated'] = (bool)($progressSource['signalActivated'] ?? false); + $out['progress']['medicineTypes'] = unique_allowed_strings($progressSource['medicineTypes'] ?? [], MEDICINE_LEDGER_TYPES); + $out['progress']['dailyPlayStreak'] = bounded_int($progressSource['dailyPlayStreak'] ?? 0, 0, 7); + $out['progress']['dailyPlayLastDay'] = bounded_int($progressSource['dailyPlayLastDay'] ?? 0, 0, 1000000); + $ids = []; + foreach ((array)($progressSource['mysteryDrugTarinaiIds'] ?? []) as $rawId) { + $id = substr(trim((string)$rawId), 0, 160); + if ($id !== '' && preg_match('/[\x00-\x1F\x7F]/', $id) !== 1) $ids[$id] = true; + if (count($ids) >= MAD_SCIENTIST_TARGET) break; + } + $out['progress']['mysteryDrugTarinaiIds'] = array_keys($ids); + return $out; +} + +function merge_progress_state(mixed $targetInput, mixed $sourceInput): array { + $target = normalize_progress_state($targetInput); + $source = normalize_progress_state($sourceInput); + foreach (ADDITIVE_PROGRESS_CAPS as $key => $cap) { + $target['ledger']['base'][$key] = max((int)$target['ledger']['base'][$key], (int)$source['ledger']['base'][$key]); + foreach ($source['ledger']['shards'][$key] as $actorId => $value) { + $target['ledger']['shards'][$key][$actorId] = max((int)($target['ledger']['shards'][$key][$actorId] ?? 0), (int)$value); + } + } + $targetDay = (int)$target['progress']['dailyPlayLastDay']; + $sourceDay = (int)$source['progress']['dailyPlayLastDay']; + if ($sourceDay > $targetDay) { + $target['progress']['dailyPlayLastDay'] = $sourceDay; + $target['progress']['dailyPlayStreak'] = (int)$source['progress']['dailyPlayStreak']; + } elseif ($sourceDay === $targetDay) { + $target['progress']['dailyPlayStreak'] = max((int)$target['progress']['dailyPlayStreak'], (int)$source['progress']['dailyPlayStreak']); + } + $target['progress']['signalActivated'] = (bool)$target['progress']['signalActivated'] || (bool)$source['progress']['signalActivated']; + $target['progress']['linkTypes'] = array_values(array_unique(array_merge($target['progress']['linkTypes'], $source['progress']['linkTypes']))); + $target['progress']['medicineTypes'] = array_values(array_unique(array_merge($target['progress']['medicineTypes'], $source['progress']['medicineTypes']))); + $target['progress']['mysteryDrugTarinaiIds'] = array_slice(array_values(array_unique(array_merge( + $target['progress']['mysteryDrugTarinaiIds'], + $source['progress']['mysteryDrugTarinaiIds'] + ))), 0, MAD_SCIENTIST_TARGET); + return normalize_progress_state($target); +} + +function progress_unlock_satisfied(string $id, array $progressState): ?bool { + $rule = PROGRESS_RULES[$id] ?? null; + if (!is_array($rule)) return null; + $type = (string)($rule['type'] ?? ''); + $key = (string)($rule['key'] ?? ''); + $target = max(0, (int)($rule['target'] ?? 0)); + $progress = $progressState['progress']; + if ($type === 'counter') return progress_counter_value($progressState, $key) >= $target; + if ($type === 'value') return bounded_int($progress[$key] ?? 0, 0, max($target, 1000000)) >= $target; + if ($type === 'set') { + $required = (string)($rule['required'] ?? ''); + $requiredValues = $required === 'medicineLedgerTypes' ? MEDICINE_LEDGER_TYPES : []; + return count(array_intersect($requiredValues, (array)($progress[$key] ?? []))) === count($requiredValues); + } + if ($type === 'unique') return count((array)($progress[$key] ?? [])) >= $target; + if ($type === 'mechanized') { + return (bool)($progress['signalActivated'] ?? false) + && count(array_intersect(LINK_PROGRESS_TYPES, (array)($progress['linkTypes'] ?? []))) === count(LINK_PROGRESS_TYPES); + } + return null; +} + +function reconcile_progress_unlocks(array &$unlocked, array $progressState, int $now): void { + foreach (ACHIEVEMENT_IDS as $id) { + if ($id === COMPLETIONIST_ID || isset($unlocked[$id])) continue; + if (progress_unlock_satisfied($id, $progressState) === true) $unlocked[$id] = $now; + } +} + +function default_player(string $playerId, string $ownerHash, int $now): array { + return [ + 'schema' => 5, + 'playerId' => $playerId, + 'ownerHash' => $ownerHash, + 'firstSeen' => $now, + 'lastSeen' => $now, + 'activityCount' => 0, + 'qualified' => false, + 'gameVersion' => '', + 'generation' => 0, + 'unlocked' => [], + 'progressState' => default_progress_state(), + ]; +} + +function normalize_player(array $player, string $playerId): array { + $now = time(); + $unlocked = []; + foreach ((array)($player['unlocked'] ?? []) as $id => $timestamp) { + if (is_string($id) && in_array($id, ACHIEVEMENT_IDS, true)) $unlocked[$id] = max(1, (int)$timestamp); + } + return [ + 'schema' => 5, + 'playerId' => $playerId, + 'ownerHash' => (string)($player['ownerHash'] ?? ''), + 'firstSeen' => max(1, (int)($player['firstSeen'] ?? $now)), + 'lastSeen' => max(1, (int)($player['lastSeen'] ?? $now)), + 'activityCount' => max(0, (int)($player['activityCount'] ?? 0)), + 'qualified' => (bool)($player['qualified'] ?? false), + 'gameVersion' => substr((string)($player['gameVersion'] ?? ''), 0, 32), + 'generation' => max(0, (int)($player['generation'] ?? 0)), + 'unlocked' => $unlocked, + 'progressState' => normalize_progress_state($player['progressState'] ?? null), + 'legacyClaimHash' => preg_match('/^[0-9a-f]{64}$/', strtolower((string)($player['legacyClaimHash'] ?? ''))) === 1 + ? strtolower((string)$player['legacyClaimHash']) : '', + 'legacyClaimedAt' => max(0, (int)($player['legacyClaimedAt'] ?? 0)), + ]; +} + +/** + * The summary is a derived cache, never the source of truth. Rebuilding it from + * player records makes a corrupt/missing summary self-healing and repairs a + * process interruption between the player and summary renames. + */ +function rebuild_summary_from_players(string $root): array { + $summary = default_summary(); + $playersRoot = $root . DIRECTORY_SEPARATOR . 'players'; + if (!is_dir($playersRoot)) return $summary; + try { + $iterator = new RecursiveIteratorIterator( + new RecursiveDirectoryIterator($playersRoot, FilesystemIterator::SKIP_DOTS) + ); + foreach ($iterator as $file) { + if (!$file->isFile() || strtolower($file->getExtension()) !== 'json') continue; + try { + $raw = read_json_file($file->getPathname(), []); + $playerId = strtolower((string)($raw['playerId'] ?? '')); + if (!valid_player_id($playerId)) continue; + $player = normalize_player($raw, $playerId); + } catch (Throwable) { + // One damaged player record must not take down every player. + continue; + } + if (!(bool)$player['qualified']) continue; + $summary['totalPlayers']++; + foreach (array_keys($player['unlocked']) as $id) { + if (isset($summary['counts'][$id])) $summary['counts'][$id]++; + } + } + } catch (UnexpectedValueException) { + throw new RuntimeException('storage_unavailable'); + } + return normalize_summary($summary); +} + +function repair_summary_cache(string $root, string $summaryPath): array { + $summary = rebuild_summary_from_players($root); + atomic_write_json($summaryPath, $summary); + return $summary; +} + +function verify_owner(array &$player, string $secret): void { + $submitted = hash('sha256', strtolower($secret)); + $stored = (string)($player['ownerHash'] ?? ''); + if ($stored === '' || !hash_equals($stored, $submitted)) respond(['ok' => false, 'error' => 'invalid_owner'], 403); +} + +function reconcile_completionist(array &$unlocked, int $now): void { + $latestPrerequisite = 0; + foreach (ACHIEVEMENT_IDS as $id) { + if ($id === COMPLETIONIST_ID) continue; + if (!isset($unlocked[$id])) { unset($unlocked[COMPLETIONIST_ID]); return; } + $latestPrerequisite = max($latestPrerequisite, max(1, (int)$unlocked[$id])); + } + $completionTime = max(1, $latestPrerequisite ?: $now); + if (!isset($unlocked[COMPLETIONIST_ID])) $unlocked[COMPLETIONIST_ID] = $completionTime; + else $unlocked[COMPLETIONIST_ID] = max((int)$unlocked[COMPLETIONIST_ID], $completionTime); +} + +function normalize_client_unlock_time(mixed $value, int $now): int { + if (!is_int($value) && !is_float($value) && !is_string($value)) return $now; + if (!is_numeric($value)) return $now; + $numeric = (float)$value; + if (!is_finite($numeric) || $numeric <= 0) return $now; + // Browser timestamps are milliseconds; legacy/server timestamps are seconds. + if ($numeric >= 100000000000.0) $numeric /= 1000.0; + $seconds = (int)floor($numeric); + // Reject implausible/future values, but preserve valid offline unlock times. + if ($seconds < 946684800 || $seconds > $now + 300) return $now; + return $seconds; +} + +function apply_summary_delta(array &$summary, array $before, array $after): void { + foreach (ACHIEVEMENT_IDS as $id) { + $had = isset($before[$id]); + $has = isset($after[$id]); + if ($had === $has) continue; + $summary['counts'][$id] = max(0, (int)$summary['counts'][$id] + ($has ? 1 : -1)); + } +} + +function maybe_qualify(array &$player, array &$summary, int $now): bool { + if ($player['qualified']) return false; + if ((int)$player['activityCount'] < QUALIFY_MIN_ACTIVITY) return false; + if ($now - (int)$player['firstSeen'] < QUALIFY_MIN_AGE_SECONDS) return false; + $player['qualified'] = true; + $summary['totalPlayers'] = max(0, (int)$summary['totalPlayers'] + 1); + foreach (array_keys($player['unlocked']) as $id) $summary['counts'][$id] = max(0, (int)$summary['counts'][$id] + 1); + return true; +} + +function public_summary(array $summary, ?array $player = null): array { + $total = max(0, (int)$summary['totalPlayers']); + $achievements = []; + foreach (ACHIEVEMENT_IDS as $id) { + $count = max(0, min($total, (int)($summary['counts'][$id] ?? 0))); + $achievements[$id] = [ + 'unlockedPlayers' => $count, + 'percentage' => $total > 0 ? round($count * 100 / $total, 1) : 0.0, + ]; + } + $out = ['ok' => true, 'totalPlayers' => $total, 'achievements' => $achievements, 'statisticsTrust' => 'client-reported']; + if ($player !== null) { + $out['qualified'] = (bool)($player['qualified'] ?? false); + $out['playerGeneration'] = max(0, (int)($player['generation'] ?? 0)); + // Return the authenticated player's grow-only set. The client uploads + // its offline snapshot first, then merges this atomic union response. + $out['playerUnlocked'] = (object)(is_array($player['unlocked'] ?? null) ? $player['unlocked'] : []); + $out['playerProgress'] = normalize_progress_state($player['progressState'] ?? null); + } + return $out; +} + +function enforce_rate_limit(string $root, string $scope, int $limit): void { + $now = time(); + $hash = hash('sha256', $scope); + $path = $root . DIRECTORY_SEPARATOR . 'rate' . DIRECTORY_SEPARATOR . substr($hash, 0, 2) . DIRECTORY_SEPARATOR . $hash . '.json'; + ensure_directory(dirname($path)); + $lockPath = $path . '.lock'; + with_lock($lockPath, LOCK_EX, function () use ($path, $now, $limit): void { + $state = read_json_file($path, ['window' => $now, 'count' => 0]); + $window = (int)($state['window'] ?? $now); + $count = (int)($state['count'] ?? 0); + if ($now - $window >= RATE_WINDOW_SECONDS) { $window = $now; $count = 0; } + $count++; + if ($count > $limit) respond(['ok' => false, 'error' => 'rate_limited', 'retryAfter' => max(1, RATE_WINDOW_SECONDS - ($now - $window))], 429); + atomic_write_json($path, ['window' => $window, 'count' => $count]); + }); +} + +function claim_identity_issue_slot(string $root, string $ip): void { + $now = time(); + $hash = hash('sha256', 'identity:' . $ip); + $path = $root . DIRECTORY_SEPARATOR . 'identity-rate' . DIRECTORY_SEPARATOR . substr($hash, 0, 2) . DIRECTORY_SEPARATOR . $hash . '.json'; + with_lock($path . '.lock', LOCK_EX, function () use ($path, $now): void { + $state = read_json_file($path, ['window' => $now, 'count' => 0]); + $window = max(1, (int)($state['window'] ?? $now)); + $count = max(0, (int)($state['count'] ?? 0)); + if ($now - $window >= IDENTITY_ISSUE_WINDOW_SECONDS) { $window = $now; $count = 0; } + if ($count >= IDENTITY_ISSUE_LIMIT_PER_IP) { + respond([ + 'ok' => false, + 'error' => 'identity_creation_limited', + 'retryAfter' => max(1, IDENTITY_ISSUE_WINDOW_SECONDS - ($now - $window)), + ], 429); + } + atomic_write_json($path, ['window' => $window, 'count' => $count + 1]); + }); +} + +function random_uuid_v4(): string { + $bytes = random_bytes(16); + $bytes[6] = chr((ord($bytes[6]) & 0x0f) | 0x40); + $bytes[8] = chr((ord($bytes[8]) & 0x3f) | 0x80); + $hex = bin2hex($bytes); + return substr($hex, 0, 8) . '-' . substr($hex, 8, 4) . '-' . substr($hex, 12, 4) . '-' . substr($hex, 16, 4) . '-' . substr($hex, 20, 12); +} + +function session_signing_key(string $root): string { + $path = $root . DIRECTORY_SEPARATOR . 'session-key.json'; + return with_lock($path . '.lock', LOCK_EX, function () use ($path): string { + $state = read_json_file($path, []); + $hex = strtolower((string)($state['key'] ?? '')); + if (preg_match('/^[0-9a-f]{64}$/', $hex) !== 1) { + $hex = bin2hex(random_bytes(32)); + atomic_write_json($path, ['key' => $hex]); + } + $key = hex2bin($hex); + if (!is_string($key) || strlen($key) !== 32) throw new RuntimeException('storage_corrupt'); + return $key; + }); +} + +function make_session_cookie(string $root, string $playerId, string $secret): string { + $payload = strtolower($playerId) . '.' . strtolower($secret); + return $payload . '.' . hash_hmac('sha256', $payload, session_signing_key($root)); +} + +function read_session_cookie(string $root): ?array { + $token = strtolower((string)($_COOKIE[SESSION_COOKIE_NAME] ?? '')); + $parts = explode('.', $token); + if (count($parts) !== 3) return null; + [$playerId, $secret, $mac] = $parts; + if (!valid_player_id($playerId) || !valid_player_secret($secret) || preg_match('/^[0-9a-f]{64}$/', $mac) !== 1) return null; + $payload = $playerId . '.' . $secret; + $expected = hash_hmac('sha256', $payload, session_signing_key($root)); + return hash_equals($expected, $mac) ? ['playerId' => $playerId, 'playerSecret' => $secret] : null; +} + +function set_session_cookie(string $root, string $playerId, string $secret): void { + $secure = (!empty($_SERVER['HTTPS']) && strtolower((string)$_SERVER['HTTPS']) !== 'off'); + setcookie(SESSION_COOKIE_NAME, make_session_cookie($root, $playerId, $secret), [ + 'expires' => time() + SESSION_COOKIE_MAX_AGE, + 'path' => '/', + 'secure' => $secure, + 'httponly' => true, + 'samesite' => 'Strict', + ]); +} + +function stored_owner_matches(string $root, string $playerId, string $secret): bool { + $path = player_path($root, $playerId); + if (!is_file($path)) return false; + try { + $player = normalize_player(read_json_file($path, []), $playerId); + } catch (RuntimeException) { + return false; + } + $stored = (string)($player['ownerHash'] ?? ''); + return $stored !== '' && hash_equals($stored, hash('sha256', strtolower($secret))); +} + +function resolve_session_credentials(string $root, string $submittedPlayerId, string $submittedSecret, string $legacyPlayerId): array { + if (valid_legacy_player_id($legacyPlayerId) && valid_player_secret($submittedSecret)) { + $migratedPlayerId = legacy_player_uuid($legacyPlayerId); + $path = player_path($root, $migratedPlayerId); + if (is_file($path)) { + $raw = read_json_file($path, []); + $claimHash = strtolower((string)($raw['legacyClaimHash'] ?? '')); + if ($claimHash !== '' && hash_equals($claimHash, hash('sha256', $legacyPlayerId))) { + $ownerHash = strtolower((string)($raw['ownerHash'] ?? '')); + $submittedOwnerHash = hash('sha256', strtolower($submittedSecret)); + if ($ownerHash !== '' && !hash_equals($ownerHash, $submittedOwnerHash)) { + // A valid durable identity or HttpOnly cookie must remain a + // recovery path even when stale legacy-ID storage survived + // but its generated secret did not. Otherwise the stale + // legacy value permanently blocks an already-authenticated + // browser before cookie recovery is considered. + if (valid_player_id($submittedPlayerId) && valid_player_secret($submittedSecret) + && stored_owner_matches($root, strtolower($submittedPlayerId), strtolower($submittedSecret))) { + return [ + 'playerId' => strtolower($submittedPlayerId), + 'playerSecret' => strtolower($submittedSecret), + 'created' => false, + ]; + } + $cookie = read_session_cookie($root); + if ($cookie !== null && stored_owner_matches($root, $cookie['playerId'], $cookie['playerSecret'])) { + return [ + 'playerId' => $cookie['playerId'], + 'playerSecret' => $cookie['playerSecret'], + 'created' => false, + ]; + } + respond(['ok' => false, 'error' => 'legacy_player_already_claimed'], 403); + } + return [ + 'playerId' => $migratedPlayerId, + 'playerSecret' => strtolower($submittedSecret), + 'created' => false, + 'legacyClaimId' => $legacyPlayerId, + ]; + } + } + } + if (valid_player_id($submittedPlayerId) && valid_player_secret($submittedSecret) + && stored_owner_matches($root, strtolower($submittedPlayerId), strtolower($submittedSecret))) { + return ['playerId' => strtolower($submittedPlayerId), 'playerSecret' => strtolower($submittedSecret), 'created' => false]; + } + $cookie = read_session_cookie($root); + if ($cookie !== null && stored_owner_matches($root, $cookie['playerId'], $cookie['playerSecret'])) { + return ['playerId' => $cookie['playerId'], 'playerSecret' => $cookie['playerSecret'], 'created' => false]; + } + claim_identity_issue_slot($root, client_ip()); + return ['playerId' => random_uuid_v4(), 'playerSecret' => bin2hex(random_bytes(32)), 'created' => true]; +} + +$method = strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET')); if (!in_array($method, ['GET', 'POST'], true)) respond(['ok' => false, 'error' => 'method_not_allowed'], 405); $payload = []; @@ -377,137 +1033,195 @@ if ($method === 'POST') { if ($declaredLength > MAX_REQUEST_BYTES) respond(['ok' => false, 'error' => 'request_too_large'], 413); $raw = file_get_contents('php://input', false, null, 0, MAX_REQUEST_BYTES + 1); if (!is_string($raw) || strlen($raw) > MAX_REQUEST_BYTES) respond(['ok' => false, 'error' => 'request_too_large'], 413); - try { - $decoded = json_decode($raw, true, 64, JSON_THROW_ON_ERROR); - } catch (JsonException) { - respond(['ok' => false, 'error' => 'invalid_json'], 400); - } + try { $decoded = json_decode($raw, true, 64, JSON_THROW_ON_ERROR); } + catch (JsonException) { respond(['ok' => false, 'error' => 'invalid_json'], 400); } if (!is_array($decoded)) respond(['ok' => false, 'error' => 'invalid_json'], 400); $payload = $decoded; } -$action = $method === 'POST' - ? (string)($payload['action'] ?? '') - : (string)($_GET['action'] ?? 'summary'); -$playerId = $method === 'POST' - ? (string)($payload['playerId'] ?? '') - : (string)($_GET['playerId'] ?? ''); +$action = $method === 'POST' ? (string)($payload['action'] ?? '') : (string)($_GET['action'] ?? 'summary'); +if (!in_array($action, ['session', 'sync', 'reset', 'summary'], true)) respond(['ok' => false, 'error' => 'invalid_action'], 400); +if ($method === 'GET' && $action !== 'summary') respond(['ok' => false, 'error' => 'method_not_allowed'], 405); -if (!in_array($action, ['session', 'unlock', 'sync', 'reset', 'summary'], true)) { - respond(['ok' => false, 'error' => 'invalid_action'], 400); -} -if ($method === 'GET' && $action !== 'summary') { - respond(['ok' => false, 'error' => 'method_not_allowed'], 405); -} -if (!valid_player_id($playerId)) { - respond(['ok' => false, 'error' => 'invalid_player'], 400); -} -$playerId = strtolower($playerId); -$syncUnlocks = []; -$completionistEligible = null; -if ($action === 'unlock') { - $achievementId = (string)($payload['achievementId'] ?? ''); - if (!in_array($achievementId, ACHIEVEMENT_IDS, true)) { - respond(['ok' => false, 'error' => 'invalid_achievement'], 400); - } -} elseif ($action === 'sync') { - $submittedUnlocks = $payload['unlocked'] ?? null; - if (!is_array($submittedUnlocks) || count($submittedUnlocks) > count(ACHIEVEMENT_IDS)) { - respond(['ok' => false, 'error' => 'invalid_unlocks'], 400); - } - if (array_key_exists('completionistEligible', $payload)) { - if (!is_bool($payload['completionistEligible'])) { - respond(['ok' => false, 'error' => 'invalid_completionist_state'], 400); - } - $completionistEligible = $payload['completionistEligible']; - } - foreach ($submittedUnlocks as $achievementId => $timestamp) { - if (!is_string($achievementId) || !in_array($achievementId, ACHIEVEMENT_IDS, true)) { - respond(['ok' => false, 'error' => 'invalid_achievement'], 400); - } - if (!is_int($timestamp) && !is_float($timestamp) && !is_string($timestamp)) { - respond(['ok' => false, 'error' => 'invalid_timestamp'], 400); - } - $numericTimestamp = filter_var($timestamp, FILTER_VALIDATE_FLOAT); - if ($numericTimestamp === false || !is_finite((float)$numericTimestamp) || $numericTimestamp <= 0) { - respond(['ok' => false, 'error' => 'invalid_timestamp'], 400); - } - $syncUnlocks[$achievementId] = (float)$numericTimestamp; - } - if ($completionistEligible === false) unset($syncUnlocks['true_tarinai_observer']); -} - -$dataDir = __DIR__ . DIRECTORY_SEPARATOR . DATA_DIR_NAME; -if (!is_dir($dataDir) && !mkdir($dataDir, 0775, true) && !is_dir($dataDir)) { - respond(['ok' => false, 'error' => 'storage_unavailable'], 503); -} -$dataPath = $dataDir . DIRECTORY_SEPARATOR . DATA_FILE_NAME; -$lockPath = $dataDir . DIRECTORY_SEPARATOR . LOCK_FILE_NAME; -$lockHandle = @fopen($lockPath, 'c'); -if ($lockHandle === false || !flock($lockHandle, LOCK_EX)) { - if (is_resource($lockHandle)) fclose($lockHandle); - respond(['ok' => false, 'error' => 'storage_locked'], 503); -} - -$summary = null; -$storageError = null; try { - $contents = is_file($dataPath) ? file_get_contents($dataPath) : ''; - if ($contents === false) throw new RuntimeException('storage_unavailable'); - [$state, $sourceFormat] = decode_stored_state($contents); - $now = time(); - $mutatesPlayer = $action !== 'summary'; - - if ($mutatesPlayer) { - $player = isset($state['players'][$playerId]) && is_array($state['players'][$playerId]) - ? $state['players'][$playerId] - : ['firstSeen' => $now]; - $player['lastSeen'] = $now; - $submittedGameVersion = substr((string)($payload['gameVersion'] ?? ''), 0, 32); - if ($submittedGameVersion !== '' || !isset($player['gameVersion'])) $player['gameVersion'] = $submittedGameVersion; - $state['players'][$playerId] = $player; - } - - if ($action === 'unlock') { - $achievementId = (string)$payload['achievementId']; - if (!isset($state['unlocks'][$achievementId]) || !is_array($state['unlocks'][$achievementId])) { - $state['unlocks'][$achievementId] = []; - } - if (!isset($state['unlocks'][$achievementId][$playerId])) { - $state['unlocks'][$achievementId][$playerId] = $now; - } - } elseif ($action === 'sync') { - if ($completionistEligible === false && isset($state['unlocks']['true_tarinai_observer'][$playerId])) { - unset($state['unlocks']['true_tarinai_observer'][$playerId]); - } - foreach ($syncUnlocks as $achievementId => $submittedTimestamp) { - if (!isset($state['unlocks'][$achievementId]) || !is_array($state['unlocks'][$achievementId])) { - $state['unlocks'][$achievementId] = []; - } - if (isset($state['unlocks'][$achievementId][$playerId])) continue; - $timestampSeconds = $submittedTimestamp >= 100000000000 - ? (int)floor($submittedTimestamp / 1000) - : (int)floor($submittedTimestamp); - $state['unlocks'][$achievementId][$playerId] = max(1, min($now, $timestampSeconds)); - } - } elseif ($action === 'reset') { - foreach ($state['unlocks'] as $achievementId => $records) { - if (is_array($records)) unset($state['unlocks'][$achievementId][$playerId]); - } - } - - $encoded = encode_compact_state($state); - if (trim($contents) !== $encoded || $sourceFormat !== 'v3' || $mutatesPlayer) { - atomic_write_state($dataPath, $encoded); - } - $summary = build_summary($state); + $root = data_root(); + protect_data_root($root); + $summaryPath = $root . DIRECTORY_SEPARATOR . 'summary.json'; + $globalLock = $root . DIRECTORY_SEPARATOR . 'summary.lock'; + with_lock($globalLock, LOCK_EX, fn() => migrate_legacy_compact_state_v4($root, $summaryPath)); } catch (RuntimeException $error) { - $known = ['storage_corrupt', 'storage_unavailable', 'storage_write_failed', 'storage_encode_failed']; - $storageError = in_array($error->getMessage(), $known, true) ? $error->getMessage() : 'storage_unavailable'; -} finally { - flock($lockHandle, LOCK_UN); - fclose($lockHandle); + $known = [ + 'storage_corrupt', 'storage_unavailable', 'storage_write_failed', 'storage_encode_failed', 'storage_locked', + 'legacy_state_unreadable', 'legacy_state_invalid', 'legacy_catalog_mismatch', 'legacy_backup_failed', + 'legacy_player_collision', 'legacy_migration_verify_failed', + ]; + $message = in_array($error->getMessage(), $known, true) ? $error->getMessage() : 'storage_unavailable'; + respond(['ok' => false, 'error' => $message], 503); +} +if ($action === 'summary') { + enforce_rate_limit($root, 'ip:' . client_ip() . ':read', RATE_READ_LIMIT); +} elseif ($action === 'session') { + enforce_rate_limit($root, 'ip:' . client_ip() . ':session', RATE_SESSION_IP_LIMIT); +} else { + // Authenticated writes are primarily player-scoped. The high IP ceiling is + // only an abuse fuse and does not make a classroom share a 30-request pool. + enforce_rate_limit($root, 'ip:' . client_ip() . ':write-abuse', RATE_WRITE_IP_LIMIT); +} +if ($action === 'summary') { + try { + $result = with_lock($globalLock, LOCK_EX, fn() => public_summary(repair_summary_cache($root, $summaryPath))); + respond($result); + } catch (RuntimeException $error) { respond(['ok' => false, 'error' => $error->getMessage()], 503); } } -if ($storageError !== null) respond(['ok' => false, 'error' => $storageError], 503); -respond(is_array($summary) ? $summary : ['ok' => false, 'error' => 'storage_unavailable'], is_array($summary) ? 200 : 503); +$submittedPlayerId = strtolower((string)($payload['playerId'] ?? '')); +$submittedSecret = strtolower((string)($payload['playerSecret'] ?? '')); +$submittedLegacyPlayerId = (string)($payload['legacyPlayerId'] ?? ''); +$sessionCredentials = null; +if ($action === 'session') { + try { $sessionCredentials = resolve_session_credentials($root, $submittedPlayerId, $submittedSecret, $submittedLegacyPlayerId); } + catch (RuntimeException $error) { respond(['ok' => false, 'error' => $error->getMessage()], 503); } + $playerId = $sessionCredentials['playerId']; + $secret = $sessionCredentials['playerSecret']; +} else { + $playerId = $submittedPlayerId; + $secret = $submittedSecret; + if (!valid_player_id($playerId)) respond(['ok' => false, 'error' => 'invalid_player'], 400); + if (!valid_player_secret($secret)) respond(['ok' => false, 'error' => 'invalid_owner'], 403); + if (!is_file(player_path($root, $playerId))) respond(['ok' => false, 'error' => 'unknown_player'], 403); +} +enforce_rate_limit($root, 'player:' . $playerId, RATE_PLAYER_WRITE_LIMIT); +$clientGeneration = max(0, (int)($payload['generation'] ?? 0)); +$generationRecovery = (bool)($payload['generationRecovery'] ?? false); +$submittedUnlocks = []; +$submittedProgress = default_progress_state(); + +if ($action === 'sync') { + if ((int)($payload['syncProtocol'] ?? 0) !== SYNC_PROTOCOL_VERSION) { + respond(['ok' => false, 'error' => 'sync_protocol_upgrade_required', 'requiredProtocol' => SYNC_PROTOCOL_VERSION], 426); + } + if ((string)($payload['mergeMode'] ?? '') !== 'grow-only-union-v5') { + respond(['ok' => false, 'error' => 'invalid_merge_mode'], 400); + } + $rawUnlocks = $payload['unlocked'] ?? null; + if (!is_array($rawUnlocks) || count($rawUnlocks) > count(ACHIEVEMENT_IDS)) respond(['ok' => false, 'error' => 'invalid_unlocks'], 400); + if ((bool)($payload['replace'] ?? false)) respond(['ok' => false, 'error' => 'destructive_sync_disabled'], 409); + $rawProgress = $payload['progressState'] ?? null; + if (!is_array($rawProgress)) respond(['ok' => false, 'error' => 'invalid_progress'], 400); + $submittedProgress = normalize_progress_state($rawProgress); + $receivedAt = time(); + foreach ($rawUnlocks as $id => $timestamp) { + if (!is_string($id) || !in_array($id, ACHIEVEMENT_IDS, true)) respond(['ok' => false, 'error' => 'invalid_achievement'], 400); + if ($id === COMPLETIONIST_ID) continue; // completionist is always server-derived. + $submittedUnlocks[$id] = normalize_client_unlock_time($timestamp, $receivedAt); + } +} +if ($action === 'reset') { + if ((int)($payload['syncProtocol'] ?? 0) !== SYNC_PROTOCOL_VERSION) { + respond(['ok' => false, 'error' => 'sync_protocol_upgrade_required', 'requiredProtocol' => SYNC_PROTOCOL_VERSION], 426); + } + if ((string)($payload['confirmReset'] ?? '') !== 'RESET_ACHIEVEMENTS') respond(['ok' => false, 'error' => 'reset_confirmation_required'], 409); + if ((string)($payload['catalogRevision'] ?? '') !== CATALOG_REVISION) respond(['ok' => false, 'error' => 'catalog_mismatch'], 409); +} + +try { + $result = with_lock($globalLock, LOCK_EX, function () use ($root, $summaryPath, $playerId, $secret, $payload, $action, $submittedUnlocks, $submittedProgress, $sessionCredentials, $clientGeneration, $generationRecovery): array { + $now = time(); + $summary = default_summary(); + $path = player_path($root, $playerId); + $exists = is_file($path); + if (!$exists && $action !== 'session') respond(['ok' => false, 'error' => 'unknown_player'], 403); + $ownerHash = hash('sha256', $secret); + $player = $exists ? normalize_player(read_json_file($path, []), $playerId) : default_player($playerId, $ownerHash, $now); + $legacyClaimId = (string)($sessionCredentials['legacyClaimId'] ?? ''); + if ($action === 'session' && $legacyClaimId !== '') { + $expectedClaimHash = hash('sha256', $legacyClaimId); + if (!hash_equals((string)($player['legacyClaimHash'] ?? ''), $expectedClaimHash)) { + respond(['ok' => false, 'error' => 'legacy_claim_invalid'], 403); + } + $storedOwnerHash = (string)($player['ownerHash'] ?? ''); + if ($storedOwnerHash !== '' && !hash_equals($storedOwnerHash, $ownerHash)) { + respond(['ok' => false, 'error' => 'legacy_player_already_claimed'], 403); + } + $player['ownerHash'] = $ownerHash; + if ((int)($player['legacyClaimedAt'] ?? 0) <= 0) $player['legacyClaimedAt'] = $now; + } + verify_owner($player, $secret); + + $beforeQualified = (bool)$player['qualified']; + $beforeUnlocks = $player['unlocked']; + $serverGeneration = max(0, (int)($player['generation'] ?? 0)); + + if ($action === 'sync') { + if ($clientGeneration < $serverGeneration) { + $summary = repair_summary_cache($root, $summaryPath); + $error = public_summary($summary, $player); + $error['ok'] = false; + $error['error'] = 'stale_generation'; + respond($error, 409); + } + if ($clientGeneration > $serverGeneration) { + if (!$generationRecovery) { + $summary = repair_summary_cache($root, $summaryPath); + $error = public_summary($summary, $player); + $error['ok'] = false; + $error['error'] = 'generation_ahead'; + respond($error, 409); + } + // A locally durable newer generation is authoritative after a + // server backup restore or a newly-issued replacement identity. + $player['generation'] = $clientGeneration; + $player['unlocked'] = []; + $player['progressState'] = default_progress_state(); + $serverGeneration = $clientGeneration; + } + } + + $player['lastSeen'] = $now; + $player['activityCount'] = max(0, (int)$player['activityCount']) + 1; + $version = substr((string)($payload['gameVersion'] ?? ''), 0, 32); + if ($version !== '') $player['gameVersion'] = $version; + + if ($action === 'sync') { + $player['progressState'] = merge_progress_state($player['progressState'] ?? null, $submittedProgress); + foreach ($submittedUnlocks as $id => $submittedAt) { + if (!isset($player['unlocked'][$id])) $player['unlocked'][$id] = $submittedAt; + else $player['unlocked'][$id] = min((int)$player['unlocked'][$id], $submittedAt); + } + // Cumulative achievements are independently reconstructed from the + // merged progress CRDT, so 99 actions on one device plus 1 on + // another unlocks exactly once without trusting request ordering. + reconcile_progress_unlocks($player['unlocked'], $player['progressState'], $now); + } elseif ($action === 'reset') { + // The client generation is the target generation. Equal or older + // reset requests are already-processed retries and must be no-ops. + if ($clientGeneration > $serverGeneration) { + $player['generation'] = $clientGeneration; + $player['unlocked'] = []; + $player['progressState'] = default_progress_state(); + } + } + reconcile_completionist($player['unlocked'], $now); + + if ($beforeQualified) apply_summary_delta($summary, $beforeUnlocks, $player['unlocked']); + maybe_qualify($player, $summary, $now); + + atomic_write_json($path, $player); + $summary = repair_summary_cache($root, $summaryPath); + $public = public_summary($summary, $player); + if ($action === 'session') { + $public['playerId'] = $playerId; + $public['playerSecret'] = $secret; + $public['serverIssued'] = (bool)($sessionCredentials['created'] ?? false); + $public['legacyClaimed'] = (string)($sessionCredentials['legacyClaimId'] ?? '') !== ''; + } + return $public; + }); + if ($action === 'session') set_session_cookie($root, $playerId, $secret); + respond($result); + +} catch (RuntimeException $error) { + $known = ['storage_corrupt', 'storage_unavailable', 'storage_write_failed', 'storage_encode_failed', 'storage_locked']; + $message = in_array($error->getMessage(), $known, true) ? $error->getMessage() : 'storage_unavailable'; + respond(['ok' => false, 'error' => $message], 503); +} diff --git a/app_manifest.json b/app_manifest.json index 48459a8..1f598cf 100644 --- a/app_manifest.json +++ b/app_manifest.json @@ -1,5 +1,5 @@ { - "version": "39.16.98", + "version": "39.18.18", "css": [ "css/base.css", "css/layout.css", @@ -58,6 +58,7 @@ "js/item_dynamic_duplicator_system.js", "js/item_dynamic_pin_system.js", "js/item_dynamic_zunchi_system.js", + "js/item_environment_hazard_system.js", "js/item_dynamic_system.js", "js/item_lifecycle_decay_system.js", "js/item_lifecycle_growth_system.js", @@ -69,6 +70,7 @@ "js/item_lifecycle_pipeline.js", "js/item_runtime.js", "js/structure_lifecycle.js", + "js/memorial_bell_system.js", "js/item_render_helpers.js", "js/item_render_runtime.js", "js/burn_motion_util.js", @@ -148,6 +150,7 @@ "js/text_catalog.js", "js/ui.js", "js/game_dialogs.js", + "js/achievement_catalog.js", "js/achievements.js", "js/ui_helpers.js", "js/ui_log.js", diff --git a/assets/objects/mamekusaredake.png b/assets/objects/mamekusaredake.png new file mode 100644 index 0000000..254f5b2 Binary files /dev/null and b/assets/objects/mamekusaredake.png differ diff --git a/assets/sounds/achievement_unlock.mp3 b/assets/sounds/achievement_unlock.mp3 new file mode 100644 index 0000000..9d814a7 Binary files /dev/null and b/assets/sounds/achievement_unlock.mp3 differ diff --git a/assets/sounds/acquired_stress_001.wav b/assets/sounds/acquired_stress_001.wav new file mode 100644 index 0000000..81ca9c2 Binary files /dev/null and b/assets/sounds/acquired_stress_001.wav differ diff --git a/assets/sounds/acquired_stress_002.wav b/assets/sounds/acquired_stress_002.wav new file mode 100644 index 0000000..fea55d0 Binary files /dev/null and b/assets/sounds/acquired_stress_002.wav differ diff --git a/assets/sounds/acquired_stress_003.wav b/assets/sounds/acquired_stress_003.wav new file mode 100644 index 0000000..8f57321 Binary files /dev/null and b/assets/sounds/acquired_stress_003.wav differ diff --git a/assets/sounds/acquired_stress_004.wav b/assets/sounds/acquired_stress_004.wav new file mode 100644 index 0000000..110d484 Binary files /dev/null and b/assets/sounds/acquired_stress_004.wav differ diff --git a/assets/sounds/acquired_stress_005.wav b/assets/sounds/acquired_stress_005.wav new file mode 100644 index 0000000..eee7794 Binary files /dev/null and b/assets/sounds/acquired_stress_005.wav differ diff --git a/assets/sounds/acquired_stress_006.wav b/assets/sounds/acquired_stress_006.wav new file mode 100644 index 0000000..9311ed7 Binary files /dev/null and b/assets/sounds/acquired_stress_006.wav differ diff --git a/assets/sounds/acquired_stress_007.wav b/assets/sounds/acquired_stress_007.wav new file mode 100644 index 0000000..dd56594 Binary files /dev/null and b/assets/sounds/acquired_stress_007.wav differ diff --git a/assets/sounds/acquired_stress_008.wav b/assets/sounds/acquired_stress_008.wav new file mode 100644 index 0000000..9585451 Binary files /dev/null and b/assets/sounds/acquired_stress_008.wav differ diff --git a/assets/sounds/acquired_stress_009.wav b/assets/sounds/acquired_stress_009.wav new file mode 100644 index 0000000..f6c07dc Binary files /dev/null and b/assets/sounds/acquired_stress_009.wav differ diff --git a/assets/sounds/acquired_tarinai/001_縺壹s縺繧ゅs・医ヮ繝シ繝槭Ν・雲繝代ヱ縺壹s縺ッ縺ゥ縺薙↑縺ョ窶ヲ(1).wav b/assets/sounds/acquired_tarinai/001_縺壹s縺繧ゅs・医ヮ繝シ繝槭Ν・雲繝代ヱ縺壹s縺ッ縺ゥ縺薙↑縺ョ窶ヲ(1).wav new file mode 100644 index 0000000..81ca9c2 Binary files /dev/null and b/assets/sounds/acquired_tarinai/001_縺壹s縺繧ゅs・医ヮ繝シ繝槭Ν・雲繝代ヱ縺壹s縺ッ縺ゥ縺薙↑縺ョ窶ヲ(1).wav differ diff --git a/assets/sounds/acquired_tarinai/002_縺壹s縺繧ゅs・医ヮ繝シ繝槭Ν・雲繝槭・縺壹s縺ッ縺ゥ縺薙↑縺ョ窶ヲ(2).wav b/assets/sounds/acquired_tarinai/002_縺壹s縺繧ゅs・医ヮ繝シ繝槭Ν・雲繝槭・縺壹s縺ッ縺ゥ縺薙↑縺ョ窶ヲ(2).wav new file mode 100644 index 0000000..fea55d0 Binary files /dev/null and b/assets/sounds/acquired_tarinai/002_縺壹s縺繧ゅs・医ヮ繝シ繝槭Ν・雲繝槭・縺壹s縺ッ縺ゥ縺薙↑縺ョ窶ヲ(2).wav differ diff --git a/assets/sounds/acquired_tarinai/003_縺壹s縺繧ゅs・医ヮ繝シ繝槭Ν・雲縺薙s縺ェ縺ッ縺壹§繧・↑縺銀€ヲ(2).wav b/assets/sounds/acquired_tarinai/003_縺壹s縺繧ゅs・医ヮ繝シ繝槭Ν・雲縺薙s縺ェ縺ッ縺壹§繧・↑縺銀€ヲ(2).wav new file mode 100644 index 0000000..8f57321 Binary files /dev/null and b/assets/sounds/acquired_tarinai/003_縺壹s縺繧ゅs・医ヮ繝シ繝槭Ν・雲縺薙s縺ェ縺ッ縺壹§繧・↑縺銀€ヲ(2).wav differ diff --git a/assets/sounds/acquired_tarinai/004_縺壹s縺繧ゅs・医ヮ繝シ繝槭Ν・雲縺ゥ縺・@縺ヲ(2).wav b/assets/sounds/acquired_tarinai/004_縺壹s縺繧ゅs・医ヮ繝シ繝槭Ν・雲縺ゥ縺・@縺ヲ(2).wav new file mode 100644 index 0000000..110d484 Binary files /dev/null and b/assets/sounds/acquired_tarinai/004_縺壹s縺繧ゅs・医ヮ繝シ繝槭Ν・雲縺ゥ縺・@縺ヲ(2).wav differ diff --git a/assets/sounds/acquired_tarinai/005_縺壹s縺繧ゅs・医ヮ繝シ繝槭Ν・雲縺翫∪縺医r繧・k縺輔↑縺・€ヲ(2).wav b/assets/sounds/acquired_tarinai/005_縺壹s縺繧ゅs・医ヮ繝シ繝槭Ν・雲縺翫∪縺医r繧・k縺輔↑縺・€ヲ(2).wav new file mode 100644 index 0000000..eee7794 Binary files /dev/null and b/assets/sounds/acquired_tarinai/005_縺壹s縺繧ゅs・医ヮ繝シ繝槭Ν・雲縺翫∪縺医r繧・k縺輔↑縺・€ヲ(2).wav differ diff --git a/assets/sounds/acquired_tarinai/006_縺壹s縺繧ゅs・医ヮ繝シ繝槭Ν・雲縺ョ繧阪▲縺ヲ繧・k縺ョ縺(2).wav b/assets/sounds/acquired_tarinai/006_縺壹s縺繧ゅs・医ヮ繝シ繝槭Ν・雲縺ョ繧阪▲縺ヲ繧・k縺ョ縺(2).wav new file mode 100644 index 0000000..9311ed7 Binary files /dev/null and b/assets/sounds/acquired_tarinai/006_縺壹s縺繧ゅs・医ヮ繝シ繝槭Ν・雲縺ョ繧阪▲縺ヲ繧・k縺ョ縺(2).wav differ diff --git a/assets/sounds/bicycle_bell.mp3 b/assets/sounds/bicycle_bell.mp3 new file mode 100644 index 0000000..6fef91a Binary files /dev/null and b/assets/sounds/bicycle_bell.mp3 differ diff --git a/assets/sounds/intimidate_alt_001.wav b/assets/sounds/intimidate_alt_001.wav new file mode 100644 index 0000000..146764b Binary files /dev/null and b/assets/sounds/intimidate_alt_001.wav differ diff --git a/assets/sounds/ochibi_calm_001.wav b/assets/sounds/ochibi_calm_001.wav new file mode 100644 index 0000000..6ec4cb2 Binary files /dev/null and b/assets/sounds/ochibi_calm_001.wav differ diff --git a/assets/sounds/ochibi_calm_002.wav b/assets/sounds/ochibi_calm_002.wav new file mode 100644 index 0000000..f0bb63f Binary files /dev/null and b/assets/sounds/ochibi_calm_002.wav differ diff --git a/assets/sounds/ochibi_calm_003.wav b/assets/sounds/ochibi_calm_003.wav new file mode 100644 index 0000000..ec88928 Binary files /dev/null and b/assets/sounds/ochibi_calm_003.wav differ diff --git a/assets/sounds/ochibi_calm_004.wav b/assets/sounds/ochibi_calm_004.wav new file mode 100644 index 0000000..ee10326 Binary files /dev/null and b/assets/sounds/ochibi_calm_004.wav differ diff --git a/assets/sounds/ochibi_calm_005.wav b/assets/sounds/ochibi_calm_005.wav new file mode 100644 index 0000000..bd71d76 Binary files /dev/null and b/assets/sounds/ochibi_calm_005.wav differ diff --git a/assets/sounds/ochibi_calm_006.wav b/assets/sounds/ochibi_calm_006.wav new file mode 100644 index 0000000..1d5c55a Binary files /dev/null and b/assets/sounds/ochibi_calm_006.wav differ diff --git a/assets/sounds/ochibi_calm_007.wav b/assets/sounds/ochibi_calm_007.wav new file mode 100644 index 0000000..8606b70 Binary files /dev/null and b/assets/sounds/ochibi_calm_007.wav differ diff --git a/assets/sounds/ochibi_calm_008.wav b/assets/sounds/ochibi_calm_008.wav new file mode 100644 index 0000000..624d717 Binary files /dev/null and b/assets/sounds/ochibi_calm_008.wav differ diff --git a/assets/sounds/ochibi_calm_009.wav b/assets/sounds/ochibi_calm_009.wav new file mode 100644 index 0000000..8fbb49c Binary files /dev/null and b/assets/sounds/ochibi_calm_009.wav differ diff --git a/assets/sounds/ochibi_damage_001.wav b/assets/sounds/ochibi_damage_001.wav new file mode 100644 index 0000000..5a774bd Binary files /dev/null and b/assets/sounds/ochibi_damage_001.wav differ diff --git a/assets/sounds/ochibi_damage_002.wav b/assets/sounds/ochibi_damage_002.wav new file mode 100644 index 0000000..5f8fb15 Binary files /dev/null and b/assets/sounds/ochibi_damage_002.wav differ diff --git a/assets/sounds/ochibi_damage_003.wav b/assets/sounds/ochibi_damage_003.wav new file mode 100644 index 0000000..8ff254b Binary files /dev/null and b/assets/sounds/ochibi_damage_003.wav differ diff --git a/assets/sounds/ochibi_dirty_001.wav b/assets/sounds/ochibi_dirty_001.wav new file mode 100644 index 0000000..cdaf92b Binary files /dev/null and b/assets/sounds/ochibi_dirty_001.wav differ diff --git a/assets/sounds/ochibi_dirty_002.wav b/assets/sounds/ochibi_dirty_002.wav new file mode 100644 index 0000000..dfa73a9 Binary files /dev/null and b/assets/sounds/ochibi_dirty_002.wav differ diff --git a/assets/sounds/ochibi_dirty_003.wav b/assets/sounds/ochibi_dirty_003.wav new file mode 100644 index 0000000..8470f4a Binary files /dev/null and b/assets/sounds/ochibi_dirty_003.wav differ diff --git a/assets/sounds/ochibi_dirty_004.wav b/assets/sounds/ochibi_dirty_004.wav new file mode 100644 index 0000000..8d48ae6 Binary files /dev/null and b/assets/sounds/ochibi_dirty_004.wav differ diff --git a/assets/sounds/ochibi_disease_001.wav b/assets/sounds/ochibi_disease_001.wav new file mode 100644 index 0000000..f486513 Binary files /dev/null and b/assets/sounds/ochibi_disease_001.wav differ diff --git a/assets/sounds/ochibi_electric_006.wav b/assets/sounds/ochibi_electric_006.wav new file mode 100644 index 0000000..6706edc Binary files /dev/null and b/assets/sounds/ochibi_electric_006.wav differ diff --git a/assets/sounds/ochibi_fight_hit_004.wav b/assets/sounds/ochibi_fight_hit_004.wav new file mode 100644 index 0000000..b4c99fa Binary files /dev/null and b/assets/sounds/ochibi_fight_hit_004.wav differ diff --git a/assets/sounds/ochibi_hot_007.wav b/assets/sounds/ochibi_hot_007.wav new file mode 100644 index 0000000..9a334a0 Binary files /dev/null and b/assets/sounds/ochibi_hot_007.wav differ diff --git a/assets/sounds/ochibi_panic_005.wav b/assets/sounds/ochibi_panic_005.wav new file mode 100644 index 0000000..e8dbbf2 Binary files /dev/null and b/assets/sounds/ochibi_panic_005.wav differ diff --git a/assets/sounds/ochibi_sleep_002.wav b/assets/sounds/ochibi_sleep_002.wav new file mode 100644 index 0000000..24eba42 Binary files /dev/null and b/assets/sounds/ochibi_sleep_002.wav differ diff --git a/assets/sounds/ochibi_sleep_003.wav b/assets/sounds/ochibi_sleep_003.wav new file mode 100644 index 0000000..6ab4744 Binary files /dev/null and b/assets/sounds/ochibi_sleep_003.wav differ diff --git a/assets/sounds/ochibi_stress_008.wav b/assets/sounds/ochibi_stress_008.wav new file mode 100644 index 0000000..d0650a9 Binary files /dev/null and b/assets/sounds/ochibi_stress_008.wav differ diff --git a/assets/sprites/tarinai_40_intimidate_alt.webp b/assets/sprites/tarinai_40_intimidate_alt.webp new file mode 100644 index 0000000..07e2454 Binary files /dev/null and b/assets/sprites/tarinai_40_intimidate_alt.webp differ diff --git a/assets/sprites/tarinai_acquired_overlay.png b/assets/sprites/tarinai_acquired_overlay.png new file mode 100644 index 0000000..3afc640 Binary files /dev/null and b/assets/sprites/tarinai_acquired_overlay.png differ diff --git a/assets/ui/pwa-icon-192.png b/assets/ui/pwa-icon-192.png new file mode 100644 index 0000000..480d662 Binary files /dev/null and b/assets/ui/pwa-icon-192.png differ diff --git a/assets/ui/pwa-icon-512.png b/assets/ui/pwa-icon-512.png new file mode 100644 index 0000000..f84c2de Binary files /dev/null and b/assets/ui/pwa-icon-512.png differ diff --git a/assets/ui/tool_acquired_tarinai.webp b/assets/ui/tool_acquired_tarinai.webp new file mode 100644 index 0000000..1b23823 Binary files /dev/null and b/assets/ui/tool_acquired_tarinai.webp differ diff --git a/assets/ui/tool_mamekusaredake.webp b/assets/ui/tool_mamekusaredake.webp new file mode 100644 index 0000000..6b63693 Binary files /dev/null and b/assets/ui/tool_mamekusaredake.webp differ diff --git a/css/base.css b/css/base.css index 91b9d49..03a8520 100644 --- a/css/base.css +++ b/css/base.css @@ -78,10 +78,19 @@ button { min-width: 0; } +.room-links { + display: flex; + flex-direction: column; + align-items: stretch; + gap: 6px; + flex: 0 0 auto; +} + .room-link { text-decoration: none; white-space: nowrap; background: rgba(255,255,255,0.86); + text-align: center; } h1 { @@ -91,6 +100,11 @@ h1 { white-space: nowrap; } + +.speed-select-native { display: none; } +.speed-menu { position: relative; display: inline-block; } +.speed-menu-btn { min-width: 92px; text-align: center; white-space: nowrap; } + .top-actions { display: flex; gap: 6px; @@ -381,6 +395,7 @@ h1 { word-break: normal; overflow-wrap: anywhere; text-shadow: 0 1px 0 rgba(255,255,255,0.62); + white-space: pre-line; } .tool.tool-has-canvas-icon { --tool-icon: none; grid-template-columns: 31px minmax(0,1fr); min-height: 47px; padding-top: 4px; } diff --git a/css/components.css b/css/components.css index a13e84e..75daf0a 100644 --- a/css/components.css +++ b/css/components.css @@ -27,6 +27,9 @@ gap: 8px; flex-wrap: wrap; margin: 8px 0 4px; + position: relative; + z-index: 4; + isolation: isolate; } .favorite-toggle { border: 1px solid rgba(128, 102, 56, 0.32); @@ -34,8 +37,15 @@ background: rgba(255, 248, 221, 0.92); color: #5a4630; font-weight: 700; - padding: 5px 10px; + padding: 7px 12px; cursor: pointer; + position: relative; + z-index: 5; + display: block; + width: 100%; + box-sizing: border-box; + pointer-events: auto; + touch-action: manipulation; } .favorite-toggle.active { background: rgba(255, 229, 122, 0.95); @@ -335,13 +345,20 @@ border: 1px solid rgba(192, 138, 96, 0.24); background: rgba(255, 247, 239, 0.74); } +.event-category-heading { + margin-bottom: 7px; + font-size: 11px; + font-weight: 700; + color: rgba(82, 66, 52, 0.88); +} .push-master { display: flex; align-items: center; gap: 7px; font-size: 12px; font-weight: 700; - margin-bottom: 8px; + margin-top: 9px; + margin-bottom: 0; } .push-kind-grid { display: grid; @@ -419,6 +436,13 @@ .log-push-toast.log-push-weather::before { background: #7bbbdc; } .log-push-toast.log-push-grass::before { background: #8cc77a; } .log-push-toast.log-push-event::before { background: #8b82d6; } + +.log-push-toast.log-push-life::before { background: #82bd72; } +.log-push-toast.log-push-danger::before { background: #df845d; } +.log-push-toast.log-push-social::before { background: #b28bd0; } +.log-push-toast.log-push-living::before { background: #d7ad58; } +.log-push-toast.log-push-environment::before { background: #70aac8; } +.log-push-toast.log-push-observe::before { background: #9b9184; } .log-push-toast.leaving { animation: logPushOut .18s ease both; } @@ -667,6 +691,10 @@ gap: 5px; } .top-menu-panel.hidden { display: none; } +.speed-menu-panel { width: 116px; min-width: 116px; } +.speed-menu-panel .top-menu-item { text-align: center; } +.speed-menu-panel .top-menu-item.active, +.speed-menu-panel .top-menu-item[aria-checked="true"] { background: rgba(224,242,201,.92); } .top-menu-item { width: 100%; min-height: 38px; diff --git a/css/layout.css b/css/layout.css index 18545dc..d0f4064 100644 --- a/css/layout.css +++ b/css/layout.css @@ -25,6 +25,7 @@ .tool[data-tool="delete"] { --tool-icon-zoom: 1.42; } .tool[data-tool="area_delete"] { --tool-icon-zoom: 1; } .tool[data-tool="pinch"].tool-emoji-icon::before { font-size: 22px; } +.tool[data-tool="bell"].tool-emoji-icon::before { font-size: 21px; z-index: 1; } .tool[data-tool="area_delete"].tool-emoji-icon::before { font-size: 31px; line-height: 1; @@ -125,6 +126,7 @@ box-shadow: 0 1px 4px rgba(42,36,29,0.16); pointer-events: auto; cursor: pointer; + z-index: 4; } .chart-tabs { display: grid; grid-template-columns: repeat(3, 1fr); gap: 5px; margin: 3px 0 8px; } .chart-tabs button { border: 1px solid var(--line); background: rgba(255,255,255,0.62); border-radius: 999px; padding: 5px 4px; font-size: 11px; cursor: pointer; } @@ -295,9 +297,15 @@ meter { .log-grass { border-left-color: rgba(72, 148, 67, 0.68); } .log-weather { border-left-color: rgba(92, 142, 210, 0.62); } .log-relation { border-left-color: rgba(204, 126, 176, 0.62); } -.log-observe { border-left-color: rgba(175, 146, 86, 0.62); } .log-event { border-left-color: rgba(132, 120, 210, 0.62); } +.log-life { border-left-color: rgba(105, 166, 96, 0.68); } +.log-danger { border-left-color: rgba(214, 104, 70, 0.72); } +.log-social { border-left-color: rgba(184, 116, 184, 0.66); } +.log-living { border-left-color: rgba(183, 151, 74, 0.68); } +.log-environment { border-left-color: rgba(82, 142, 170, 0.66); } +.log-observe { border-left-color: rgba(142, 132, 116, 0.62); } + /* Clearer tool category grouping. */ .tool-category[data-tool-category="operate"] { --tool-cat-a: rgba(224,239,255,0.82); --tool-cat-b: rgba(203,226,255,0.74); --tool-cat-line: rgba(82,128,190,0.26); } .tool-category[data-tool-category="food"] { --tool-cat-a: rgba(236,252,219,0.82); --tool-cat-b: rgba(214,244,194,0.74); --tool-cat-line: rgba(96,156,72,0.26); } @@ -347,3 +355,7 @@ meter { border-color: rgba(38,132,190,0.56); box-shadow: inset 0 0 0 1px rgba(84,176,226,0.20), 0 8px 20px rgba(59,133,177,0.10); } + +.chart-range-tabs { display: grid; grid-template-columns: repeat(3, 1fr); gap: 5px; margin: -2px 0 7px; } +.chart-range-tabs button { border: 1px solid var(--line); background: rgba(255,255,255,0.48); border-radius: 8px; padding: 4px 4px; font-size: 10px; cursor: pointer; color: var(--muted); } +.chart-range-tabs button.active { background: rgba(239,255,222,0.92); border-color: rgba(103,178,44,0.42); color: var(--text); font-weight: 700; } diff --git a/css/mobile.css b/css/mobile.css index fa953da..9b35acf 100644 --- a/css/mobile.css +++ b/css/mobile.css @@ -429,3 +429,23 @@ body.touch-mobile-ui .tool-tip-popover.mobile-selection-tip { @media (max-width: 980px) { .top-actions { overflow-x: auto; overflow-y: hidden; } } + +/* Mobile toolbar: keep every primary action reachable without hidden horizontal overflow. */ +@media (max-width: 520px) { + .top-actions { + display: flex; + flex-wrap: wrap; + overflow: visible; + align-items: center; + } + .top-panel-search { + flex: 1 1 100%; + width: 100%; + min-width: 0; + } + .top-actions > .btn, + .top-actions > .top-menu, + .top-actions > .speed-menu { + flex: 0 1 auto; + } +} diff --git a/css/panel.css b/css/panel.css index 766acea..762f2c2 100644 --- a/css/panel.css +++ b/css/panel.css @@ -119,6 +119,14 @@ body::before { pointer-events: none; } + +.family-death-time { + display: block; + margin-top: 1px; + font-size: 10px; + line-height: 1.15; + color: rgba(93, 72, 61, 0.76); +} .family-genetic-stats { display: grid !important; grid-template-columns: repeat(2, minmax(0, 1fr)); @@ -260,8 +268,8 @@ body::before { .lineage-family-tree .tree-node { position: absolute; width: 150px; - height: 104px; - min-height: 104px; + height: 112px; + min-height: 112px; box-sizing: border-box; align-items: flex-start; background: linear-gradient(180deg, #fffdf8, #f8f1e5); @@ -280,6 +288,29 @@ body::before { .lineage-family-tree .tree-node[data-family-tarinai-id]:hover { transform: none; } +.lineage-family-tree.family-hover-active .tree-node.family-hover-dim { + opacity: 0.28; + filter: saturate(0.58); + transition: opacity .12s ease, filter .12s ease, box-shadow .12s ease, border-color .12s ease; +} +.lineage-family-tree.family-hover-active .tree-node.family-hover-focus, +.lineage-family-tree.family-hover-active .tree-node.family-hover-parent, +.lineage-family-tree.family-hover-active .tree-node.family-hover-child { + opacity: 1; + filter: none; +} +.lineage-family-tree.family-hover-active .tree-node.family-hover-focus { + border-color: rgba(124, 165, 66, 0.78); + box-shadow: 0 0 0 3px rgba(124, 165, 66, 0.16), 0 5px 13px rgba(64,48,32,0.10); +} +.lineage-family-tree.family-hover-active .tree-node.family-hover-parent { + border-color: rgba(80, 132, 198, 0.72); + box-shadow: 0 0 0 2px rgba(80, 132, 198, 0.14); +} +.lineage-family-tree.family-hover-active .tree-node.family-hover-child { + border-color: rgba(87, 170, 91, 0.72); + box-shadow: 0 0 0 2px rgba(87, 170, 91, 0.14); +} .lineage-family-tree .tree-node .family-portrait { right: 4px; top: 4px; @@ -319,7 +350,7 @@ body::before { /* Restored from the original ZIP: fixed colony graph/legend sizing. */ .colony-card { overflow: visible; min-height: 0; flex: 0 0 auto; } .colony-stats { - grid-template-columns: repeat(2, 1fr); + grid-template-columns: 1fr; margin-bottom: 8px; } .colony-chart { @@ -442,3 +473,12 @@ body::before { line-height: 9px !important; font-size: 6.8px !important; } + +.colony-chart { position: relative; } +.colony-chart-tooltip { position: fixed; z-index: 10020; pointer-events: none; min-width: 112px; max-width: 210px; padding: 7px 8px; border-radius: 9px; border: 1px solid rgba(80,65,48,0.18); background: rgba(255,252,245,0.98); color: #4d443a; box-shadow: 0 4px 14px rgba(64,48,30,0.16); font-size: 10px; line-height: 1.45; transform: none; } +.colony-chart-tooltip.hidden { display: none; } +.colony-chart-tooltip strong { display: block; margin-bottom: 3px; font-size: 10.5px; } +.colony-chart-tooltip-row { display: flex; justify-content: space-between; gap: 10px; white-space: nowrap; } +.colony-chart-hover-point { position: absolute; z-index: 5; width: 8px; height: 8px; border: 2px solid #5d8ee6; border-radius: 50%; background: rgba(255,255,255,0.96); box-shadow: 0 0 0 2px rgba(255,255,255,0.7); pointer-events: none; transform: translate(-50%, -50%); } +.colony-chart-hover-point.hidden { display: none; } + diff --git a/index.html b/index.html index c00fce4..09f28dc 100644 --- a/index.html +++ b/index.html @@ -4,14 +4,16 @@ たりない観察 - - - - - - - - + + + + + + + + + +
@@ -27,7 +29,10 @@
- 333の部屋に移動 +

たりない観察

@@ -40,17 +45,30 @@
- +
+ + + +
- + +
- @@ -159,19 +178,17 @@
-
- +
+
表示カテゴリ
- - - - - - - - - + + + + + +
+
@@ -202,7 +219,7 @@
たりない観察
-

実績 0 / 75

+

実績 0 / 77

@@ -293,173 +310,221 @@
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/js/achievement_catalog.js b/js/achievement_catalog.js new file mode 100644 index 0000000..875a9de --- /dev/null +++ b/js/achievement_catalog.js @@ -0,0 +1,731 @@ +window.TARINAI_ACHIEVEMENT_CATALOG = { + "revision": "2026-07-25-achievement-cleanup-v1", + "completionistId": "true_tarinai_observer", + "categories": [ + { + "id": "ecology", + "title": "生態" + }, + { + "id": "population", + "title": "人口" + }, + { + "id": "experiment", + "title": "実験" + }, + { + "id": "construction", + "title": "建築" + }, + { + "id": "operation", + "title": "操作" + }, + { + "id": "other", + "title": "その他" + } + ], + "medicineLedgerTypes": [ + "first_aid", + "sedative", + "sleep_drug", + "laxative", + "protein", + "niteropu", + "ammo", + "mystery_drug", + "mercury", + "giant_drug", + "dwarf_drug" + ], + "linkProgressTypes": [ + "rope", + "rod", + "spring" + ], + "additiveProgressCaps": { + "placementCount": 100, + "antKills": 100, + "birthCount": 3333, + "quickDeleteCount": 30, + "undoCount": 20, + "redoCount": 20, + "directFeedCount": 33, + "firstAidHeals": 50, + "fightMochiFightCount": 666, + "shotCount": 333, + "loveMochiBirthCount": 721, + "statsButtonPressCount": 30, + "totalDeathCount": 10000, + "manualTarinaiAddedCount": 100, + "robotCleanCount": 200 + }, + "definitions": [ + { + "id": "first_birth", + "title": "はじめての繁殖", + "description": "たりないの繁殖を1回成功させる。", + "category": "population", + "showLockedDescription": true, + "progress": { + "type": "counter", + "key": "birthCount", + "target": 1 + } + }, + { + "id": "natural_zunchi_slave", + "title": "ずんちどれい", + "description": "ずんちどれいが出現する。", + "category": "ecology", + "showLockedDescription": true + }, + { + "id": "ochibi_natural_slave", + "title": "たりないより「たりない」", + "description": "おちびが鎖無しでずんちどれいになる。", + "category": "ecology", + "showLockedDescription": true + }, + { + "id": "natural_tarinai_king", + "title": "たりない王", + "description": "たりない王が出現する。", + "category": "ecology", + "showLockedDescription": true + }, + { + "id": "self_zunchi_death", + "title": "あぁ^~ たまらねぇぜ", + "description": "おしり鋲を抜いた時、自分のずんちで自爆する。", + "category": "experiment", + "showLockedDescription": true + }, + { + "id": "zunchi_collision_death", + "title": "くちゃいのだ!", + "description": "ずんちとの衝突で死亡する個体が出現する。", + "category": "experiment", + "showLockedDescription": true + }, + { + "id": "natural_zunchi_slave_5_generations", + "title": "末代までの恥", + "description": "5代連続でずんちどれい(鎖なし)", + "category": "population", + "showLockedDescription": true + }, + { + "id": "natural_tarinai_king_3_generations", + "title": "華麗なる王族", + "description": "3代連続でたりない王(王冠なし)", + "category": "population", + "showLockedDescription": true + }, + { + "id": "death_50_in_10_seconds", + "title": "6番目の大量絶滅", + "description": "10秒以内に50体のたりないが死亡する。", + "category": "experiment", + "showLockedDescription": true + }, + { + "id": "birth_50_in_60_seconds", + "title": "ベビーブーム", + "description": "1分以内に30体のたりないが誕生する。", + "category": "population", + "showLockedDescription": true + }, + { + "id": "great_mother_1000_births", + "title": "母なる大地", + "description": "たりないを繁殖で累計3333体誕生させる。", + "category": "population", + "showLockedDescription": true, + "progress": { + "type": "counter", + "key": "birthCount", + "target": 3333, + "display": "percent", + "unit": "体" + } + }, + { + "id": "lifespan_completed", + "title": "天寿", + "description": "たりない1体が天寿を全うする。", + "category": "ecology", + "showLockedDescription": true + }, + { + "id": "soccer_ball_death", + "title": "豆野、殺ッカーやろうぜ!", + "description": "サッカーボールとの衝突で、たりない1体が死亡する。", + "category": "experiment", + "showLockedDescription": false + }, + { + "id": "fight_pair_danger_kill", + "title": "喧嘩両成敗", + "description": "喧嘩中のたりないを、両方とも危険カテゴリのアイテムで倒す。", + "category": "experiment", + "showLockedDescription": false + }, + { + "id": "all_non_sleep_diseased_25", + "title": "緊急事態宣言", + "description": "25体以上が存命し、フィールド上の全員がねむり病以外の病気にかかる。", + "category": "ecology", + "showLockedDescription": true + }, + { + "id": "colony_happy", + "title": "管理された楽園", + "description": "コロニー状態をしばらく「幸福」にする。", + "category": "ecology", + "showLockedDescription": true + }, + { + "id": "direct_feed_33", + "title": "餌やりじいさん", + "description": "手から直接33回餌を与える。", + "category": "ecology", + "showLockedDescription": false, + "progress": { + "type": "counter", + "key": "directFeedCount", + "target": 33 + } + }, + { + "id": "ignite_during_birth_ritual", + "title": "燃え上がる恋", + "description": "たりないがヘコヘコ中に着火する。", + "category": "experiment", + "showLockedDescription": false + }, + { + "id": "laxative_starvation", + "title": "内臓全部出た", + "description": "下剤の効果中に餓死する。", + "category": "experiment", + "showLockedDescription": true + }, + { + "id": "idle_observer_5_minutes", + "title": "監視カメラ", + "description": "3ゲーム日、操作せず画面を見るだけ", + "category": "operation", + "showLockedDescription": false + }, + { + "id": "placed_objects_100", + "title": "物でいっぱい", + "description": "配置物を累計100個置く。", + "category": "construction", + "showLockedDescription": false, + "progress": { + "type": "counter", + "key": "placementCount", + "target": 100 + } + }, + { + "id": "mechanized_industry", + "title": "機械化産業", + "description": "検知器の信号で接続先を作動させ、ロープ・棒・ばねをそれぞれ1本以上設置する。", + "category": "construction", + "showLockedDescription": false, + "progress": { + "type": "mechanized" + } + }, + { + "id": "safe_colony_25_5_minutes", + "title": "安全第一", + "description": "25体以上いる状態をゲーム内5分間維持し、その間寿命以外で死亡者を出さない。", + "category": "ecology", + "showLockedDescription": true + }, + { + "id": "ants_alive_25", + "title": "アリの惑星", + "description": "生存しているアリが25体に到達する。", + "category": "ecology", + "showLockedDescription": true + }, + { + "id": "ants_killed_100", + "title": "害虫駆除", + "description": "アリを累計100体倒す。", + "category": "experiment", + "showLockedDescription": false, + "progress": { + "type": "counter", + "key": "antKills", + "target": 100 + } + }, + { + "id": "secret_collection_9_slots", + "title": "秘密のコレクション", + "description": "セーブスロット9つをすべて埋める。", + "category": "operation", + "showLockedDescription": false + }, + { + "id": "pause_spam_4_in_1_second", + "title": "何やってるの?", + "description": "何もない部分を1秒間に4回連打する。", + "category": "operation", + "showLockedDescription": false + }, + { + "id": "continuous_play_1_hour", + "title": "めっちゃたりない観察", + "description": "1時間連続プレイする。", + "category": "other", + "showLockedDescription": true + }, + { + "id": "below_absolute_zero_item", + "title": "物理法則を下側に超越", + "description": "温度計算されるアイテムを1つ絶対零度を下回る温度にする。", + "category": "experiment", + "showLockedDescription": false + }, + { + "id": "undo_mass_revival", + "title": "見なかったことにしよう", + "description": "一度のUndoで10体以上の死亡をなかったことにする。", + "category": "operation", + "showLockedDescription": false + }, + { + "id": "robot_cleaner_100", + "title": "清掃業者", + "description": "ロボ掃除機にずんち・死骸・汚れを累計200個処理させる。", + "category": "construction", + "showLockedDescription": true, + "progress": { + "type": "counter", + "key": "robotCleanCount", + "target": 200, + "display": "count", + "unit": "個" + } + }, + { + "id": "held_30_seconds", + "title": "空中生活", + "description": "同じたりないを30秒間つまみ続ける。", + "category": "operation", + "showLockedDescription": false + }, + { + "id": "minimalist_happy", + "title": "ミニマリスト", + "description": "プレイ開始6日目以降、配置物を10個以下に抑えてコロニー状態を「幸福」にする。", + "category": "construction", + "showLockedDescription": false + }, + { + "id": "overprotective", + "title": "過保護", + "description": "同じたりないに手から10回餌を与え、3回以上薬で治療する。", + "category": "ecology", + "showLockedDescription": true + }, + { + "id": "self_sufficient", + "title": "自給自足", + "description": "複製機がない状態で、20体以上を直接給餌せず10分間維持する。", + "category": "ecology", + "showLockedDescription": false + }, + { + "id": "unplanned_city_30", + "title": "無計画都市", + "description": "配置後30秒以内に削除する操作を累計30回行う。", + "category": "construction", + "showLockedDescription": false, + "progress": { + "type": "counter", + "key": "quickDeleteCount", + "target": 30 + } + }, + { + "id": "sauna_cold_plunge", + "title": "サウナ水風呂", + "description": "暑すぎる状態になったたりないを、15秒以内に寒すぎる状態にする。", + "category": "experiment", + "showLockedDescription": false + }, + { + "id": "rain_shelter_all", + "title": "雨宿り完了", + "description": "雨天時、20体以上の全員をパラソル・巣箱・土管で雨宿りさせる。", + "category": "ecology", + "showLockedDescription": true + }, + { + "id": "medicine_ledger_all", + "title": "おくすり手帳全埋め", + "description": "全種類の薬を少なくとも1回使用する。", + "category": "ecology", + "showLockedDescription": false, + "progress": { + "type": "set", + "key": "medicineTypes", + "required": "medicineLedgerTypes" + } + }, + { + "id": "mercury_lifespan", + "title": "不老不死まであと一歩", + "description": "水銀を使用したたりないが天寿を全うする。", + "category": "experiment", + "showLockedDescription": true + }, + { + "id": "enemy_enemy_friend", + "title": "敵の敵は味方", + "description": "たりない30体以上を無傷で保ちながら、危険アイテムでアリを10体倒す。", + "category": "ecology", + "showLockedDescription": true + }, + { + "id": "revolution", + "title": "革命", + "description": "ずんちどれいが、たりない王を喧嘩で死亡させる。", + "category": "experiment", + "showLockedDescription": true + }, + { + "id": "fuel_to_fire", + "title": "火に油", + "description": "けんか餅を与えたたりないが30秒以内に喧嘩を始める。", + "category": "experiment", + "showLockedDescription": false + }, + { + "id": "undo_20", + "title": "やっぱなし", + "description": "Undoを累計20回成功させる。", + "category": "operation", + "showLockedDescription": false, + "progress": { + "type": "counter", + "key": "undoCount", + "target": 20 + } + }, + { + "id": "redo_20", + "title": "やっぱあり", + "description": "Redoを累計20回成功させる。", + "category": "operation", + "showLockedDescription": false, + "progress": { + "type": "counter", + "key": "redoCount", + "target": 20 + } + }, + { + "id": "eternal_history_generation_10", + "title": "悠久の歴史", + "description": "世代が10に到達する。", + "category": "population", + "showLockedDescription": true + }, + { + "id": "king_full_satisfaction", + "title": "五体満足", + "description": "たりない王1個体にプロテインと巨大薬の効果を同時に付与する。", + "category": "ecology", + "showLockedDescription": false + }, + { + "id": "slave_zero_satisfaction", + "title": "零体満足", + "description": "ずんちどれい1個体にンイテロプと矮小薬の効果を同時に付与する。", + "category": "ecology", + "showLockedDescription": false + }, + { + "id": "town_doctor_50", + "title": "町のお医者さん", + "description": "救急薬を累計50回使用し、体力を回復させる。", + "category": "ecology", + "showLockedDescription": true, + "progress": { + "type": "counter", + "key": "firstAidHeals", + "target": 50, + "display": "count", + "unit": "回" + } + }, + { + "id": "poke_plushie_fling", + "title": "割とふわふわ", + "description": "ぬいぐるみを「つつく」で弾き飛ばす。", + "category": "operation", + "showLockedDescription": false + }, + { + "id": "chaos_seeker_666_fights", + "title": "混沌ヲ希求スル者", + "description": "けんか餅の影響下で喧嘩を累計666回発生させる。", + "category": "experiment", + "showLockedDescription": true, + "progress": { + "type": "counter", + "key": "fightMochiFightCount", + "target": 666, + "display": "percent", + "unit": "回" + } + }, + { + "id": "clean_freak_robot_only", + "title": "潔癖症", + "description": "ロボット掃除機の設定全項目にチェックを入れて稼働させ、フィールド上にロボット掃除機以外を存在させない。", + "category": "construction", + "showLockedDescription": false + }, + { + "id": "true_tarinai_observer", + "title": "真・たりない観察", + "description": "これ以外の全ての実績を達成する。", + "category": "other", + "showLockedDescription": false + }, + { + "id": "sniper_333_shots", + "title": "狙撃手", + "description": "累計333発撃つ。", + "category": "operation", + "showLockedDescription": false, + "progress": { + "type": "counter", + "key": "shotCount", + "target": 333 + } + }, + { + "id": "megalopolis", + "title": "メガロポリス", + "description": "複製機を10個以上、干草寝床・巣箱・土管を合計15個以上設置し、たりないを100体以上生存させる。", + "category": "construction", + "showLockedDescription": true + }, + { + "id": "fertility_seeker_721_love_births", + "title": "豊穣ヲ希求スル者", + "description": "へこ餅の影響下で繁殖を721回成功させる。", + "category": "population", + "showLockedDescription": true, + "progress": { + "type": "counter", + "key": "loveMochiBirthCount", + "target": 721, + "display": "percent", + "unit": "回" + } + }, + { + "id": "low_fps_single_digit", + "title": "スペックがたりない", + "description": "fpsを1桁にする。", + "category": "other", + "showLockedDescription": true + }, + { + "id": "continuous_play_24_hours", + "title": "寝ろ", + "description": "24時間連続でプレイする。", + "category": "other", + "showLockedDescription": true + }, + { + "id": "sandbox_five_toilets", + "title": "砂場", + "description": "トイレの砂をフィールドに5個設置する。", + "category": "construction", + "showLockedDescription": false + }, + { + "id": "park_ground_changed", + "title": "そこ公共空間だよ?", + "description": "公園の地面を勝手に変更する。", + "category": "construction", + "showLockedDescription": false + }, + { + "id": "ground_change_4_in_1_second", + "title": "破格の工事費用", + "description": "地面を変えすぎて破産する。", + "category": "construction", + "showLockedDescription": false + }, + { + "id": "ant_nest_without_tarinai", + "title": "アリ観察", + "description": "アリの巣があるが、たりないがいない。", + "category": "ecology", + "showLockedDescription": false + }, + { + "id": "sticky_bomb_15_passes", + "title": "命のバトン", + "description": "粘着ボムを爆発までに15回以上パスする。", + "category": "experiment", + "showLockedDescription": false + }, + { + "id": "daily_play_7_days", + "title": "毎日たりない観察", + "description": "7日連続でプレイする。", + "category": "other", + "showLockedDescription": true, + "progress": { + "type": "value", + "key": "dailyPlayStreak", + "target": 7, + "display": "percent", + "unit": "日" + } + }, + { + "id": "wire_shock_7_tarinai", + "title": "抵抗器じゃない", + "description": "電流が流れている1本の電線で7体のたりないを感電させる。", + "category": "experiment", + "showLockedDescription": false + }, + { + "id": "information_industry", + "title": "情報化産業", + "description": "基盤同士を電線類でつなぎ、信号を流す。", + "category": "construction", + "showLockedDescription": false + }, + { + "id": "strength_in_numbers", + "title": "数こそ力", + "description": "生存しているたりないが100体に到達する。", + "category": "population", + "showLockedDescription": false + }, + { + "id": "elite_few", + "title": "少数精鋭", + "description": "たりないが25体以下の状態を5日間維持する。", + "category": "population", + "showLockedDescription": true + }, + { + "id": "zunchi_overflow", + "title": "踩屎感", + "description": "たりないが20体以上いる状態で、ずんちの数がたりないの数を上回る。", + "category": "ecology", + "showLockedDescription": false + }, + { + "id": "comfortable_beds", + "title": "快適な寝床", + "description": "生存している全てのたりないに行き渡る数の寝床を用意する。", + "category": "ecology", + "showLockedDescription": false + }, + { + "id": "stone_pillow", + "title": "石に枕す", + "description": "たりないが30体以上いる状態で、寝床充足率を0%にする。", + "category": "ecology", + "showLockedDescription": false + }, + { + "id": "across_seasons", + "title": "季節を越えて", + "description": "春夏秋冬の四季を一巡する。", + "category": "other", + "showLockedDescription": false + }, + { + "id": "favorite_one", + "title": "推し", + "description": "ある個体をお気に入りに登録する。", + "category": "ecology", + "showLockedDescription": false + }, + { + "id": "statistician", + "title": "統計学者", + "description": "統計の個体数・欲求・環境・グラフ表示切替ボタンを累計30回押す。", + "category": "operation", + "showLockedDescription": false, + "progress": { + "type": "counter", + "key": "statsButtonPressCount", + "target": 30, + "display": "count", + "unit": "回" + } + }, + { + "id": "well_informed", + "title": "情報通", + "description": "プッシュ通知をONにする。", + "category": "operation", + "showLockedDescription": false + }, + { + "id": "lively_making", + "title": "賑わいづくり", + "description": "「たりないを追加」で100体追加する。", + "category": "population", + "showLockedDescription": true, + "progress": { + "type": "counter", + "key": "manualTarinaiAddedCount", + "target": 100, + "display": "count", + "unit": "体" + } + }, + { + "id": "memento_mori", + "title": "多数の死は統計上の数字でしかない", + "description": "たりないが合計10000体死亡する。", + "category": "population", + "showLockedDescription": true, + "progress": { + "type": "counter", + "key": "totalDeathCount", + "target": 10000, + "display": "percent", + "unit": "体" + } + }, + { + "id": "mad_scientist", + "title": "マッドサイエンティスト", + "description": "異なる10匹のたりないに怪しい薬を投与する。", + "category": "experiment", + "showLockedDescription": false, + "progress": { + "type": "unique", + "key": "mysteryDrugTarinaiIds", + "target": 10, + "display": "count", + "unit": "匹" + } + } + ] +}; diff --git a/js/achievements.js b/js/achievements.js index c98a1e8..31bff77 100644 --- a/js/achievements.js +++ b/js/achievements.js @@ -1,209 +1,87 @@ "use strict"; (function initAchievementSystem(global) { - const STORAGE_KEY = "tarinai_achievements_v2"; + // v7 uses a fresh namespace so tabs left open on older builds cannot write + // stale full-state envelopes into the current persistence layer. + const STORAGE_KEY = "tarinai_achievements_v7"; + const STORAGE_BACKUP_KEY = "tarinai_achievements_backup_v7"; + const STORAGE_SESSION_KEY = "tarinai_achievements_session_v7"; + const PREVIOUS_STORAGE_KEY = "tarinai_achievements_v6"; + const PREVIOUS_STORAGE_BACKUP_KEY = "tarinai_achievements_backup_v6"; + const PREVIOUS_STORAGE_SESSION_KEY = "tarinai_achievements_session_v6"; + const OLDER_STORAGE_KEY = "tarinai_achievements_v5"; + const OLDER_STORAGE_BACKUP_KEY = "tarinai_achievements_backup_v5"; + const OLDER_STORAGE_SESSION_KEY = "tarinai_achievements_session_v5"; + const LEGACY_STORAGE_KEY = "tarinai_achievements_v4"; + const LEGACY_STORAGE_BACKUP_KEY = "tarinai_achievements_backup_v4"; + const LEGACY_STORAGE_SESSION_KEY = "tarinai_achievements_session_v4"; + const ANCIENT_STORAGE_KEY = "tarinai_achievements_v2"; + const ANCIENT_STORAGE_BACKUP_KEY = "tarinai_achievements_backup_v3"; + const ANCIENT_STORAGE_SESSION_KEY = "tarinai_achievements_session_v3"; + const PERSISTENCE_FORMAT = "tarinai-achievements-envelope-v1"; + const PERSISTENCE_DB_NAME = "tarinai_achievements_durable_v5"; + const PREVIOUS_PERSISTENCE_DB_NAME = "tarinai_achievements_durable_v4"; + const OLDER_PERSISTENCE_DB_NAME = "tarinai_achievements_durable_v3"; + const LEGACY_PERSISTENCE_DB_NAME = "tarinai_achievements_durable_v2"; + const ANCIENT_PERSISTENCE_DB_NAME = "tarinai_achievements_durable_v1"; + const PERSISTENCE_DB_STORE = "records"; + const PERSISTENCE_DB_KEY = "achievement-state"; + const PERSISTENCE_CHANNEL_NAME = "tarinai-achievements-persistence-v5"; + const PREHYDRATION_JOURNAL_PREFIX = "tarinai_achievements_pre_hydration_v7_"; + const PREHYDRATION_JOURNAL_FORMAT = "tarinai-achievements-pre-hydration-v1"; + const PREHYDRATION_JOURNAL_DB_PREFIX = "pre-hydration-journal:"; const PLAYER_KEY = "tarinai_achievement_player_v1"; + const PLAYER_SECRET_KEY = "tarinai_achievement_player_secret_v1"; + const LEGACY_PLAYER_KEY = "tarinai_achievement_legacy_player_v4"; const API_URL = String(global.TARINAI_ACHIEVEMENT_API || "achievement_api.php"); - const GAME_VERSION = String(global.TARINAI_VERSION || "39.16.77"); + const GAME_VERSION = String(global.TARINAI_VERSION || "39.18.18"); const DEBUG_MODE = ["1", "true"].includes(new URLSearchParams(global.location?.search || "").get("debug")); - const PLAYER_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + const PLAYER_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; + const LEGACY_PLAYER_ID_PATTERN = /^[A-Za-z0-9_-]{22}$/; + const PLAYER_SECRET_PATTERN = /^[0-9a-f]{64}$/i; const ABSOLUTE_ZERO_C = -273.15; const CONTINUOUS_PLAY_TARGET_MS = 60 * 60 * 1000; const CONTINUOUS_PLAY_24H_TARGET_MS = 24 * 60 * 60 * 1000; const HELD_TARGET_MS = 30 * 1000; - const COMPLETIONIST_ID = "true_tarinai_observer"; + const ACHIEVEMENT_CATALOG = global.TARINAI_ACHIEVEMENT_CATALOG; + if (!ACHIEVEMENT_CATALOG || !Array.isArray(ACHIEVEMENT_CATALOG.definitions) || !Array.isArray(ACHIEVEMENT_CATALOG.categories)) { + throw new Error("achievement catalog unavailable"); + } + const COMPLETIONIST_ID = String(ACHIEVEMENT_CATALOG.completionistId || "true_tarinai_observer"); + const ACHIEVEMENT_CATALOG_REVISION = String(ACHIEVEMENT_CATALOG.revision || "unknown"); const GENERATION_TARGET = 10; - const CHAOS_FIGHT_TARGET = 666; - const SNIPER_SHOT_TARGET = 333; - const FERTILITY_BIRTH_TARGET = 721; - const DAILY_PLAY_TARGET = 7; - const WIRE_SHOCK_TARGET = 7; const DAY_MS = 24 * 60 * 60 * 1000; - const ROBOT_CLEAN_TARGET = 200; - const ROBOT_ALL_TARGET_MASK = 0x3f; const SYNC_DEBOUNCE_MS = 450; const FULL_SYNC_INTERVAL_MS = 5 * 60 * 1000; - const SPELL_STATE_VERSION = 8; - const MEDICINE_LEDGER_TYPES = Object.freeze(["first_aid", "sedative", "sleep_drug", "laxative", "protein", "niteropu", "ammo", "mystery_drug", "mercury", "giant_drug", "dwarf_drug"]); - const DIRECT_TREATMENT_TYPES = new Set(["first_aid", "sedative", "sleep_drug", "laxative", "protein", "niteropu", "ammo", "mystery_drug", "mercury", "giant_drug", "dwarf_drug"]); + const SYNC_PROTOCOL_VERSION = 5; + const SPELL_STATE_VERSION = 11; // v11 stores additive counters only in the canonical ledger. + const MEDICINE_LEDGER_TYPES = Object.freeze([...(ACHIEVEMENT_CATALOG.medicineLedgerTypes || [])]); + const LINK_PROGRESS_TYPES = Object.freeze([...(ACHIEVEMENT_CATALOG.linkProgressTypes || [])]); + const ADDITIVE_PROGRESS_CAPS = Object.freeze({ ...(ACHIEVEMENT_CATALOG.additiveProgressCaps || {}) }); + const ADDITIVE_PROGRESS_KEYS = Object.freeze(Object.keys(ADDITIVE_PROGRESS_CAPS)); + const CHAOS_FIGHT_TARGET = ADDITIVE_PROGRESS_CAPS.fightMochiFightCount; + const SNIPER_SHOT_TARGET = ADDITIVE_PROGRESS_CAPS.shotCount; + const FERTILITY_BIRTH_TARGET = ADDITIVE_PROGRESS_CAPS.loveMochiBirthCount; + const DAILY_PLAY_TARGET = 7; + const WIRE_SHOCK_TARGET = 7; + const ROBOT_CLEAN_TARGET = ADDITIVE_PROGRESS_CAPS.robotCleanCount; + const ROBOT_ALL_TARGET_MASK = 0x7f; const OBSERVER_GAME_DAYS = 3; const STRENGTH_IN_NUMBERS_TARGET = 100; const ELITE_FEW_MAX_POPULATION = 25; const ELITE_FEW_TARGET_DAYS = 5; - const STATISTICIAN_TARGET = 30; - const LIVELY_MAKING_TARGET = 100; - const MEMENTO_MORI_TARGET = 10000; + const STATISTICIAN_TARGET = ADDITIVE_PROGRESS_CAPS.statsButtonPressCount; + const LIVELY_MAKING_TARGET = ADDITIVE_PROGRESS_CAPS.manualTarinaiAddedCount; + const MEMENTO_MORI_TARGET = ADDITIVE_PROGRESS_CAPS.totalDeathCount; + const MAD_SCIENTIST_TARGET = Number(ACHIEVEMENT_CATALOG.definitions.find(def => def.id === "mad_scientist")?.progress?.target || 10); const FULL_SEASON_CYCLE_DAYS = 20; - const PRE_UNLOCK_DESCRIPTION_IDS = new Set([ - "natural_zunchi_slave", - "natural_tarinai_king", - "revolution", - "laxative_starvation", - "natural_zunchi_slave_5_generations", - "natural_tarinai_king_3_generations", - "first_birth", - "lifespan_completed", - "birth_50_in_60_seconds", - "death_50_in_10_seconds", - "all_non_sleep_diseased_25", - "colony_happy", - "safe_colony_25_5_minutes", - "ants_alive_25", - "great_mother_1000_births", - "continuous_play_1_hour", - "low_fps_single_digit", - "continuous_play_24_hours", - "robot_cleaner_100", - "mercury_lifespan", - "enemy_enemy_friend", - "eternal_history_generation_10", - "town_doctor_50", - "chaos_seeker_666_fights", - "fertility_seeker_721_love_births", - "daily_play_7_days", - "elite_few", - "lively_making", - "memento_mori", - ]); - const ACHIEVEMENT_CATEGORIES = Object.freeze([ - Object.freeze({ - id: "ecology", - title: "\u751f\u614b", - ids: Object.freeze([ - "natural_zunchi_slave", "natural_tarinai_king", "lifespan_completed", - "all_non_sleep_diseased_25", "colony_happy", "direct_feed_33", - "safe_colony_25_5_minutes", "ants_alive_25", "overprotective", - "self_sufficient", "rain_shelter_all", "medicine_ledger_all", - "enemy_enemy_friend", "king_full_satisfaction", "slave_zero_satisfaction", - "town_doctor_50", "ant_nest_without_tarinai", "zunchi_overflow", - "comfortable_beds", "stone_pillow", "favorite_one", - ]), - }), - Object.freeze({ - id: "population", - title: "\u7e41\u6b96\u30fb\u4eba\u53e3", - ids: Object.freeze([ - "first_birth", "natural_zunchi_slave_5_generations", "natural_tarinai_king_3_generations", - "birth_50_in_60_seconds", "great_mother_1000_births", "eternal_history_generation_10", - "fertility_seeker_721_love_births", "strength_in_numbers", "elite_few", - "lively_making", "memento_mori", - ]), - }), - Object.freeze({ - id: "experiment", - title: "\u5b9f\u9a13", - ids: Object.freeze([ - "self_zunchi_death", "death_50_in_10_seconds", "soccer_ball_death", - "fight_pair_danger_kill", "ignite_during_birth_ritual", "laxative_starvation", - "ants_killed_100", "below_absolute_zero_item", "sauna_cold_plunge", - "mercury_lifespan", "revolution", "fuel_to_fire", - "chaos_seeker_666_fights", "sticky_bomb_15_passes", "wire_shock_7_tarinai", - ]), - }), - Object.freeze({ - id: "construction", - title: "\u5efa\u7bc9", - ids: Object.freeze([ - "placed_objects_100", "mechanized_industry", "information_industry", "robot_cleaner_100", - "minimalist_happy", "unplanned_city_30", "clean_freak_robot_only", "megalopolis", - "sandbox_five_toilets", "park_ground_changed", "ground_change_4_in_1_second", - ]), - }), - Object.freeze({ - id: "operation", - title: "\u64cd\u4f5c", - ids: Object.freeze([ - "idle_observer_5_minutes", "secret_collection_9_slots", "pause_spam_4_in_1_second", - "undo_mass_revival", "held_30_seconds", "undo_20", "redo_20", - "poke_plushie_fling", "sniper_333_shots", "statistician", "well_informed", - ]), - }), - Object.freeze({ - id: "other", - title: "\u305d\u306e\u4ed6", - ids: Object.freeze([ - "low_fps_single_digit", "daily_play_7_days", "continuous_play_24_hours", - "continuous_play_1_hour", "across_seasons", "true_tarinai_observer", - ]), - }), - ]); - const DEFINITIONS = Object.freeze([ - Object.freeze({ id: "first_birth", title: "\u306f\u3058\u3081\u3066\u306e\u7e41\u6b96", description: "\u305f\u308a\u306a\u3044\u306e\u7e41\u6b96\u30921\u56de\u6210\u529f\u3055\u305b\u308b\u3002" }), - Object.freeze({ id: "natural_zunchi_slave", title: "\u305a\u3093\u3061\u3069\u308c\u3044", description: "\u305a\u3093\u3061\u3069\u308c\u3044\u304c\u51fa\u73fe\u3059\u308b\u3002" }), - Object.freeze({ id: "natural_tarinai_king", title: "\u305f\u308a\u306a\u3044\u738b", description: "\u305f\u308a\u306a\u3044\u738b\u304c\u51fa\u73fe\u3059\u308b\u3002" }), - Object.freeze({ id: "self_zunchi_death", title: "\u3042\u3041\uff3e\uff5e \u305f\u307e\u3089\u306d\u3047\u305c", description: "\u304a\u3057\u308a\u92f2\u3092\u629c\u3044\u305f\u6642\u3001\u81ea\u5206\u306e\u305a\u3093\u3061\u3067\u81ea\u7206\u3059\u308b\u3002" }), - Object.freeze({ id: "natural_zunchi_slave_5_generations", title: "\u672b\u4ee3\u307e\u3067\u306e\u6065", description: "5\u4ee3\u9023\u7d9a\u3067\u305a\u3093\u3061\u3069\u308c\u3044\uff08\u9396\u306a\u3057\uff09" }), - Object.freeze({ id: "natural_tarinai_king_3_generations", title: "\u83ef\u9e97\u306a\u308b\u738b\u65cf", description: "3\u4ee3\u9023\u7d9a\u3067\u305f\u308a\u306a\u3044\u738b\uff08\u738b\u51a0\u306a\u3057\uff09" }), - Object.freeze({ id: "death_50_in_10_seconds", title: "6\u756a\u76ee\u306e\u5927\u91cf\u7d76\u6ec5", description: "10\u79d2\u4ee5\u5185\u306b50\u4f53\u306e\u305f\u308a\u306a\u3044\u304c\u6b7b\u4ea1\u3059\u308b\u3002" }), - Object.freeze({ id: "birth_50_in_60_seconds", title: "\u30d9\u30d3\u30fc\u30d6\u30fc\u30e0", description: "1\u5206\u4ee5\u5185\u306b30\u4f53\u306e\u305f\u308a\u306a\u3044\u304c\u8a95\u751f\u3059\u308b\u3002" }), - Object.freeze({ id: "great_mother_1000_births", title: "\u5927\u3044\u306a\u308b\u6bcd", description: "\u305f\u308a\u306a\u3044\u3092\u7e41\u6b96\u3067\u7d2f\u8a083333\u4f53\u8a95\u751f\u3055\u305b\u308b\u3002" }), - Object.freeze({ id: "lifespan_completed", title: "\u5929\u5bff", description: "\u305f\u308a\u306a\u30441\u4f53\u304c\u5929\u5bff\u3092\u5168\u3046\u3059\u308b\u3002" }), - Object.freeze({ id: "soccer_ball_death", title: "\u8c46\u91ce\u3001\u6bba\u30c3\u30ab\u30fc\u3084\u308d\u3046\u305c\uff01", description: "\u30b5\u30c3\u30ab\u30fc\u30dc\u30fc\u30eb\u3068\u306e\u885d\u7a81\u3067\u3001\u305f\u308a\u306a\u30441\u4f53\u304c\u6b7b\u4ea1\u3059\u308b\u3002" }), - Object.freeze({ id: "fight_pair_danger_kill", title: "\u55a7\u5629\u4e21\u6210\u6557", description: "\u55a7\u5629\u4e2d\u306e\u305f\u308a\u306a\u3044\u3092\u3001\u4e21\u65b9\u3068\u3082\u5371\u967a\u30ab\u30c6\u30b4\u30ea\u306e\u30a2\u30a4\u30c6\u30e0\u3067\u5012\u3059\u3002" }), - Object.freeze({ id: "all_non_sleep_diseased_25", title: "\u7dca\u6025\u4e8b\u614b\u5ba3\u8a00", description: "25\u4f53\u4ee5\u4e0a\u304c\u5b58\u547d\u3057\u3001\u30d5\u30a3\u30fc\u30eb\u30c9\u4e0a\u306e\u5168\u54e1\u304c\u306d\u3080\u308a\u75c5\u4ee5\u5916\u306e\u75c5\u6c17\u306b\u304b\u304b\u308b\u3002" }), - Object.freeze({ id: "colony_happy", title: "\u7ba1\u7406\u3055\u308c\u305f\u697d\u5712", description: "\u30b3\u30ed\u30cb\u30fc\u72b6\u614b\u3092\u3057\u3070\u3089\u304f\u300c\u5e78\u798f\u300d\u306b\u3059\u308b\u3002" }), - Object.freeze({ id: "direct_feed_33", title: "\u990c\u3084\u308a\u3058\u3044\u3055\u3093", description: "\u624b\u304b\u3089\u76f4\u63a533\u56de\u990c\u3092\u4e0e\u3048\u308b\u3002" }), - Object.freeze({ id: "ignite_during_birth_ritual", title: "\u71c3\u3048\u4e0a\u304c\u308b\u604b", description: "\u305f\u308a\u306a\u3044\u304c\u30d8\u30b3\u30d8\u30b3\u4e2d\u306b\u7740\u706b\u3059\u308b\u3002" }), - Object.freeze({ id: "laxative_starvation", title: "\u5185\u81d3\u5168\u90e8\u51fa\u305f", description: "\u4e0b\u5264\u306e\u52b9\u679c\u4e2d\u306b\u9913\u6b7b\u3059\u308b\u3002" }), - Object.freeze({ id: "idle_observer_5_minutes", title: "\u76e3\u8996\u30ab\u30e1\u30e9", description: "3\u30b2\u30fc\u30e0\u65e5\u3001\u64cd\u4f5c\u305b\u305a\u753b\u9762\u3092\u898b\u308b\u3060\u3051" }), - Object.freeze({ id: "placed_objects_100", title: "\u7269\u3067\u3044\u3063\u3071\u3044", description: "\u914d\u7f6e\u7269\u3092\u7d2f\u8a08100\u500b\u7f6e\u304f\u3002" }), - Object.freeze({ id: "mechanized_industry", title: "\u6a5f\u68b0\u5316\u7523\u696d", description: "\u691c\u77e5\u5668\u306e\u4fe1\u53f7\u3067\u63a5\u7d9a\u5148\u3092\u4f5c\u52d5\u3055\u305b\u3001\u30ed\u30fc\u30d7\u30fb\u68d2\u30fb\u3070\u306d\u3092\u305d\u308c\u305e\u308c1\u672c\u4ee5\u4e0a\u8a2d\u7f6e\u3059\u308b\u3002" }), - Object.freeze({ id: "safe_colony_25_5_minutes", title: "\u5b89\u5168\u7b2c\u4e00", description: "25\u4f53\u4ee5\u4e0a\u3044\u308b\u72b6\u614b\u3092\u30b2\u30fc\u30e0\u51855\u5206\u9593\u7dad\u6301\u3057\u3001\u305d\u306e\u9593\u5bff\u547d\u4ee5\u5916\u3067\u6b7b\u4ea1\u8005\u3092\u51fa\u3055\u306a\u3044\u3002" }), - Object.freeze({ id: "ants_alive_25", title: "\u30a2\u30ea\u306e\u60d1\u661f", description: "\u751f\u5b58\u3057\u3066\u3044\u308b\u30a2\u30ea\u304c25\u4f53\u306b\u5230\u9054\u3059\u308b\u3002" }), - Object.freeze({ id: "ants_killed_100", title: "\u5bb3\u866b\u99c6\u9664", description: "\u30a2\u30ea\u3092\u7d2f\u8a08100\u4f53\u5012\u3059\u3002" }), - Object.freeze({ id: "secret_collection_9_slots", title: "\u79d8\u5bc6\u306e\u30b3\u30ec\u30af\u30b7\u30e7\u30f3", description: "\u30bb\u30fc\u30d6\u30b9\u30ed\u30c3\u30c89\u3064\u3092\u3059\u3079\u3066\u57cb\u3081\u308b\u3002" }), - Object.freeze({ id: "pause_spam_4_in_1_second", title: "\u4f55\u3084\u3063\u3066\u308b\u306e\uff1f", description: "\u4f55\u3082\u306a\u3044\u90e8\u5206\u30921\u79d2\u9593\u306b4\u56de\u9023\u6253\u3059\u308b\u3002" }), - Object.freeze({ id: "continuous_play_1_hour", title: "\u3081\u3063\u3061\u3083\u305f\u308a\u306a\u3044\u89b3\u5bdf", description: "1\u6642\u9593\u9023\u7d9a\u30d7\u30ec\u30a4\u3059\u308b\u3002" }), - Object.freeze({ id: "below_absolute_zero_item", title: "\u7269\u7406\u6cd5\u5247\u3092\u4e0b\u5074\u306b\u8d85\u8d8a", description: "\u6e29\u5ea6\u8a08\u7b97\u3055\u308c\u308b\u30a2\u30a4\u30c6\u30e0\u30921\u3064\u7d76\u5bfe\u96f6\u5ea6\u3092\u4e0b\u56de\u308b\u6e29\u5ea6\u306b\u3059\u308b\u3002" }), - Object.freeze({ id: "undo_mass_revival", title: "\u898b\u306a\u304b\u3063\u305f\u3053\u3068\u306b\u3057\u3088\u3046", description: "\u4e00\u5ea6\u306eUndo\u306710\u4f53\u4ee5\u4e0a\u306e\u6b7b\u4ea1\u3092\u306a\u304b\u3063\u305f\u3053\u3068\u306b\u3059\u308b\u3002" }), - Object.freeze({ id: "robot_cleaner_100", title: "\u6e05\u6383\u696d\u8005", description: "\u30ed\u30dc\u6383\u9664\u6a5f\u306b\u305a\u3093\u3061\u30fb\u6b7b\u9ab8\u30fb\u6c5a\u308c\u3092\u7d2f\u8a08200\u500b\u51e6\u7406\u3055\u305b\u308b\u3002" }), - Object.freeze({ id: "held_30_seconds", title: "\u7a7a\u4e2d\u751f\u6d3b", description: "\u540c\u3058\u305f\u308a\u306a\u3044\u309230\u79d2\u9593\u3064\u307e\u307f\u7d9a\u3051\u308b\u3002" }), - Object.freeze({ id: "minimalist_happy", title: "\u30df\u30cb\u30de\u30ea\u30b9\u30c8", description: "\u30d7\u30ec\u30a4\u958b\u59cb6\u65e5\u76ee\u4ee5\u964d\u3001\u914d\u7f6e\u7269\u309210\u500b\u4ee5\u4e0b\u306b\u6291\u3048\u3066\u30b3\u30ed\u30cb\u30fc\u72b6\u614b\u3092\u300c\u5e78\u798f\u300d\u306b\u3059\u308b\u3002" }), - Object.freeze({ id: "overprotective", title: "\u904e\u4fdd\u8b77", description: "\u540c\u3058\u305f\u308a\u306a\u3044\u306b\u624b\u304b\u308910\u56de\u990c\u3092\u4e0e\u3048\u30013\u56de\u4ee5\u4e0a\u85ac\u3067\u6cbb\u7642\u3059\u308b\u3002" }), - Object.freeze({ id: "self_sufficient", title: "\u81ea\u7d66\u81ea\u8db3", description: "\u8907\u88fd\u6a5f\u304c\u306a\u3044\u72b6\u614b\u3067\u300120\u4f53\u4ee5\u4e0a\u3092\u76f4\u63a5\u7d66\u990c\u305b\u305a10\u5206\u9593\u7dad\u6301\u3059\u308b\u3002" }), - Object.freeze({ id: "unplanned_city_30", title: "\u7121\u8a08\u753b\u90fd\u5e02", description: "\u914d\u7f6e\u5f8c30\u79d2\u4ee5\u5185\u306b\u524a\u9664\u3059\u308b\u64cd\u4f5c\u3092\u7d2f\u8a0830\u56de\u884c\u3046\u3002" }), - Object.freeze({ id: "sauna_cold_plunge", title: "\u30b5\u30a6\u30ca\u6c34\u98a8\u5442", description: "\u6691\u3059\u304e\u308b\u72b6\u614b\u306b\u306a\u3063\u305f\u305f\u308a\u306a\u3044\u3092\u300115\u79d2\u4ee5\u5185\u306b\u5bd2\u3059\u304e\u308b\u72b6\u614b\u306b\u3059\u308b\u3002" }), - Object.freeze({ id: "rain_shelter_all", title: "\u96e8\u5bbf\u308a\u5b8c\u4e86", description: "\u96e8\u5929\u6642\u300120\u4f53\u4ee5\u4e0a\u306e\u5168\u54e1\u3092\u30d1\u30e9\u30bd\u30eb\u30fb\u5de3\u7bb1\u30fb\u571f\u7ba1\u3067\u96e8\u5bbf\u308a\u3055\u305b\u308b\u3002" }), - Object.freeze({ id: "medicine_ledger_all", title: "\u304a\u304f\u3059\u308a\u624b\u5e33\u5168\u57cb\u3081", description: "\u5168\u7a2e\u985e\u306e\u85ac\u3092\u5c11\u306a\u304f\u3068\u30821\u56de\u4f7f\u7528\u3059\u308b\u3002" }), - Object.freeze({ id: "mercury_lifespan", title: "\u4e0d\u8001\u4e0d\u6b7b\u307e\u3067\u3042\u3068\u4e00\u6b69", description: "\u6c34\u9280\u3092\u4f7f\u7528\u3057\u305f\u305f\u308a\u306a\u3044\u304c\u5929\u5bff\u3092\u5168\u3046\u3059\u308b\u3002" }), - Object.freeze({ id: "enemy_enemy_friend", title: "\u6575\u306e\u6575\u306f\u5473\u65b9", description: "\u305f\u308a\u306a\u304430\u4f53\u4ee5\u4e0a\u3092\u7121\u50b7\u3067\u4fdd\u3061\u306a\u304c\u3089\u3001\u5371\u967a\u30a2\u30a4\u30c6\u30e0\u3067\u30a2\u30ea\u309210\u4f53\u5012\u3059\u3002" }), - Object.freeze({ id: "revolution", title: "\u9769\u547d", description: "\u305a\u3093\u3061\u3069\u308c\u3044\u304c\u3001\u305f\u308a\u306a\u3044\u738b\u3092\u55a7\u5629\u3067\u6b7b\u4ea1\u3055\u305b\u308b\u3002" }), - Object.freeze({ id: "fuel_to_fire", title: "\u706b\u306b\u6cb9", description: "\u3051\u3093\u304b\u9905\u3092\u4e0e\u3048\u305f\u305f\u308a\u306a\u3044\u304c30\u79d2\u4ee5\u5185\u306b\u55a7\u5629\u3092\u59cb\u3081\u308b\u3002" }), - Object.freeze({ id: "undo_20", title: "\u3084\u3063\u3071\u306a\u3057", description: "Undo\u3092\u7d2f\u8a0820\u56de\u6210\u529f\u3055\u305b\u308b\u3002" }), - Object.freeze({ id: "redo_20", title: "\u3084\u3063\u3071\u3042\u308a", description: "Redo\u3092\u7d2f\u8a0820\u56de\u6210\u529f\u3055\u305b\u308b\u3002" }), - Object.freeze({ id: "eternal_history_generation_10", title: "\u60a0\u4e45\u306e\u6b74\u53f2", description: "\u4e16\u4ee3\u304c10\u306b\u5230\u9054\u3059\u308b\u3002" }), - Object.freeze({ id: "king_full_satisfaction", title: "\u4e94\u4f53\u6e80\u8db3", description: "\u305f\u308a\u306a\u3044\u738b1\u500b\u4f53\u306b\u30d7\u30ed\u30c6\u30a4\u30f3\u3068\u5de8\u5927\u85ac\u306e\u52b9\u679c\u3092\u540c\u6642\u306b\u4ed8\u4e0e\u3059\u308b\u3002" }), - Object.freeze({ id: "slave_zero_satisfaction", title: "\u96f6\u4f53\u6e80\u8db3", description: "\u305a\u3093\u3061\u3069\u308c\u30441\u500b\u4f53\u306b\u30f3\u30a4\u30c6\u30ed\u30d7\u3068\u77ee\u5c0f\u85ac\u306e\u52b9\u679c\u3092\u540c\u6642\u306b\u4ed8\u4e0e\u3059\u308b\u3002" }), - Object.freeze({ id: "town_doctor_50", title: "\u753a\u306e\u304a\u533b\u8005\u3055\u3093", description: "\u6551\u6025\u85ac\u3092\u7d2f\u8a0850\u56de\u4f7f\u7528\u3057\u3001\u4f53\u529b\u3092\u56de\u5fa9\u3055\u305b\u308b\u3002" }), - Object.freeze({ id: "poke_plushie_fling", title: "\u5272\u3068\u3075\u308f\u3075\u308f", description: "\u306c\u3044\u3050\u308b\u307f\u3092\u300c\u3064\u3064\u304f\u300d\u3067\u5f3e\u304d\u98db\u3070\u3059\u3002" }), - Object.freeze({ id: "chaos_seeker_666_fights", title: "\u6df7\u6c8c\u30f2\u5e0c\u6c42\u30b9\u30eb\u8005", description: "\u3051\u3093\u304b\u9905\u306e\u5f71\u97ff\u4e0b\u3067\u55a7\u5629\u3092\u7d2f\u8a08666\u56de\u767a\u751f\u3055\u305b\u308b\u3002" }), - Object.freeze({ id: "clean_freak_robot_only", title: "\u6f54\u7656\u75c7", description: "\u30ed\u30dc\u30c3\u30c8\u6383\u9664\u6a5f\u306e\u8a2d\u5b9a\u5168\u9805\u76ee\u306b\u30c1\u30a7\u30c3\u30af\u3092\u5165\u308c\u3066\u7a3c\u50cd\u3055\u305b\u3001\u30d5\u30a3\u30fc\u30eb\u30c9\u4e0a\u306b\u30ed\u30dc\u30c3\u30c8\u6383\u9664\u6a5f\u4ee5\u5916\u3092\u5b58\u5728\u3055\u305b\u306a\u3044\u3002" }), - Object.freeze({ id: "true_tarinai_observer", title: "\u771f\u30fb\u305f\u308a\u306a\u3044\u89b3\u5bdf", description: "\u3053\u308c\u4ee5\u5916\u306e\u5168\u3066\u306e\u5b9f\u7e3e\u3092\u9054\u6210\u3059\u308b\u3002" }), - Object.freeze({ id: "sniper_333_shots", title: "\u72d9\u6483\u624b", description: "\u7d2f\u8a08333\u767a\u6483\u3064\u3002" }), - Object.freeze({ id: "megalopolis", title: "\u30e1\u30ac\u30ed\u30dd\u30ea\u30b9", description: "\u8907\u88fd\u6a5f\u309210\u500b\u4ee5\u4e0a\u3001\u5e72\u8349\u5bdd\u5e8a\u30fb\u5de3\u7bb1\u30fb\u571f\u7ba1\u3092\u5408\u8a0815\u500b\u4ee5\u4e0a\u8a2d\u7f6e\u3057\u3001\u305f\u308a\u306a\u3044\u3092100\u4f53\u4ee5\u4e0a\u751f\u5b58\u3055\u305b\u308b\u3002" }), - Object.freeze({ id: "fertility_seeker_721_love_births", title: "\u8c4a\u7a63\u30f2\u5e0c\u6c42\u30b9\u30eb\u8005", description: "\u3078\u3053\u9905\u306e\u5f71\u97ff\u4e0b\u3067\u7e41\u6b96\u3092721\u56de\u6210\u529f\u3055\u305b\u308b\u3002" }), - Object.freeze({ id: "low_fps_single_digit", title: "\u30b9\u30da\u30c3\u30af\u304c\u305f\u308a\u306a\u3044", description: "fps\u30921\u6841\u306b\u3059\u308b\u3002" }), - Object.freeze({ id: "continuous_play_24_hours", title: "\u5bdd\u308d", description: "24\u6642\u9593\u9023\u7d9a\u3067\u30d7\u30ec\u30a4\u3059\u308b\u3002" }), - Object.freeze({ id: "sandbox_five_toilets", title: "\u7802\u5834", description: "\u30c8\u30a4\u30ec\u306e\u7802\u3092\u30d5\u30a3\u30fc\u30eb\u30c9\u306b5\u500b\u8a2d\u7f6e\u3059\u308b\u3002" }), - Object.freeze({ id: "park_ground_changed", title: "\u305d\u3053\u516c\u5171\u7a7a\u9593\u3060\u3088\uff1f", description: "\u516c\u5712\u306e\u5730\u9762\u3092\u52dd\u624b\u306b\u5909\u66f4\u3059\u308b\u3002" }), - Object.freeze({ id: "ground_change_4_in_1_second", title: "\u7834\u683c\u306e\u5de5\u4e8b\u8cbb\u7528", description: "\u5730\u9762\u3092\u5909\u3048\u3059\u304e\u3066\u7834\u7523\u3059\u308b\u3002" }), - Object.freeze({ id: "ant_nest_without_tarinai", title: "\u30a2\u30ea\u89b3\u5bdf", description: "\u30a2\u30ea\u306e\u5de3\u304c\u3042\u308b\u304c\u3001\u305f\u308a\u306a\u3044\u304c\u3044\u306a\u3044\u3002" }), - Object.freeze({ id: "sticky_bomb_15_passes", title: "\u547d\u306e\u30d0\u30c8\u30f3", description: "\u7c98\u7740\u30dc\u30e0\u3092\u7206\u767a\u307e\u3067\u306b15\u56de\u4ee5\u4e0a\u30d1\u30b9\u3059\u308b\u3002" }), - Object.freeze({ id: "daily_play_7_days", title: "\u6bce\u65e5\u305f\u308a\u306a\u3044\u89b3\u5bdf", description: "7\u65e5\u9023\u7d9a\u3067\u30d7\u30ec\u30a4\u3059\u308b\u3002" }), - Object.freeze({ id: "wire_shock_7_tarinai", title: "\u62b5\u6297\u5668\u3058\u3083\u306a\u3044", description: "\u96fb\u6d41\u304c\u6d41\u308c\u3066\u3044\u308b1\u672c\u306e\u96fb\u7dda\u30677\u4f53\u306e\u305f\u308a\u306a\u3044\u3092\u611f\u96fb\u3055\u305b\u308b\u3002" }), - Object.freeze({ id: "information_industry", title: "\u60c5\u5831\u5316\u7523\u696d", description: "\u57fa\u76e4\u540c\u58eb\u3092\u96fb\u7dda\u985e\u3067\u3064\u306a\u304e\u3001\u4fe1\u53f7\u3092\u6d41\u3059\u3002" }), - Object.freeze({ id: "strength_in_numbers", title: "\u6570\u3053\u305d\u529b", description: "\u751f\u5b58\u3057\u3066\u3044\u308b\u305f\u308a\u306a\u3044\u304c100\u4f53\u306b\u5230\u9054\u3059\u308b\u3002" }), - Object.freeze({ id: "elite_few", title: "\u5c11\u6570\u7cbe\u92ed", description: "\u305f\u308a\u306a\u3044\u304c25\u4f53\u4ee5\u4e0b\u306e\u72b6\u614b\u30925\u65e5\u9593\u7dad\u6301\u3059\u308b\u3002" }), - Object.freeze({ id: "zunchi_overflow", title: "\u8e29\u5c4e\u611f", description: "\u305f\u308a\u306a\u3044\u304c20\u4f53\u4ee5\u4e0a\u3044\u308b\u72b6\u614b\u3067\u3001\u305a\u3093\u3061\u306e\u6570\u304c\u305f\u308a\u306a\u3044\u306e\u6570\u3092\u4e0a\u56de\u308b\u3002" }), - Object.freeze({ id: "comfortable_beds", title: "\u5feb\u9069\u306a\u5bdd\u5e8a", description: "\u751f\u5b58\u3057\u3066\u3044\u308b\u5168\u3066\u306e\u305f\u308a\u306a\u3044\u306b\u884c\u304d\u6e21\u308b\u6570\u306e\u5bdd\u5e8a\u3092\u7528\u610f\u3059\u308b\u3002" }), - Object.freeze({ id: "stone_pillow", title: "\u77f3\u306b\u6795\u3059", description: "\u305f\u308a\u306a\u3044\u304c30\u4f53\u4ee5\u4e0a\u3044\u308b\u72b6\u614b\u3067\u3001\u5bdd\u5e8a\u5145\u8db3\u7387\u30920%\u306b\u3059\u308b\u3002" }), - Object.freeze({ id: "across_seasons", title: "\u5b63\u7bc0\u3092\u8d8a\u3048\u3066", description: "\u6625\u590f\u79cb\u51ac\u306e\u56db\u5b63\u3092\u4e00\u5de1\u3059\u308b\u3002" }), - Object.freeze({ id: "favorite_one", title: "\u63a8\u3057", description: "\u3042\u308b\u500b\u4f53\u3092\u304a\u6c17\u306b\u5165\u308a\u306b\u767b\u9332\u3059\u308b\u3002" }), - Object.freeze({ id: "statistician", title: "\u7d71\u8a08\u5b66\u8005", description: "\u7d71\u8a08\u306e\u500b\u4f53\u6570\u30fb\u6b32\u6c42\u30fb\u74b0\u5883\u30fb\u30b0\u30e9\u30d5\u8868\u793a\u5207\u66ff\u30dc\u30bf\u30f3\u3092\u7d2f\u8a0830\u56de\u62bc\u3059\u3002" }), - Object.freeze({ id: "well_informed", title: "\u60c5\u5831\u901a", description: "\u30d7\u30c3\u30b7\u30e5\u901a\u77e5\u3092ON\u306b\u3059\u308b\u3002" }), - Object.freeze({ id: "lively_making", title: "\u8cd1\u308f\u3044\u3065\u304f\u308a", description: "\u300c\u305f\u308a\u306a\u3044\u3092\u8ffd\u52a0\u300d\u3067100\u4f53\u8ffd\u52a0\u3059\u308b\u3002" }), - Object.freeze({ id: "memento_mori", title: "\u30e1\u30e1\u30f3\u30c8\u30fb\u30e2\u30ea", description: "\u305f\u308a\u306a\u3044\u304c\u5408\u8a0810000\u4f53\u6b7b\u4ea1\u3059\u308b\u3002" }), - ]); + const DEFINITIONS = Object.freeze(ACHIEVEMENT_CATALOG.definitions.map(definition => Object.freeze({ ...definition }))); + const PRE_UNLOCK_DESCRIPTION_IDS = new Set(DEFINITIONS.filter(definition => definition.showLockedDescription).map(definition => definition.id)); + const ACHIEVEMENT_CATEGORIES = Object.freeze(ACHIEVEMENT_CATALOG.categories.map(category => Object.freeze({ + id: String(category.id || ""), + title: String(category.title || ""), + ids: Object.freeze(DEFINITIONS.filter(definition => definition.category === category.id).map(definition => definition.id)), + }))); const definitionById = new Map(DEFINITIONS.map(def => [def.id, def])); const CATEGORY_DEFINITIONS = new Map(ACHIEVEMENT_CATEGORIES.map(category => [ category.id, @@ -228,8 +106,25 @@ pauseButton: document.getElementById("pauseBtn"), }; - let state = loadState(); - let shared = { connected: false, loading: false, totalPlayers: 0, achievements: {} }; + function createPersistenceActorId() { + if (global.crypto?.randomUUID) return global.crypto.randomUUID(); + return `tab-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`; + } + + const persistenceActorId = createPersistenceActorId(); + let persistenceGeneration = 0; + let persistenceRevision = 0; + let persistenceHydrated = false; + let persistenceDirty = false; + let durableWriteQueue = Promise.resolve(); + let persistenceReadyPromise = Promise.resolve(); + let persistenceChannel = null; + const initialPersistence = loadStateRecord(); + const initialPersistenceBaseline = normalizeState(initialPersistence.state); + let state = initialPersistence.state; + persistenceGeneration = initialPersistence.generation; + persistenceRevision = initialPersistence.revision; + let shared = { connected: false, loading: false, totalPlayers: 0, achievements: {}, statisticsTrust: "client-reported" }; let requestSerial = 0; let runtimeByWorld = new WeakMap(); let dangerFightDeathsByWorld = new WeakMap(); @@ -239,82 +134,734 @@ let toastActive = false; let emptyClickTimes = []; let groundChangeTimes = []; - let continuousPlayStartedAt = Date.now(); - let continuousPlayLastHeartbeatAt = continuousPlayStartedAt; + let continuousPlayAccumulatedMs = 0; + let continuousPlayLastHeartbeatAt = Date.now(); + let continuousPlayActive = !document.hidden; let lastListSignature = ""; let scheduledSyncTimer = 0; let scheduledProgressSaveTimer = 0; + let progressMutationRevision = 0; + let progressSyncedRevision = 0; - function blankState() { - return { unlocked: {}, pending: [], resetPending: false, debugUnlocked: [], progress: { placementCount: 0, linkTypes: [], signalActivated: false, antKills: 0, birthCount: 0, quickDeleteCount: 0, undoCount: 0, redoCount: 0, medicineTypes: [], firstAidHeals: 0, fightMochiFightCount: 0, shotCount: 0, loveMochiBirthCount: 0, dailyPlayStreak: 0, dailyPlayLastDay: 0, statsButtonPressCount: 0, totalDeathCount: 0, manualTarinaiAddedCount: 0 } }; + function blankProgressLedger() { + return { + base: Object.fromEntries(ADDITIVE_PROGRESS_KEYS.map(key => [key, 0])), + shards: Object.fromEntries(ADDITIVE_PROGRESS_KEYS.map(key => [key, {}])), + }; } - function loadState() { + function blankState() { + return { + unlocked: {}, + pending: [], + resetPending: false, + debugUnlocked: [], + serverIdentity: null, + progress: { linkTypes: [], signalActivated: false, medicineTypes: [], dailyPlayStreak: 0, dailyPlayLastDay: 0, mysteryDrugTarinaiIds: [] }, + _progressLedger: blankProgressLedger(), + }; + } + + function ledgerCounterValue(ledgerInput, key) { + if (!Object.prototype.hasOwnProperty.call(ADDITIVE_PROGRESS_CAPS, key)) return 0; + const cap = ADDITIVE_PROGRESS_CAPS[key]; + const ledger = ledgerInput && typeof ledgerInput === "object" ? ledgerInput : {}; + const base = Math.min(cap, Math.max(0, Math.floor(Number(ledger.base?.[key] || 0) || 0))); + const shards = ledger.shards?.[key] && typeof ledger.shards[key] === "object" ? ledger.shards[key] : {}; + return Math.min(cap, base + Object.values(shards).reduce((sum, value) => sum + Math.max(0, Math.floor(Number(value || 0) || 0)), 0)); + } + + function sanitizeProgressLedger(parsed, legacyProgress = {}) { + const source = parsed?._progressLedger && typeof parsed._progressLedger === "object" ? parsed._progressLedger : {}; + const baseSource = source.base && typeof source.base === "object" ? source.base : {}; + const shardsSource = source.shards && typeof source.shards === "object" ? source.shards : {}; + const ledger = blankProgressLedger(); + for (const key of ADDITIVE_PROGRESS_KEYS) { + const cap = ADDITIVE_PROGRESS_CAPS[key]; + let base = Math.min(cap, Math.max(0, Math.floor(Number(baseSource[key] || 0) || 0))); + const shards = {}; + const rawShards = shardsSource[key] && typeof shardsSource[key] === "object" ? shardsSource[key] : {}; + for (const [actorId, rawValue] of Object.entries(rawShards)) { + const id = String(actorId || "").slice(0, 160); + const value = Math.min(cap, Math.max(0, Math.floor(Number(rawValue || 0) || 0))); + if (id && value > 0) shards[id] = value; + } + let total = Math.min(cap, base + Object.values(shards).reduce((sum, value) => sum + value, 0)); + const legacyFloor = Math.min(cap, Math.max(0, Math.floor(Number(legacyProgress[key] || 0) || 0))); + if (legacyFloor > total) { + base = Math.min(cap, base + (legacyFloor - total)); + total = legacyFloor; + } + if (total >= cap) { + base = cap; + for (const actorId of Object.keys(shards)) delete shards[actorId]; + } + ledger.base[key] = base; + ledger.shards[key] = shards; + } + return ledger; + } + + function normalizeServerIdentity(value) { + if (!value || typeof value !== "object") return null; + const id = String(value.playerId || "").toLowerCase(); + const secret = String(value.playerSecret || "").toLowerCase(); + if (!PLAYER_ID_PATTERN.test(id) || !PLAYER_SECRET_PATTERN.test(secret)) return null; + return { playerId: id, playerSecret: secret }; + } + + function normalizeState(parsed) { + if (!parsed || typeof parsed !== "object") return blankState(); + const unlockedSource = parsed.unlocked && typeof parsed.unlocked === "object" ? parsed.unlocked : {}; + const unlocked = {}; + for (const [id, timestamp] of Object.entries(unlockedSource)) { + if (definitionById.has(id) && Number(timestamp) > 0) unlocked[id] = Number(timestamp); + } + const debugUnlockedSource = Array.isArray(parsed.debugUnlocked) ? parsed.debugUnlocked : []; + const debugUnlocked = [...new Set(debugUnlockedSource.filter(id => definitionById.has(id)))]; + if (!DEBUG_MODE) { + for (const id of debugUnlocked) delete unlocked[id]; + } + // v6 and older persisted a redundant synced list. It is read once only to + // avoid re-queuing already acknowledged legacy unlocks, then discarded. + const legacySynced = new Set((Array.isArray(parsed.synced) ? parsed.synced : []).filter(id => definitionById.has(id))); + const pendingSource = Array.isArray(parsed.pending) ? parsed.pending : []; + const pending = pendingSource.filter(id => definitionById.has(id) && unlocked[id] && !debugUnlocked.includes(id) && !legacySynced.has(id)); + const progressSource = parsed.progress && typeof parsed.progress === "object" ? parsed.progress : {}; + const progress = { + linkTypes: [...new Set((Array.isArray(progressSource.linkTypes) ? progressSource.linkTypes : []).filter(type => LINK_PROGRESS_TYPES.includes(type)))], + signalActivated: Boolean(progressSource.signalActivated), + medicineTypes: [...new Set((Array.isArray(progressSource.medicineTypes) ? progressSource.medicineTypes : []).filter(type => MEDICINE_LEDGER_TYPES.includes(type)))], + dailyPlayStreak: Math.min(DAILY_PLAY_TARGET, Math.max(0, Math.floor(Number(progressSource.dailyPlayStreak || 0) || 0))), + dailyPlayLastDay: Math.max(0, Math.floor(Number(progressSource.dailyPlayLastDay || 0) || 0)), + mysteryDrugTarinaiIds: [...new Set((Array.isArray(progressSource.mysteryDrugTarinaiIds) ? progressSource.mysteryDrugTarinaiIds : []).map(id => String(id || "")).filter(Boolean))].slice(0, MAD_SCIENTIST_TARGET), + }; + const progressLedger = sanitizeProgressLedger(parsed, progressSource); + const missingCompletionRequirement = DEFINITIONS.some(definition => definition.id !== COMPLETIONIST_ID && !unlocked[definition.id]); + if (unlocked[COMPLETIONIST_ID] && missingCompletionRequirement) { + delete unlocked[COMPLETIONIST_ID]; + const pendingIndex = pending.indexOf(COMPLETIONIST_ID); + if (pendingIndex >= 0) pending.splice(pendingIndex, 1); + } + return { unlocked, pending: [...new Set(pending)], resetPending: Boolean(parsed.resetPending), debugUnlocked: DEBUG_MODE ? debugUnlocked : [], serverIdentity: normalizeServerIdentity(parsed.serverIdentity), progress, _progressLedger: progressLedger }; + } + + function decodePersistenceEnvelope(raw) { try { - const parsed = JSON.parse(global.localStorage?.getItem(STORAGE_KEY) || "null"); - if (!parsed || typeof parsed !== "object") return blankState(); - const unlockedSource = parsed.unlocked && typeof parsed.unlocked === "object" ? parsed.unlocked : {}; - const unlocked = {}; - for (const [id, timestamp] of Object.entries(unlockedSource)) { - if (definitionById.has(id) && Number(timestamp) > 0) unlocked[id] = Number(timestamp); + const parsed = typeof raw === "string" ? JSON.parse(raw) : raw; + if (!parsed || typeof parsed !== "object") return null; + if (parsed.format === PERSISTENCE_FORMAT && parsed.state && typeof parsed.state === "object") { + return { + generation: Math.max(0, Math.floor(Number(parsed.generation || 0) || 0)), + revision: Math.max(0, Math.floor(Number(parsed.revision || 0) || 0)), + updatedAt: Math.max(0, Number(parsed.updatedAt || 0) || 0), + migrationComplete: Boolean(parsed.migrationComplete), + state: normalizeState(parsed.state), + }; } - const legacyMechanizedAt = Math.max( - Number(unlockedSource.signal_automation_first || 0) || 0, - Number(unlockedSource.link_craftsman || 0) || 0 - ); - if (!unlocked.mechanized_industry - && Number(unlockedSource.signal_automation_first || 0) > 0 - && Number(unlockedSource.link_craftsman || 0) > 0) { - unlocked.mechanized_industry = legacyMechanizedAt || Date.now(); - } - const debugUnlockedSource = Array.isArray(parsed.debugUnlocked) ? parsed.debugUnlocked : []; - const debugUnlocked = [...new Set(debugUnlockedSource.filter(id => definitionById.has(id)))]; - if (!DEBUG_MODE) { - for (const id of debugUnlocked) delete unlocked[id]; - } - const pendingSource = Array.isArray(parsed.pending) ? parsed.pending : []; - const pending = pendingSource.filter(id => definitionById.has(id) && !debugUnlocked.includes(id)); - if (unlocked.mechanized_industry && !pending.includes("mechanized_industry") - && (pendingSource.includes("signal_automation_first") || pendingSource.includes("link_craftsman"))) { - pending.push("mechanized_industry"); - } - const progressSource = parsed.progress && typeof parsed.progress === "object" ? parsed.progress : {}; - const legacyLinkTypes = Number(unlockedSource.link_craftsman || 0) > 0 ? ["rope", "rod", "spring"] : []; - const progress = { - placementCount: Math.max(0, Math.floor(Number(progressSource.placementCount || 0) || 0)), - linkTypes: [...new Set([...(Array.isArray(progressSource.linkTypes) ? progressSource.linkTypes : []), ...legacyLinkTypes].filter(type => ["rope", "rod", "spring"].includes(type)))], - signalActivated: Boolean(progressSource.signalActivated || unlockedSource.signal_automation_first), - antKills: Math.max(0, Math.floor(Number(progressSource.antKills || 0) || 0)), - birthCount: Math.max(0, Math.floor(Number(progressSource.birthCount || 0) || 0)), - quickDeleteCount: Math.max(0, Math.floor(Number(progressSource.quickDeleteCount || 0) || 0)), - undoCount: Math.max(0, Math.floor(Number(progressSource.undoCount || 0) || 0)), - redoCount: Math.max(0, Math.floor(Number(progressSource.redoCount || 0) || 0)), - medicineTypes: [...new Set((Array.isArray(progressSource.medicineTypes) ? progressSource.medicineTypes : []).filter(type => MEDICINE_LEDGER_TYPES.includes(type)))], - firstAidHeals: Math.max(0, Math.floor(Number(progressSource.firstAidHeals || 0) || 0)), - fightMochiFightCount: Math.max(0, Math.floor(Number(progressSource.fightMochiFightCount || 0) || 0)), - shotCount: Math.max(0, Math.floor(Number(progressSource.shotCount || 0) || 0)), - loveMochiBirthCount: Math.max(0, Math.floor(Number(progressSource.loveMochiBirthCount || 0) || 0)), - dailyPlayStreak: Math.min(DAILY_PLAY_TARGET, Math.max(0, Math.floor(Number(progressSource.dailyPlayStreak || 0) || 0))), - dailyPlayLastDay: Math.max(0, Math.floor(Number(progressSource.dailyPlayLastDay || 0) || 0)), - statsButtonPressCount: Math.min(STATISTICIAN_TARGET, Math.max(0, Math.floor(Number(progressSource.statsButtonPressCount || 0) || 0))), - totalDeathCount: Math.min(MEMENTO_MORI_TARGET, Math.max(0, Math.floor(Number(progressSource.totalDeathCount || 0) || 0))), - manualTarinaiAddedCount: Math.min(LIVELY_MAKING_TARGET, Math.max(0, Math.floor(Number(progressSource.manualTarinaiAddedCount || 0) || 0))), - }; - const missingCompletionRequirement = DEFINITIONS.some(definition => definition.id !== COMPLETIONIST_ID && !unlocked[definition.id]); - if (unlocked[COMPLETIONIST_ID] && missingCompletionRequirement) { - delete unlocked[COMPLETIONIST_ID]; - const pendingIndex = pending.indexOf(COMPLETIONIST_ID); - if (pendingIndex >= 0) pending.splice(pendingIndex, 1); - } - return { unlocked, pending: [...new Set(pending)], resetPending: Boolean(parsed.resetPending), debugUnlocked: DEBUG_MODE ? debugUnlocked : [], progress }; + return { generation: 0, revision: 0, updatedAt: 0, migrationComplete: false, state: normalizeState(parsed) }; } catch (_) { - return blankState(); + return null; } } + function mergeStateData(targetInput, sourceInput) { + const target = normalizeState(targetInput); + const source = normalizeState(sourceInput); + for (const [id, timestamp] of Object.entries(source.unlocked)) { + const current = Number(target.unlocked[id] || 0) || 0; + target.unlocked[id] = current > 0 ? Math.min(current, timestamp) : timestamp; + } + target.pending = [...new Set([...target.pending, ...source.pending])] + .filter(id => definitionById.has(id) && target.unlocked[id] && !target.debugUnlocked.includes(id)); + if (DEBUG_MODE) target.debugUnlocked = [...new Set([...target.debugUnlocked, ...source.debugUnlocked])]; + if (!target.serverIdentity && source.serverIdentity) target.serverIdentity = { ...source.serverIdentity }; + for (const key of ADDITIVE_PROGRESS_KEYS) { + target._progressLedger.base[key] = Math.max( + Number(target._progressLedger.base[key] || 0) || 0, + Number(source._progressLedger.base[key] || 0) || 0, + ); + const targetShards = target._progressLedger.shards[key] || (target._progressLedger.shards[key] = {}); + const sourceShards = source._progressLedger.shards[key] || {}; + for (const [actorId, value] of Object.entries(sourceShards)) { + targetShards[actorId] = Math.max(Number(targetShards[actorId] || 0) || 0, Number(value || 0) || 0); + } + } + // Daily streak and its last-day marker are one logical record. Merging the + // two numbers independently can pair an old high streak with a new date. + const targetDay = Number(target.progress.dailyPlayLastDay || 0) || 0; + const sourceDay = Number(source.progress.dailyPlayLastDay || 0) || 0; + if (sourceDay > targetDay) { + target.progress.dailyPlayLastDay = sourceDay; + target.progress.dailyPlayStreak = Number(source.progress.dailyPlayStreak || 0) || 0; + } else if (sourceDay === targetDay) { + target.progress.dailyPlayStreak = Math.max(Number(target.progress.dailyPlayStreak || 0) || 0, Number(source.progress.dailyPlayStreak || 0) || 0); + } + target.progress.signalActivated = Boolean(target.progress.signalActivated || source.progress.signalActivated); + target.progress.linkTypes = [...new Set([...(target.progress.linkTypes || []), ...(source.progress.linkTypes || [])])]; + target.progress.medicineTypes = [...new Set([...(target.progress.medicineTypes || []), ...(source.progress.medicineTypes || [])])]; + target.progress.mysteryDrugTarinaiIds = [...new Set([...(target.progress.mysteryDrugTarinaiIds || []), ...(source.progress.mysteryDrugTarinaiIds || [])])].slice(0, MAD_SCIENTIST_TARGET); + return normalizeState(target); + } + + function growOnlyStateDelta(baseInput, currentInput) { + const base = normalizeState(baseInput); + const current = normalizeState(currentInput); + const delta = blankState(); + for (const [id, timestamp] of Object.entries(current.unlocked)) { + const previous = Number(base.unlocked[id] || 0) || 0; + if (!previous || timestamp < previous) delta.unlocked[id] = timestamp; + } + delta.pending = current.pending.filter(id => delta.unlocked[id]); + if (DEBUG_MODE) delta.debugUnlocked = current.debugUnlocked.filter(id => !base.debugUnlocked.includes(id)); + if (current.serverIdentity && (!base.serverIdentity || current.serverIdentity.playerId !== base.serverIdentity.playerId || current.serverIdentity.playerSecret !== base.serverIdentity.playerSecret)) { + delta.serverIdentity = { ...current.serverIdentity }; + } + for (const key of ADDITIVE_PROGRESS_KEYS) { + const currentBase = Number(current._progressLedger.base[key] || 0) || 0; + const baselineBase = Number(base._progressLedger.base[key] || 0) || 0; + if (currentBase > baselineBase) delta._progressLedger.base[key] = currentBase; + const currentShards = current._progressLedger.shards[key] || {}; + const baselineShards = base._progressLedger.shards[key] || {}; + const deltaShards = delta._progressLedger.shards[key] + || (delta._progressLedger.shards[key] = {}); + for (const [actorId, value] of Object.entries(currentShards)) { + if ((Number(value) || 0) > (Number(baselineShards[actorId]) || 0)) { + deltaShards[actorId] = Number(value) || 0; + } + } + } + const currentDay = Number(current.progress.dailyPlayLastDay || 0) || 0; + const baseDay = Number(base.progress.dailyPlayLastDay || 0) || 0; + const currentStreak = Number(current.progress.dailyPlayStreak || 0) || 0; + const baseStreak = Number(base.progress.dailyPlayStreak || 0) || 0; + if (currentDay !== baseDay) { + delta.progress.dailyPlayLastDay = currentDay; + delta.progress.dailyPlayStreak = currentStreak; + } else if (currentStreak > baseStreak) { + delta.progress.dailyPlayStreak = currentStreak; + } + delta.progress.signalActivated = Boolean(current.progress.signalActivated && !base.progress.signalActivated); + delta.progress.linkTypes = current.progress.linkTypes.filter(value => !base.progress.linkTypes.includes(value)); + delta.progress.medicineTypes = current.progress.medicineTypes.filter(value => !base.progress.medicineTypes.includes(value)); + delta.progress.mysteryDrugTarinaiIds = current.progress.mysteryDrugTarinaiIds.filter(value => !base.progress.mysteryDrugTarinaiIds.includes(value)); + return normalizeState(delta); + } + + function readStorageCandidate(storage, key) { + try { return decodePersistenceEnvelope(storage?.getItem?.(key) || null); } + catch (_) { return null; } + } + + function webStorageCandidates() { + return [ + readStorageCandidate(global.localStorage, STORAGE_KEY), + readStorageCandidate(global.localStorage, STORAGE_BACKUP_KEY), + readStorageCandidate(global.sessionStorage, STORAGE_SESSION_KEY), + ].filter(Boolean); + } + + function legacyWebStorageCandidates() { + return [ + readStorageCandidate(global.localStorage, PREVIOUS_STORAGE_KEY), + readStorageCandidate(global.localStorage, PREVIOUS_STORAGE_BACKUP_KEY), + readStorageCandidate(global.sessionStorage, PREVIOUS_STORAGE_SESSION_KEY), + readStorageCandidate(global.localStorage, OLDER_STORAGE_KEY), + readStorageCandidate(global.localStorage, OLDER_STORAGE_BACKUP_KEY), + readStorageCandidate(global.sessionStorage, OLDER_STORAGE_SESSION_KEY), + readStorageCandidate(global.localStorage, LEGACY_STORAGE_KEY), + readStorageCandidate(global.localStorage, LEGACY_STORAGE_BACKUP_KEY), + readStorageCandidate(global.sessionStorage, LEGACY_STORAGE_SESSION_KEY), + readStorageCandidate(global.localStorage, ANCIENT_STORAGE_KEY), + readStorageCandidate(global.localStorage, ANCIENT_STORAGE_BACKUP_KEY), + readStorageCandidate(global.sessionStorage, ANCIENT_STORAGE_SESSION_KEY), + ].filter(Boolean); + } + + function decodePreHydrationJournal(raw) { + try { + const parsed = typeof raw === "string" ? JSON.parse(raw) : raw; + if (!parsed || parsed.format !== PREHYDRATION_JOURNAL_FORMAT || !parsed.delta || typeof parsed.delta !== "object") return null; + return { + format: PREHYDRATION_JOURNAL_FORMAT, + actorId: String(parsed.actorId || "").slice(0, 160), + baseGeneration: Math.max(0, Math.floor(Number(parsed.baseGeneration || 0) || 0)), + updatedAt: Math.max(0, Number(parsed.updatedAt || 0) || 0), + delta: normalizeState(parsed.delta), + }; + } catch (_) { + return null; + } + } + + function storageJournalCandidates(storage) { + const journals = []; + try { + const length = Math.max(0, Number(storage?.length || 0) || 0); + for (let index = 0; index < length; index += 1) { + const key = String(storage?.key?.(index) || ""); + if (!key.startsWith(PREHYDRATION_JOURNAL_PREFIX)) continue; + const journal = decodePreHydrationJournal(storage?.getItem?.(key)); + if (journal) journals.push(journal); + } + } catch (_) {} + return journals; + } + + function webStorageJournals() { + return [...storageJournalCandidates(global.localStorage), ...storageJournalCandidates(global.sessionStorage)]; + } + + function currentPreHydrationJournal() { + return { + format: PREHYDRATION_JOURNAL_FORMAT, + actorId: persistenceActorId, + baseGeneration: persistenceGeneration, + updatedAt: Date.now(), + delta: growOnlyStateDelta(initialPersistenceBaseline, state), + }; + } + + function writePreHydrationJournalToWebStorage(journalInput) { + const journal = decodePreHydrationJournal(journalInput); + if (!journal) return false; + let serialized = ""; + try { serialized = JSON.stringify(journal); } catch (_) { return false; } + const key = `${PREHYDRATION_JOURNAL_PREFIX}${persistenceActorId}`; + let stored = false; + try { global.localStorage?.setItem?.(key, serialized); stored = true; } catch (_) {} + try { global.sessionStorage?.setItem?.(key, serialized); stored = true; } catch (_) {} + return stored; + } + + function removeWebStorageJournals(maxGeneration = persistenceGeneration) { + for (const storage of [global.localStorage, global.sessionStorage]) { + try { + const keys = []; + const length = Math.max(0, Number(storage?.length || 0) || 0); + for (let index = 0; index < length; index += 1) { + const key = String(storage?.key?.(index) || ""); + if (key.startsWith(PREHYDRATION_JOURNAL_PREFIX)) keys.push(key); + } + for (const key of keys) { + const journal = decodePreHydrationJournal(storage?.getItem?.(key)); + if (!journal || journal.baseGeneration <= maxGeneration) storage?.removeItem?.(key); + } + } catch (_) {} + } + } + + function persistenceStateSignature(generation, stateInput) { + try { return `${Math.max(0, Number(generation) || 0)}:${JSON.stringify(normalizeState(stateInput))}`; } + catch (_) { return `${Math.max(0, Number(generation) || 0)}:`; } + } + + function normalizePersistenceCandidate(candidate) { + if (candidate && typeof candidate === "object" && candidate.state && typeof candidate.state === "object" && Number.isFinite(Number(candidate.generation))) { + return { + generation: Math.max(0, Math.floor(Number(candidate.generation || 0) || 0)), + revision: Math.max(0, Math.floor(Number(candidate.revision || 0) || 0)), + updatedAt: Math.max(0, Number(candidate.updatedAt || 0) || 0), + migrationComplete: Boolean(candidate.migrationComplete), + state: normalizeState(candidate.state), + }; + } + return decodePersistenceEnvelope(candidate); + } + + function mergePersistenceEnvelopes(candidatesInput, options = {}) { + const candidates = (Array.isArray(candidatesInput) ? candidatesInput : []) + .map(candidate => normalizePersistenceCandidate(candidate)) + .filter(Boolean); + if (!candidates.length) { + return { + format: PERSISTENCE_FORMAT, + generation: 0, + revision: options.incrementRevision ? 1 : 0, + updatedAt: Date.now(), + migrationComplete: false, + state: blankState(), + }; + } + const generation = Math.max(...candidates.map(candidate => candidate.generation)); + const active = candidates + .filter(candidate => candidate.generation === generation) + .sort((a, b) => (a.revision - b.revision) || (a.updatedAt - b.updatedAt)); + let merged = blankState(); + for (const candidate of active) merged = mergeStateData(merged, candidate.state); + const latest = active[active.length - 1]; + merged.resetPending = Boolean(latest?.state?.resetPending); + const latestIdentity = [...active].reverse().map(candidate => normalizeServerIdentity(candidate.state?.serverIdentity)).find(Boolean); + if (latestIdentity) merged.serverIdentity = { ...latestIdentity }; + const maxRevision = Math.max(0, ...active.map(candidate => candidate.revision)); + return { + format: PERSISTENCE_FORMAT, + generation, + revision: maxRevision + (options.incrementRevision ? 1 : 0), + updatedAt: Date.now(), + migrationComplete: active.some(candidate => candidate.migrationComplete), + state: normalizeState(merged), + }; + } + + function loadStateRecord() { + const currentCandidates = webStorageCandidates(); + const currentGeneration = currentCandidates.length + ? Math.max(...currentCandidates.map(candidate => candidate.generation)) + : 0; + // v6 is written only by this build. Import older namespaces once, before a + // completed v6 envelope exists. This still repairs the v39.17.7 failure + // where an empty v5 envelope hid v4/v2 data, without reading old namespaces + // forever and allowing an old open tab to contaminate current storage. + const migrationComplete = currentCandidates.some(candidate => candidate.migrationComplete); + const legacyCandidates = currentGeneration === 0 && !migrationComplete ? legacyWebStorageCandidates() : []; + const candidates = [...currentCandidates, ...legacyCandidates]; + const source = currentCandidates.length && legacyCandidates.length + ? "mixed" + : (currentCandidates.length ? "current" : (legacyCandidates.length ? "legacy" : "empty")); + const merged = mergePersistenceEnvelopes(candidates); + return { + generation: merged.generation, + revision: merged.revision, + updatedAt: merged.updatedAt, + migrationComplete: merged.migrationComplete, + state: merged.state, + source, + }; + } + + function persistenceEnvelope() { + return { + format: PERSISTENCE_FORMAT, + generation: persistenceGeneration, + revision: persistenceRevision, + updatedAt: Date.now(), + migrationComplete: true, + state: normalizeState(state), + }; + } + + function adoptPersistenceEnvelope(envelopeInput) { + const envelope = normalizePersistenceCandidate(envelopeInput); + if (!envelope || envelope.generation < persistenceGeneration) return false; + const before = persistenceStateSignature(persistenceGeneration, state); + if (envelope.generation > persistenceGeneration) { + persistenceGeneration = envelope.generation; + persistenceRevision = envelope.revision; + state = normalizeState(envelope.state); + } else { + state = mergeStateData(state, envelope.state); + if (envelope.revision >= persistenceRevision) { + state.resetPending = Boolean(envelope.state.resetPending); + const newerIdentity = normalizeServerIdentity(envelope.state.serverIdentity); + if (newerIdentity) state.serverIdentity = { ...newerIdentity }; + } + persistenceRevision = Math.max(persistenceRevision, envelope.revision); + } + return before !== persistenceStateSignature(persistenceGeneration, state); + } + + function writeEnvelopeToWebStorage(envelopeInput) { + const envelope = normalizePersistenceCandidate(envelopeInput); + if (!envelope) return false; + let serialized = ""; + try { + serialized = JSON.stringify({ + format: PERSISTENCE_FORMAT, + generation: envelope.generation, + revision: envelope.revision, + updatedAt: envelope.updatedAt || Date.now(), + migrationComplete: Boolean(envelope.migrationComplete), + state: normalizeState(envelope.state), + }); + } catch (_) { + return false; + } + let stored = false; + try { global.localStorage?.setItem?.(STORAGE_BACKUP_KEY, serialized); stored = true; } catch (_) {} + try { global.localStorage?.setItem?.(STORAGE_KEY, serialized); stored = true; } catch (_) {} + try { global.sessionStorage?.setItem?.(STORAGE_SESSION_KEY, serialized); stored = true; } catch (_) {} + return stored; + } + + function broadcastPersistenceEnvelope(envelopeInput) { + const envelope = normalizePersistenceCandidate(envelopeInput); + if (!envelope) return; + try { persistenceChannel?.postMessage?.(envelope); } catch (_) {} + } + + function openPersistenceDatabase(databaseName = PERSISTENCE_DB_NAME) { + return new Promise((resolve, reject) => { + if (!global.indexedDB?.open) return reject(new Error("indexeddb unavailable")); + let request; + try { request = global.indexedDB.open(databaseName, 1); } + catch (error) { reject(error); return; } + request.onupgradeneeded = () => { + const db = request.result; + if (!db.objectStoreNames.contains(PERSISTENCE_DB_STORE)) db.createObjectStore(PERSISTENCE_DB_STORE); + }; + request.onsuccess = () => resolve(request.result); + request.onerror = () => reject(request.error || new Error("indexeddb open failed")); + request.onblocked = () => reject(new Error("indexeddb blocked")); + }); + } + + async function readDurableEnvelope(databaseName = PERSISTENCE_DB_NAME) { + let db = null; + try { + db = await openPersistenceDatabase(databaseName); + return await new Promise((resolve, reject) => { + const tx = db.transaction(PERSISTENCE_DB_STORE, "readonly"); + const request = tx.objectStore(PERSISTENCE_DB_STORE).get(PERSISTENCE_DB_KEY); + request.onsuccess = () => resolve(decodePersistenceEnvelope(request.result)); + request.onerror = () => reject(request.error || new Error("indexeddb read failed")); + tx.onabort = () => reject(tx.error || new Error("indexeddb read aborted")); + }); + } catch (_) { + return null; + } finally { + try { db?.close?.(); } catch (_) {} + } + } + + async function readDurableJournals() { + let db = null; + try { + db = await openPersistenceDatabase(); + return await new Promise((resolve, reject) => { + const journals = []; + const tx = db.transaction(PERSISTENCE_DB_STORE, "readonly"); + const store = tx.objectStore(PERSISTENCE_DB_STORE); + const request = store.openCursor(); + request.onsuccess = () => { + const cursor = request.result; + if (!cursor) return; + if (String(cursor.key || "").startsWith(PREHYDRATION_JOURNAL_DB_PREFIX)) { + const journal = decodePreHydrationJournal(cursor.value); + if (journal) journals.push(journal); + } + cursor.continue(); + }; + request.onerror = () => reject(request.error || new Error("indexeddb journal read failed")); + tx.oncomplete = () => resolve(journals); + tx.onerror = () => reject(tx.error || new Error("indexeddb journal transaction failed")); + tx.onabort = () => reject(tx.error || new Error("indexeddb journal read aborted")); + }); + } catch (_) { + return []; + } finally { + try { db?.close?.(); } catch (_) {} + } + } + + async function writeDurableJournal(journalInput) { + const journal = decodePreHydrationJournal(journalInput); + if (!journal) return false; + let db = null; + try { + db = await openPersistenceDatabase(); + return await new Promise((resolve, reject) => { + const tx = db.transaction(PERSISTENCE_DB_STORE, "readwrite"); + tx.objectStore(PERSISTENCE_DB_STORE).put(journal, `${PREHYDRATION_JOURNAL_DB_PREFIX}${journal.actorId || persistenceActorId}`); + tx.oncomplete = () => resolve(true); + tx.onerror = () => reject(tx.error || new Error("indexeddb journal write failed")); + tx.onabort = () => reject(tx.error || new Error("indexeddb journal write aborted")); + }); + } catch (_) { + return false; + } finally { + try { db?.close?.(); } catch (_) {} + } + } + + async function removeDurableJournals(maxGeneration = persistenceGeneration) { + let db = null; + try { + db = await openPersistenceDatabase(); + await new Promise((resolve, reject) => { + const tx = db.transaction(PERSISTENCE_DB_STORE, "readwrite"); + const store = tx.objectStore(PERSISTENCE_DB_STORE); + const request = store.openCursor(); + request.onsuccess = () => { + const cursor = request.result; + if (!cursor) return; + if (String(cursor.key || "").startsWith(PREHYDRATION_JOURNAL_DB_PREFIX)) { + const journal = decodePreHydrationJournal(cursor.value); + if (!journal || journal.baseGeneration <= maxGeneration) cursor.delete(); + } + cursor.continue(); + }; + request.onerror = () => reject(request.error || new Error("indexeddb journal cleanup failed")); + tx.oncomplete = () => resolve(true); + tx.onerror = () => reject(tx.error || new Error("indexeddb journal cleanup transaction failed")); + tx.onabort = () => reject(tx.error || new Error("indexeddb journal cleanup aborted")); + }); + } catch (_) { + return false; + } finally { + try { db?.close?.(); } catch (_) {} + } + return true; + } + + async function writeDurableEnvelope(envelopeInput) { + const incoming = normalizePersistenceCandidate(envelopeInput); + if (!incoming) return null; + let db = null; + try { + db = await openPersistenceDatabase(); + return await new Promise((resolve, reject) => { + const tx = db.transaction(PERSISTENCE_DB_STORE, "readwrite"); + const store = tx.objectStore(PERSISTENCE_DB_STORE); + const request = store.get(PERSISTENCE_DB_KEY); + let committed = incoming; + request.onsuccess = () => { + const existing = normalizePersistenceCandidate(request.result); + if (existing?.generation > incoming.generation) { + committed = existing; + } else if (existing?.generation === incoming.generation) { + committed = mergePersistenceEnvelopes([existing, incoming], { incrementRevision: true }); + } + if (existing?.generation > incoming.generation) return; + try { store.put(committed, PERSISTENCE_DB_KEY); } + catch (error) { reject(error); } + }; + request.onerror = () => reject(request.error || new Error("indexeddb read before write failed")); + tx.oncomplete = () => resolve(committed); + tx.onerror = () => reject(tx.error || new Error("indexeddb write failed")); + tx.onabort = () => reject(tx.error || new Error("indexeddb write aborted")); + }); + } catch (_) { + return null; + } finally { + try { db?.close?.(); } catch (_) {} + } + } + + function handleExternalPersistenceEnvelope(envelopeInput, options = {}) { + const envelope = normalizePersistenceCandidate(envelopeInput); + if (!envelope) return false; + const changed = adoptPersistenceEnvelope(envelope); + if (!changed) return false; + const merged = mergePersistenceEnvelopes([persistenceEnvelope(), envelope], { incrementRevision: true }); + adoptPersistenceEnvelope(merged); + writeEnvelopeToWebStorage(merged); + if (options.broadcast !== false) broadcastPersistenceEnvelope(merged); + durableWriteQueue = durableWriteQueue.then( + () => writeDurableEnvelope(merged), + () => writeDurableEnvelope(merged), + ).then(committed => { + if (!committed) return null; + const durableChanged = adoptPersistenceEnvelope(committed); + writeEnvelopeToWebStorage(committed); + if (durableChanged) { + broadcastPersistenceEnvelope(committed); + render({ forceList: true }); + } + return committed; + }); + render({ forceList: true }); + return true; + } + + function setupPersistenceCrossTabSync() { + try { + if (typeof global.BroadcastChannel === "function") { + persistenceChannel = new global.BroadcastChannel(PERSISTENCE_CHANNEL_NAME); + persistenceChannel.addEventListener?.("message", event => { + handleExternalPersistenceEnvelope(event?.data, { broadcast: true }); + }); + } + } catch (_) { + persistenceChannel = null; + } + global.addEventListener?.("storage", event => { + if (![STORAGE_KEY, STORAGE_BACKUP_KEY].includes(String(event?.key || ""))) return; + handleExternalPersistenceEnvelope(event?.newValue, { broadcast: true }); + }); + } + + function persistStateNow() { + persistenceDirty = false; + const current = persistenceEnvelope(); + const envelope = mergePersistenceEnvelopes([current, ...webStorageCandidates()], { incrementRevision: true }); + adoptPersistenceEnvelope(envelope); + const stored = writeEnvelopeToWebStorage(envelope); + broadcastPersistenceEnvelope(envelope); + durableWriteQueue = durableWriteQueue.then( + () => writeDurableEnvelope(envelope), + () => writeDurableEnvelope(envelope), + ).then(committed => { + if (!committed) return null; + const changed = adoptPersistenceEnvelope(committed); + writeEnvelopeToWebStorage(committed); + if (changed) { + broadcastPersistenceEnvelope(committed); + render({ forceList: true }); + } + return committed; + }); + return stored; + } + function saveState() { - try { global.localStorage?.setItem(STORAGE_KEY, JSON.stringify(state)); } - catch (_) {} + persistenceDirty = true; + if (!persistenceHydrated) { + const journal = currentPreHydrationJournal(); + const stored = writePreHydrationJournalToWebStorage(journal); + durableWriteQueue = durableWriteQueue.then( + () => writeDurableJournal(journal), + () => writeDurableJournal(journal), + ); + return stored; + } + return persistStateNow(); + } + + async function hydrateDurableState() { + try { + const persistRequest = global.navigator?.storage?.persist?.(); + persistRequest?.catch?.(() => false); + } catch (_) {} + + const [currentDurable, previousDurable, olderDurable, legacyDurable, ancientDurable, durableJournals] = await Promise.all([ + readDurableEnvelope(PERSISTENCE_DB_NAME), + readDurableEnvelope(PREVIOUS_PERSISTENCE_DB_NAME), + readDurableEnvelope(OLDER_PERSISTENCE_DB_NAME), + readDurableEnvelope(LEGACY_PERSISTENCE_DB_NAME), + readDurableEnvelope(ANCIENT_PERSISTENCE_DB_NAME), + readDurableJournals(), + ]); + const currentCandidates = [...webStorageCandidates(), currentDurable].filter(Boolean); + const currentGeneration = currentCandidates.length + ? Math.max(...currentCandidates.map(candidate => candidate.generation)) + : 0; + const migrationComplete = currentCandidates.some(candidate => candidate.migrationComplete); + const legacyCandidates = currentGeneration === 0 && !migrationComplete + ? [...legacyWebStorageCandidates(), previousDurable, olderDurable, legacyDurable, ancientDurable].filter(Boolean) + : []; + const baseEnvelope = mergePersistenceEnvelopes([...currentCandidates, ...legacyCandidates]); + const preHydrationDelta = growOnlyStateDelta(initialPersistenceBaseline, state); + const journals = [...webStorageJournals(), ...durableJournals] + .filter(journal => journal.baseGeneration === baseEnvelope.generation); + + let mergedState = baseEnvelope.state; + if (initialPersistence.generation === baseEnvelope.generation) { + mergedState = mergeStateData(mergedState, preHydrationDelta); + } + for (const journal of journals) mergedState = mergeStateData(mergedState, journal.delta); + + persistenceGeneration = baseEnvelope.generation; + persistenceRevision = baseEnvelope.revision; + state = normalizeState(mergedState); + state.resetPending = Boolean(baseEnvelope.state.resetPending); + persistenceHydrated = true; + persistStateNow(); + await durableWriteQueue.catch(() => null); + removeWebStorageJournals(persistenceGeneration); + await removeDurableJournals(persistenceGeneration); + render({ forceList: true }); + return true; } function scheduleProgressSave(delay = 350) { @@ -325,6 +872,11 @@ }, Math.max(0, Number(delay) || 0)); } + function markProgressMutation() { + progressMutationRevision += 1; + if (!DEBUG_MODE && global.location?.protocol !== "file:") schedulePendingSync(); + } + function createPlayerId() { if (global.crypto?.randomUUID) return global.crypto.randomUUID(); const hex = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"; @@ -334,19 +886,104 @@ }); } - function playerId() { + function createPlayerSecret() { + const bytes = new Uint8Array(32); + if (global.crypto?.getRandomValues) global.crypto.getRandomValues(bytes); + else for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256); + return [...bytes].map(value => value.toString(16).padStart(2, "0")).join(""); + } + + function storageServerIdentity(storage) { try { - const stored = String(global.localStorage?.getItem(PLAYER_KEY) || ""); - if (PLAYER_ID_PATTERN.test(stored)) return stored; - const next = createPlayerId(); - global.localStorage?.setItem(PLAYER_KEY, next); - return next; + return normalizeServerIdentity({ + playerId: storage?.getItem?.(PLAYER_KEY), + playerSecret: storage?.getItem?.(PLAYER_SECRET_KEY), + }); } catch (_) { - if (!playerId.memory) playerId.memory = createPlayerId(); - return playerId.memory; + return null; } } + function legacyPlayerId() { + const candidates = []; + for (const storage of [global.localStorage, global.sessionStorage]) { + try { + candidates.push(storage?.getItem?.(LEGACY_PLAYER_KEY)); + candidates.push(storage?.getItem?.(PLAYER_KEY)); + } catch (_) {} + } + candidates.push(legacyPlayerId.memory); + const legacyId = candidates.map(value => String(value || "")).find(value => LEGACY_PLAYER_ID_PATTERN.test(value)) || ""; + if (!legacyId) return ""; + legacyPlayerId.memory = legacyId; + for (const storage of [global.localStorage, global.sessionStorage]) { + try { storage?.setItem?.(LEGACY_PLAYER_KEY, legacyId); } catch (_) {} + } + return legacyId; + } + + function clearLegacyPlayerId() { + legacyPlayerId.memory = ""; + for (const storage of [global.localStorage, global.sessionStorage]) { + try { storage?.removeItem?.(LEGACY_PLAYER_KEY); } catch (_) {} + } + } + + function currentServerIdentity() { + return storageServerIdentity(global.localStorage) + || storageServerIdentity(global.sessionStorage) + || normalizeServerIdentity(state?.serverIdentity) + || normalizeServerIdentity(currentServerIdentity.memory); + } + + function persistServerIdentity(identityInput, options = {}) { + const identity = normalizeServerIdentity(identityInput); + if (!identity) return false; + currentServerIdentity.memory = identity; + for (const storage of [global.localStorage, global.sessionStorage]) { + try { + storage?.setItem?.(PLAYER_KEY, identity.playerId); + storage?.setItem?.(PLAYER_SECRET_KEY, identity.playerSecret); + } catch (_) {} + } + const before = normalizeServerIdentity(state?.serverIdentity); + const changed = !before || before.playerId !== identity.playerId || before.playerSecret !== identity.playerSecret; + if (state && typeof state === "object") state.serverIdentity = { ...identity }; + if (changed && options.save !== false) saveState(); + return true; + } + + function ensureServerIdentity() { + // Capture the legacy bearer ID before the current UUID overwrites the old + // localStorage slot. It is retained until the server confirms the claim. + legacyPlayerId(); + const existing = currentServerIdentity(); + if (existing) { + persistServerIdentity(existing, { save: false }); + return existing; + } + const created = { playerId: createPlayerId(), playerSecret: createPlayerSecret() }; + persistServerIdentity(created); + return created; + } + + function playerId() { + return ensureServerIdentity().playerId; + } + + function playerSecret() { + return ensureServerIdentity().playerSecret; + } + + function storeServerCredentials(data) { + const stored = persistServerIdentity({ + playerId: String(data?.playerId || "").toLowerCase(), + playerSecret: String(data?.playerSecret || "").toLowerCase(), + }); + if (stored && data?.legacyClaimed === true) clearLegacyPlayerId(); + return stored; + } + function unlockedCount() { return DEFINITIONS.reduce((sum, def) => sum + (state.unlocked[def.id] ? 1 : 0), 0); } @@ -384,14 +1021,17 @@ } function sharedAchievementText(id) { - return `\u5168\u4f53\u9054\u6210\u7387 ${percentageText(id)}\uff08\u9054\u6210\u8005 ${achieverCountText(id)}\uff09`; + return `達成率 ${percentageText(id)}(達成人数 ${achieverCountText(id)})`; } function continuousPlayElapsedMs(now = Date.now()) { if (state.unlocked.continuous_play_24_hours) return CONTINUOUS_PLAY_24H_TARGET_MS; const timestamp = Number(now); - if (!continuousPlayStartedAt || !Number.isFinite(timestamp)) return 0; - return Math.max(0, timestamp - continuousPlayStartedAt); + if (!Number.isFinite(timestamp)) return Math.max(0, continuousPlayAccumulatedMs); + const activeSegment = continuousPlayActive && !document.hidden && timestamp >= continuousPlayLastHeartbeatAt + ? timestamp - continuousPlayLastHeartbeatAt + : 0; + return Math.max(0, continuousPlayAccumulatedMs + activeSegment); } function formatElapsed(ms = 0) { @@ -402,29 +1042,18 @@ } function localProgressText(id) { - if (id === "great_mother_1000_births") { - const target = 3333; - const count = state.unlocked[id] ? target : Math.min(target, Math.max(0, Math.floor(Number(state.progress?.birthCount || 0) || 0))); - return `\u73fe\u5728\u306e\u9054\u6210\u7387 ${(count / target * 100).toFixed(1)}%\uff08${count} / ${target}\u4f53\uff09`; - } - if (id === "town_doctor_50") { - const target = 50; - const count = state.unlocked[id] ? target : Math.min(target, Math.max(0, Math.floor(Number(state.progress?.firstAidHeals || 0) || 0))); - return `\u73fe\u5728 ${count} / ${target}\u56de`; - } - if (id === "chaos_seeker_666_fights") { - const target = CHAOS_FIGHT_TARGET; - const count = state.unlocked[id] ? target : Math.min(target, Math.max(0, Math.floor(Number(state.progress?.fightMochiFightCount || 0) || 0))); - return `\u73fe\u5728\u306e\u9054\u6210\u7387 ${(count / target * 100).toFixed(1)}%\uff08${count} / ${target}\u56de\uff09`; - } - if (id === "fertility_seeker_721_love_births") { - const target = FERTILITY_BIRTH_TARGET; - const count = state.unlocked[id] ? target : Math.min(target, Math.max(0, Math.floor(Number(state.progress?.loveMochiBirthCount || 0) || 0))); - return `\u73fe\u5728\u306e\u9054\u6210\u7387 ${(count / target * 100).toFixed(1)}%\uff08${count} / ${target}\u56de\uff09`; - } - if (id === "daily_play_7_days") { - const count = state.unlocked[id] ? DAILY_PLAY_TARGET : Math.min(DAILY_PLAY_TARGET, Math.max(0, Math.floor(Number(state.progress?.dailyPlayStreak || 0) || 0))); - return `\u73fe\u5728\u306e\u9054\u6210\u7387 ${(count / DAILY_PLAY_TARGET * 100).toFixed(1)}%\uff08${count} / ${DAILY_PLAY_TARGET}\u65e5\uff09`; + const definition = definitionById.get(String(id || "")); + const spec = definition?.progress || null; + if (spec?.display) { + const target = Math.max(1, Math.floor(Number(spec.target || 0) || 0)); + let count = 0; + if (spec.type === "counter") count = progressCounter(spec.key); + else if (spec.type === "value") count = Math.max(0, Math.floor(Number(ensureProgress()[spec.key] || 0) || 0)); + else if (spec.type === "unique") count = ensureProgress()[spec.key]?.length || 0; + count = state.unlocked[id] ? target : Math.min(target, count); + const unit = String(spec.unit || ""); + if (spec.display === "percent") return `現在の達成率 ${(count / target * 100).toFixed(1)}%(${count} / ${target}${unit})`; + return `現在 ${count} / ${target}${unit}`; } if (id === "elite_few") { const world = global.world || null; @@ -435,32 +1064,20 @@ ? Math.min(ELITE_FEW_TARGET_DAYS, (now - startedAt) / dayLength) : 0; const aliveCount = (world?.tarinai || []).reduce((count, tarinai) => count + (tarinai && !tarinai.dead ? 1 : 0), 0); - return `\u73fe\u5728 ${elapsedDays.toFixed(1)} / ${ELITE_FEW_TARGET_DAYS}\u65e5\uff08\u500b\u4f53\u6570 ${aliveCount} / ${ELITE_FEW_MAX_POPULATION}\u4ee5\u4e0b\uff09`; - } - if (id === "statistician") { - const count = state.unlocked[id] ? STATISTICIAN_TARGET : Math.min(STATISTICIAN_TARGET, Math.max(0, Math.floor(Number(state.progress?.statsButtonPressCount || 0) || 0))); - return `\u73fe\u5728 ${count} / ${STATISTICIAN_TARGET}\u56de`; - } - if (id === "lively_making") { - const count = state.unlocked[id] ? LIVELY_MAKING_TARGET : Math.min(LIVELY_MAKING_TARGET, Math.max(0, Math.floor(Number(state.progress?.manualTarinaiAddedCount || 0) || 0))); - return `\u73fe\u5728 ${count} / ${LIVELY_MAKING_TARGET}\u4f53`; - } - if (id === "memento_mori") { - const count = state.unlocked[id] ? MEMENTO_MORI_TARGET : Math.min(MEMENTO_MORI_TARGET, Math.max(0, Math.floor(Number(state.progress?.totalDeathCount || 0) || 0))); - return `\u73fe\u5728\u306e\u9054\u6210\u7387 ${(count / MEMENTO_MORI_TARGET * 100).toFixed(1)}%\uff08${count} / ${MEMENTO_MORI_TARGET}\u4f53\uff09`; + return `現在 ${elapsedDays.toFixed(1)} / ${ELITE_FEW_TARGET_DAYS}日(個体数 ${aliveCount} / ${ELITE_FEW_MAX_POPULATION}以下)`; } if (id === "continuous_play_1_hour") { const elapsed = Math.min(CONTINUOUS_PLAY_TARGET_MS, continuousPlayElapsedMs()); - return `\u73fe\u5728\u306e\u9054\u6210\u7387 ${(elapsed / CONTINUOUS_PLAY_TARGET_MS * 100).toFixed(1)}%\uff08${formatElapsed(elapsed)} / 60:00\uff09`; + return `現在の達成率 ${(elapsed / CONTINUOUS_PLAY_TARGET_MS * 100).toFixed(1)}%(${formatElapsed(elapsed)} / 60:00)`; } if (id === "continuous_play_24_hours") { const elapsed = Math.min(CONTINUOUS_PLAY_24H_TARGET_MS, continuousPlayElapsedMs()); - return `\u73fe\u5728\u306e\u9054\u6210\u7387 ${(elapsed / CONTINUOUS_PLAY_24H_TARGET_MS * 100).toFixed(1)}%\uff08${formatElapsed(elapsed)} / 1440:00\uff09`; + return `現在の達成率 ${(elapsed / CONTINUOUS_PLAY_24H_TARGET_MS * 100).toFixed(1)}%(${formatElapsed(elapsed)} / 1440:00)`; } if (id === "enemy_enemy_friend") { const world = global.world || null; const count = state.unlocked[id] ? 10 : Math.min(10, Math.max(0, Math.floor(Number(world?.achievementEnemyAntKills || 0) || 0))); - return `\u73fe\u5728\u306e\u9054\u6210\u7387 ${(count * 10).toFixed(1)}%\uff08${count} / 10\u4f53\uff09`; + return `現在の達成率 ${(count * 10).toFixed(1)}%(${count} / 10体)`; } return ""; } @@ -475,18 +1092,21 @@ ? DEFINITIONS.map(definition => `${percentageValue(definition.id).toFixed(1)}:${achieverCountValue(definition.id) ?? "-"}`).join(",") : shared.loading ? "loading" : "offline"; const local = [ - Math.min(3333, Math.max(0, Number(state.progress?.birthCount || 0) || 0)), + progressCounter("birthCount"), Math.floor(continuousPlayElapsedMs() / 1000), Math.max(0, Math.floor(Number(global.__tarinaiFps || 0) || 0)), Math.min(10, Math.max(0, Number(global.world?.achievementEnemyAntKills || 0) || 0)), - Math.min(50, Math.max(0, Number(state.progress?.firstAidHeals || 0) || 0)), - Math.min(CHAOS_FIGHT_TARGET, Math.max(0, Number(state.progress?.fightMochiFightCount || 0) || 0)), - Math.min(FERTILITY_BIRTH_TARGET, Math.max(0, Number(state.progress?.loveMochiBirthCount || 0) || 0)), + progressCounter("firstAidHeals"), + progressCounter("fightMochiFightCount"), + progressCounter("loveMochiBirthCount"), Math.min(DAILY_PLAY_TARGET, Math.max(0, Number(state.progress?.dailyPlayStreak || 0) || 0)), Math.max(0, Number(state.progress?.dailyPlayLastDay || 0) || 0), - Math.min(STATISTICIAN_TARGET, Math.max(0, Number(state.progress?.statsButtonPressCount || 0) || 0)), - Math.min(MEMENTO_MORI_TARGET, Math.max(0, Number(state.progress?.totalDeathCount || 0) || 0)), - Math.min(LIVELY_MAKING_TARGET, Math.max(0, Number(state.progress?.manualTarinaiAddedCount || 0) || 0)), + progressCounter("statsButtonPressCount"), + progressCounter("totalDeathCount"), + progressCounter("manualTarinaiAddedCount"), + progressCounter("directFeedCount"), + progressCounter("robotCleanCount"), + Math.min(MAD_SCIENTIST_TARGET, state.progress?.mysteryDrugTarinaiIds?.length || 0), Math.floor(Math.max(0, (Number(global.world?.time || 0) || 0) - Math.max(0, Number(global.world?.achievementEliteFewStartAt || 0) || 0)) / Math.max(1, Number(global.world?.config?.dayLength ?? global.CONFIG?.dayLength ?? 120) || 120) * 10), ].join(":"); return `${unlocks}|${rates}|${local}`; @@ -573,7 +1193,7 @@ dom.button?.classList.toggle("complete", count === DEFINITIONS.length); if (dom.sharedStatus) { if (shared.loading) dom.sharedStatus.textContent = "\u5171\u6709\u9054\u6210\u7387\u3092\u78ba\u8a8d\u4e2d\u2026"; - else if (shared.connected) dom.sharedStatus.textContent = `\u5171\u6709\u96c6\u8a08: ${shared.totalPlayers}\u4eba\u306e\u30d7\u30ec\u30a4\u30e4\u30fc`; + else if (shared.connected) dom.sharedStatus.textContent = `共有集計(端末報告値): ${shared.totalPlayers}人のプレイヤー`; else dom.sharedStatus.textContent = "\u5171\u6709\u9054\u6210\u7387: \u672a\u63a5\u7d9a\uff08\u30ed\u30fc\u30ab\u30eb\u5b9f\u7e3e\u306f\u5229\u7528\u53ef\u80fd\uff09"; } if (!dom.list || dom.dialog?.classList.contains("hidden")) return; @@ -656,6 +1276,7 @@ function runNextUnlockToast() { if (toastActive || !toastQueue.length) return; const definition = toastQueue.shift(); + global.TarinaiAudio?.achievementUnlock?.(); if (!dom.toast || !dom.toastTitle) { global.showToast?.(`\u5b9f\u7e3e\u89e3\u9664: ${definition.title} \u2014 ${definition.description || ""}`); global.setTimeout(runNextUnlockToast, 80); @@ -691,15 +1312,22 @@ const options = payload ? { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify(payload), + body: JSON.stringify({ ...payload, playerSecret: playerSecret() }), signal: controller?.signal, cache: "no-store", } : { signal: controller?.signal, cache: "no-store" }; - const url = payload ? API_URL : `${API_URL}?action=summary&playerId=${encodeURIComponent(playerId())}`; + const url = payload ? API_URL : `${API_URL}?action=summary`; const response = await fetch(url, options); - if (!response.ok) throw new Error(`api ${response.status}`); - const data = await response.json(); - if (!data?.ok) throw new Error("api rejected"); + let data = null; + try { data = await response.json(); } catch (_) {} + if (!response.ok || !data?.ok) { + const error = new Error(`api ${response.status || 0}`); + error.status = Number(response.status || 0) || 0; + error.code = String(data?.error || "api_rejected"); + error.data = data; + throw error; + } + storeServerCredentials(data); return data; } finally { global.clearTimeout(timeout); @@ -712,6 +1340,7 @@ loading: false, totalPlayers: Math.max(0, Number(data?.totalPlayers || 0) || 0), achievements: data?.achievements && typeof data.achievements === "object" ? data.achievements : {}, + statisticsTrust: String(data?.statisticsTrust || "client-reported"), }; render(); } @@ -721,11 +1350,7 @@ shared.loading = true; render(); try { - const data = await request(options.session ? { - action: "session", - playerId: playerId(), - gameVersion: GAME_VERSION, - } : null); + const data = options.session ? await establishSession() : await request(null); if (serial === requestSerial) applyShared(data); return true; } catch (_) { @@ -746,35 +1371,209 @@ return unlocked; } + function localProgressSnapshot() { + const normalized = normalizeState(state); + return { + progress: JSON.parse(JSON.stringify(normalized.progress)), + ledger: JSON.parse(JSON.stringify(normalized._progressLedger)), + }; + } + + function completionistTimestamp() { + let latest = 0; + for (const definition of DEFINITIONS) { + if (definition.id === COMPLETIONIST_ID) continue; + const timestamp = Number(state.unlocked[definition.id] || 0) || 0; + if (!timestamp) return 0; + latest = Math.max(latest, timestamp); + } + return latest; + } + + function mergeServerUnlocks(data) { + const serverGenerationRaw = Number(data?.playerGeneration); + const hasServerGeneration = Number.isFinite(serverGenerationRaw) && serverGenerationRaw >= 0; + const serverGeneration = hasServerGeneration ? Math.floor(serverGenerationRaw) : persistenceGeneration; + if (serverGeneration < persistenceGeneration) return false; + + let changed = false; + if (serverGeneration > persistenceGeneration) { + // A reset committed by another tab/device wins over every older local tab. + const identity = currentServerIdentity(); + persistenceGeneration = serverGeneration; + persistenceRevision = 0; + state = blankState(); + if (identity) state.serverIdentity = { ...identity }; + progressMutationRevision = 0; + progressSyncedRevision = 0; + changed = true; + } + + const serverProgress = data?.playerProgress; + if (serverProgress && typeof serverProgress === "object" && !Array.isArray(serverProgress)) { + const beforeProgress = JSON.stringify({ progress: state.progress, ledger: state._progressLedger }); + const incoming = blankState(); + incoming.progress = serverProgress.progress && typeof serverProgress.progress === "object" ? serverProgress.progress : {}; + incoming._progressLedger = serverProgress.ledger && typeof serverProgress.ledger === "object" ? serverProgress.ledger : {}; + state = mergeStateData(state, incoming); + const afterProgress = JSON.stringify({ progress: state.progress, ledger: state._progressLedger }); + if (beforeProgress !== afterProgress) changed = true; + } + + const source = data?.playerUnlocked; + if (source && typeof source === "object" && !Array.isArray(source)) { + const serverIds = []; + for (const [id, serverTimestamp] of Object.entries(source)) { + if (!definitionById.has(id) || state.debugUnlocked?.includes?.(id)) continue; + const seconds = Number(serverTimestamp); + const serverTime = Number.isFinite(seconds) && seconds > 0 ? Math.max(1, Math.floor(seconds * 1000)) : Date.now(); + const localTime = Number(state.unlocked[id] || 0) || 0; + const sameSecond = localTime > 0 && Math.floor(localTime / 1000) === Math.floor(serverTime / 1000); + const mergedTime = localTime > 0 ? (sameSecond ? localTime : Math.min(localTime, serverTime)) : serverTime; + if (localTime !== mergedTime) { + state.unlocked[id] = mergedTime; + changed = true; + } + serverIds.push(id); + } + const confirmedSet = new Set(serverIds); + const beforePending = state.pending.length; + state.pending = state.pending.filter(id => !confirmedSet.has(id)); + if (state.pending.length !== beforePending) changed = true; + } + + const completionTime = completionistTimestamp(); + if (completionTime > 0) { + const current = Number(state.unlocked[COMPLETIONIST_ID] || 0) || 0; + const merged = current > 0 ? Math.max(current, completionTime) : completionTime; + if (current !== merged) { + state.unlocked[COMPLETIONIST_ID] = merged; + changed = true; + } + } + if (changed) { + saveState(); + render(); + } + return changed; + } + + async function establishSession(options = {}) { + const legacyId = legacyPlayerId(); + const payload = { + action: "session", + playerId: playerId(), + gameVersion: GAME_VERSION, + generation: persistenceGeneration, + }; + if (legacyId) payload.legacyPlayerId = legacyId; + const data = await request(payload); + if (options.merge !== false) mergeServerUnlocks(data); + return data; + } + async function performSyncPending(options = {}) { let latest = null; + const writeWithIdentityRecovery = async (payload, recoveryOptions = {}) => { + try { + const data = await request(payload); + mergeServerUnlocks(data); + return data; + } catch (error) { + const status = Number(error?.status || 0); + const code = String(error?.code || ""); + if (status === 409 && code === "stale_generation") { + // A reset from another device is authoritative. Merge it, but never + // replay this request's older-generation unlock/progress snapshot. + error.recoveredData = await establishSession({ merge: true }); + throw error; + } + if (status === 409 && code === "generation_ahead") { + // Compatibility recovery for servers that require an explicit full + // generation promotion after a backup restore or identity recreation. + const data = await request({ + action: "sync", + playerId: playerId(), + gameVersion: GAME_VERSION, + generation: persistenceGeneration, + generationRecovery: true, + syncProtocol: SYNC_PROTOCOL_VERSION, + mergeMode: "grow-only-union-v5", + unlocked: localUnlockSnapshot(), + progressState: localProgressSnapshot(), + }); + mergeServerUnlocks(data); + return data; + } + const recoverableIdentity = status === 403 && ["unknown_player", "invalid_owner"].includes(code); + if (!recoverableIdentity) throw error; + const sessionData = await establishSession({ merge: true }); + if (recoveryOptions.sessionOnly) return sessionData; + if (payload.action === "reset" && !state.resetPending) return sessionData; + const retryPayload = payload.action === "sync" ? { + action: "sync", + playerId: playerId(), + gameVersion: GAME_VERSION, + generation: persistenceGeneration, + generationRecovery: true, + syncProtocol: SYNC_PROTOCOL_VERSION, + mergeMode: "grow-only-union-v5", + unlocked: localUnlockSnapshot(), + progressState: localProgressSnapshot(), + } : { + ...payload, + playerId: playerId(), + generation: persistenceGeneration, + generationRecovery: true, + syncProtocol: SYNC_PROTOCOL_VERSION, + }; + const data = await request(retryPayload); + mergeServerUnlocks(data); + return data; + } + }; try { if (state.resetPending) { - latest = await request({ + latest = await writeWithIdentityRecovery({ action: "reset", playerId: playerId(), gameVersion: GAME_VERSION, - }); + confirmReset: "RESET_ACHIEVEMENTS", + catalogRevision: ACHIEVEMENT_CATALOG_REVISION, + generation: persistenceGeneration, + syncProtocol: SYNC_PROTOCOL_VERSION, + }, { mergeSession: false }); state.resetPending = false; saveState(); } + // Unlocks and progress are uploaded as one generation-scoped CRDT + // snapshot. The server unions actor shards, set-like progress and the + // earliest unlock timestamps, then returns the atomic merged state. const snapshot = localUnlockSnapshot(); + const progressSnapshot = localProgressSnapshot(); + const progressRevisionAtStart = progressMutationRevision; const pendingIds = [...new Set(state.pending.filter(id => definitionById.has(id) && snapshot[id]))]; const unlocked = options.full ? snapshot : Object.fromEntries(pendingIds.map(id => [id, snapshot[id]])); const syncedIds = Object.keys(unlocked); - if (syncedIds.length || options.full) { - latest = await request({ + const hasProgressChanges = progressRevisionAtStart > progressSyncedRevision; + if (options.full || syncedIds.length || hasProgressChanges) { + latest = await writeWithIdentityRecovery({ action: "sync", playerId: playerId(), gameVersion: GAME_VERSION, unlocked, - ...(options.full ? { completionistEligible: allOtherAchievementsUnlocked() } : {}), - }); - const syncedSet = new Set(syncedIds); - state.pending = state.pending.filter(id => !syncedSet.has(id)); + progressState: progressSnapshot, + mergeMode: "grow-only-union-v5", + syncProtocol: SYNC_PROTOCOL_VERSION, + generation: persistenceGeneration, + generationRecovery: true, + }, { mergeSession: false }); + const confirmedSet = new Set(syncedIds); + state.pending = state.pending.filter(id => !confirmedSet.has(id)); + progressSyncedRevision = Math.max(progressSyncedRevision, progressRevisionAtStart); saveState(); } else if (!latest) { return refreshShared({ session: true }); @@ -782,7 +1581,11 @@ if (latest) applyShared(latest); return true; - } catch (_) { + } catch (error) { + if (error?.recoveredData) { + applyShared(error.recoveredData); + return true; + } shared = { ...shared, connected: false, loading: false }; render(); return false; @@ -791,7 +1594,10 @@ function syncPending(options = {}) { const normalized = { full: Boolean(options.full) }; - const run = () => performSyncPending(normalized); + const run = async () => { + await persistenceReadyPromise; + return performSyncPending(normalized); + }; syncQueue = syncQueue.then(run, run); return syncQueue; } @@ -857,30 +1663,13 @@ return tracker; } - function generationRunLength(values = []) { - const sorted = [...new Set((values || []) - .map(value => Math.max(1, Math.floor(Number(value) || 0))) - .filter(Number.isFinite))].sort((a, b) => a - b); - let best = 0; - let run = 0; - let previous = null; - for (const generation of sorted) { - run = previous !== null && generation === previous + 1 ? run + 1 : 1; - best = Math.max(best, run); - previous = generation; - } - return best; - } - - function recordNaturalGeneration(world, tarinai, property, required) { + function recordNaturalGeneration(world, tarinai, depthKey, required) { if (!world || !tarinai) return 0; - const depthKey = property === "achievementNaturalSlaveGenerations" - ? "_achievementNaturalSlaveLineageDepth" - : "_achievementNaturalKingLineageDepth"; const parentIds = Array.isArray(tarinai.parents) ? tarinai.parents.filter(Boolean) : []; let parentDepth = 0; for (const parentId of parentIds) { - const parent = (world.tarinai || []).find(candidate => candidate && String(candidate.id || "") === String(parentId)); + const parent = (world.tarinai || []).find(candidate => candidate + && String(candidate.familyKey || candidate.id || "") === String(parentId)); parentDepth = Math.max(parentDepth, Math.max(0, Math.floor(Number(parent?.[depthKey] || 0) || 0))); } tarinai[depthKey] = Math.max(1, parentDepth + 1); @@ -901,29 +1690,57 @@ function ensureProgress() { if (!state.progress || typeof state.progress !== "object") state.progress = blankState().progress; if (!Array.isArray(state.progress.linkTypes)) state.progress.linkTypes = []; - state.progress.placementCount = Math.max(0, Math.floor(Number(state.progress.placementCount || 0) || 0)); + state.progress.linkTypes = [...new Set(state.progress.linkTypes.filter(type => LINK_PROGRESS_TYPES.includes(type)))]; state.progress.signalActivated = Boolean(state.progress.signalActivated); - state.progress.antKills = Math.max(0, Math.floor(Number(state.progress.antKills || 0) || 0)); - state.progress.birthCount = Math.max(0, Math.floor(Number(state.progress.birthCount || 0) || 0)); - state.progress.quickDeleteCount = Math.max(0, Math.floor(Number(state.progress.quickDeleteCount || 0) || 0)); - state.progress.undoCount = Math.max(0, Math.floor(Number(state.progress.undoCount || 0) || 0)); - state.progress.redoCount = Math.max(0, Math.floor(Number(state.progress.redoCount || 0) || 0)); if (!Array.isArray(state.progress.medicineTypes)) state.progress.medicineTypes = []; state.progress.medicineTypes = [...new Set(state.progress.medicineTypes.filter(type => MEDICINE_LEDGER_TYPES.includes(type)))]; - state.progress.firstAidHeals = Math.max(0, Math.floor(Number(state.progress.firstAidHeals || 0) || 0)); - state.progress.fightMochiFightCount = Math.max(0, Math.floor(Number(state.progress.fightMochiFightCount || 0) || 0)); - state.progress.shotCount = Math.max(0, Math.floor(Number(state.progress.shotCount || 0) || 0)); - state.progress.loveMochiBirthCount = Math.max(0, Math.floor(Number(state.progress.loveMochiBirthCount || 0) || 0)); state.progress.dailyPlayStreak = Math.min(DAILY_PLAY_TARGET, Math.max(0, Math.floor(Number(state.progress.dailyPlayStreak || 0) || 0))); state.progress.dailyPlayLastDay = Math.max(0, Math.floor(Number(state.progress.dailyPlayLastDay || 0) || 0)); - state.progress.statsButtonPressCount = Math.min(STATISTICIAN_TARGET, Math.max(0, Math.floor(Number(state.progress.statsButtonPressCount || 0) || 0))); - state.progress.totalDeathCount = Math.min(MEMENTO_MORI_TARGET, Math.max(0, Math.floor(Number(state.progress.totalDeathCount || 0) || 0))); - state.progress.manualTarinaiAddedCount = Math.min(LIVELY_MAKING_TARGET, Math.max(0, Math.floor(Number(state.progress.manualTarinaiAddedCount || 0) || 0))); + if (!Array.isArray(state.progress.mysteryDrugTarinaiIds)) state.progress.mysteryDrugTarinaiIds = []; + state.progress.mysteryDrugTarinaiIds = [...new Set(state.progress.mysteryDrugTarinaiIds.map(id => String(id || "")).filter(Boolean))].slice(0, MAD_SCIENTIST_TARGET); return state.progress; } - function hexByte(value = 0) { - return Math.max(0, Math.min(255, Number(value) || 0)).toString(16).padStart(2, "0"); + function ensureProgressLedger() { + state._progressLedger = sanitizeProgressLedger(state, state.progress || {}); + return state._progressLedger; + } + + function progressCounter(key) { + return ledgerCounterValue(ensureProgressLedger(), key); + } + + function raiseProgressCounter(key, minimumValue = 0) { + if (!Object.prototype.hasOwnProperty.call(ADDITIVE_PROGRESS_CAPS, key)) return 0; + const cap = ADDITIVE_PROGRESS_CAPS[key]; + const ledger = ensureProgressLedger(); + const current = ledgerCounterValue(ledger, key); + const target = Math.min(cap, Math.max(0, Math.floor(Number(minimumValue || 0) || 0))); + if (target <= current) return current; + ledger.base[key] = Math.min(cap, Math.max(0, Math.floor(Number(ledger.base[key] || 0) || 0)) + (target - current)); + if (target >= cap) { + ledger.base[key] = cap; + ledger.shards[key] = {}; + } + markProgressMutation(); + return target; + } + + function incrementProgressCounter(key, amount = 1) { + if (!Object.prototype.hasOwnProperty.call(ADDITIVE_PROGRESS_CAPS, key)) return 0; + const ledger = ensureProgressLedger(); + const cap = ADDITIVE_PROGRESS_CAPS[key]; + const current = ledgerCounterValue(ledger, key); + const increment = Math.min(Math.max(0, Math.floor(Number(amount || 0) || 0)), Math.max(0, cap - current)); + if (increment <= 0) return current; + const shards = ledger.shards[key] || (ledger.shards[key] = {}); + shards[persistenceActorId] = Math.max(0, Math.floor(Number(shards[persistenceActorId] || 0) || 0)) + increment; + if (current + increment >= cap) { + ledger.base[key] = cap; + ledger.shards[key] = {}; + } + markProgressMutation(); + return current + increment; } function unlockedIndexesFromMaskWords(lowWord = 0, highWord = 0, extraWord = 0) { @@ -973,31 +1790,35 @@ baseTimestamp, deltas, [ - state.unlocked.placed_objects_100 ? 0 : Math.min(100, progress.placementCount), + state.unlocked.placed_objects_100 ? 0 : Math.min(100, progressCounter("placementCount")), state.unlocked.mechanized_industry ? 0 : linkFlags, - state.unlocked.ants_killed_100 ? 0 : Math.min(100, progress.antKills), - state.unlocked.great_mother_1000_births ? 0 : Math.min(3333, progress.birthCount), - state.unlocked.unplanned_city_30 ? 0 : Math.min(30, progress.quickDeleteCount), - state.unlocked.undo_20 ? 0 : Math.min(20, progress.undoCount), - state.unlocked.redo_20 ? 0 : Math.min(20, progress.redoCount), + state.unlocked.ants_killed_100 ? 0 : Math.min(100, progressCounter("antKills")), + state.unlocked.great_mother_1000_births ? 0 : Math.min(3333, progressCounter("birthCount")), + state.unlocked.unplanned_city_30 ? 0 : Math.min(30, progressCounter("quickDeleteCount")), + state.unlocked.undo_20 ? 0 : Math.min(20, progressCounter("undoCount")), + state.unlocked.redo_20 ? 0 : Math.min(20, progressCounter("redoCount")), state.unlocked.medicine_ledger_all ? 0 : medicineMask, - state.unlocked.town_doctor_50 ? 0 : Math.min(50, progress.firstAidHeals), - state.unlocked.chaos_seeker_666_fights ? 0 : Math.min(CHAOS_FIGHT_TARGET, progress.fightMochiFightCount), - state.unlocked.sniper_333_shots ? 0 : Math.min(SNIPER_SHOT_TARGET, progress.shotCount), - state.unlocked.fertility_seeker_721_love_births ? 0 : Math.min(FERTILITY_BIRTH_TARGET, progress.loveMochiBirthCount), + state.unlocked.town_doctor_50 ? 0 : Math.min(50, progressCounter("firstAidHeals")), + state.unlocked.chaos_seeker_666_fights ? 0 : Math.min(CHAOS_FIGHT_TARGET, progressCounter("fightMochiFightCount")), + state.unlocked.sniper_333_shots ? 0 : Math.min(SNIPER_SHOT_TARGET, progressCounter("shotCount")), + state.unlocked.fertility_seeker_721_love_births ? 0 : Math.min(FERTILITY_BIRTH_TARGET, progressCounter("loveMochiBirthCount")), state.unlocked.daily_play_7_days ? 0 : Math.min(DAILY_PLAY_TARGET, progress.dailyPlayStreak), state.unlocked.daily_play_7_days ? 0 : Math.min(131071, progress.dailyPlayLastDay), - state.unlocked.statistician ? 0 : Math.min(STATISTICIAN_TARGET, progress.statsButtonPressCount), - state.unlocked.memento_mori ? 0 : Math.min(MEMENTO_MORI_TARGET, progress.totalDeathCount), - state.unlocked.lively_making ? 0 : Math.min(LIVELY_MAKING_TARGET, progress.manualTarinaiAddedCount), + state.unlocked.statistician ? 0 : Math.min(STATISTICIAN_TARGET, progressCounter("statsButtonPressCount")), + state.unlocked.memento_mori ? 0 : Math.min(MEMENTO_MORI_TARGET, progressCounter("totalDeathCount")), + state.unlocked.lively_making ? 0 : Math.min(LIVELY_MAKING_TARGET, progressCounter("manualTarinaiAddedCount")), + state.unlocked.mad_scientist ? 0 : Math.min(MAD_SCIENTIST_TARGET, progress.mysteryDrugTarinaiIds.length), + state.unlocked.direct_feed_33 ? 0 : Math.min(33, progressCounter("directFeedCount")), + state.unlocked.robot_cleaner_100 ? 0 : Math.min(ROBOT_CLEAN_TARGET, progressCounter("robotCleanCount")), ], + state.unlocked.mad_scientist ? [] : progress.mysteryDrugTarinaiIds.slice(0, MAD_SCIENTIST_TARGET), ]; } function parseSpellState(payload = null) { if (!Array.isArray(payload)) return null; const version = Number(payload[0]); - if (version !== SPELL_STATE_VERSION) return null; + if (![9, 10, SPELL_STATE_VERSION].includes(version)) return null; const lowWord = Number(payload[1]); const highWord = Number(payload[2]); const extraWord = Number(payload[3]); @@ -1012,6 +1833,10 @@ baseTimestamp: Math.max(0, Math.floor(Number(payload[4] || 0) || 0)), deltas: Array.isArray(payload[5]) ? payload[5] : [], packed: Array.isArray(payload[6]) ? payload[6] : [], + mysteryDrugIds: version >= 10 && Array.isArray(payload[7]) + ? [...new Set(payload[7].map(id => String(id || "")).filter(Boolean))].slice(0, MAD_SCIENTIST_TARGET) + : [], + version, timestampUnitMs: 60000, }; } @@ -1019,7 +1844,7 @@ function importSpellState(payload = null) { const parsed = parseSpellState(payload); if (!parsed) return { included: false, unlockedAdded: 0, progressChanged: false }; - const { unlockedIndexes, baseTimestamp, deltas, packed, timestampUnitMs } = parsed; + const { unlockedIndexes, baseTimestamp, deltas, packed, mysteryDrugIds, version, timestampUnitMs } = parsed; if (deltas.length !== unlockedIndexes.length) throw new Error("invalid achievement spell timestamps"); const importedUnlocks = []; let importedCompletionistAt = 0; @@ -1051,8 +1876,8 @@ } const progress = ensureProgress(); - const previousProgress = JSON.stringify(progress); - progress.placementCount = Math.max(progress.placementCount, Math.min(100, Math.max(0, Math.floor(Number(packed[0] || 0) || 0)))); + const previousProgress = JSON.stringify({ progress, ledger: ensureProgressLedger() }); + raiseProgressCounter("placementCount", packed[0]); const linkFlags = Math.max(0, Math.floor(Number(packed[1] || 0) || 0)); const importedLinks = []; if (linkFlags & 1) importedLinks.push("rope"); @@ -1060,18 +1885,18 @@ if (linkFlags & 4) importedLinks.push("spring"); progress.linkTypes = [...new Set([...(progress.linkTypes || []), ...importedLinks])]; progress.signalActivated = Boolean(progress.signalActivated || (linkFlags & 8)); - progress.antKills = Math.max(progress.antKills, Math.min(100, Math.max(0, Math.floor(Number(packed[2] || 0) || 0)))); - progress.birthCount = Math.max(progress.birthCount, Math.min(3333, Math.max(0, Math.floor(Number(packed[3] || 0) || 0)))); - progress.quickDeleteCount = Math.max(progress.quickDeleteCount, Math.min(30, Math.max(0, Math.floor(Number(packed[4] || 0) || 0)))); - progress.undoCount = Math.max(progress.undoCount, Math.min(20, Math.max(0, Math.floor(Number(packed[5] || 0) || 0)))); - progress.redoCount = Math.max(progress.redoCount, Math.min(20, Math.max(0, Math.floor(Number(packed[6] || 0) || 0)))); + raiseProgressCounter("antKills", packed[2]); + raiseProgressCounter("birthCount", packed[3]); + raiseProgressCounter("quickDeleteCount", packed[4]); + raiseProgressCounter("undoCount", packed[5]); + raiseProgressCounter("redoCount", packed[6]); const medicineMask = Math.max(0, Math.floor(Number(packed[7] || 0) || 0)); const importedMedicines = MEDICINE_LEDGER_TYPES.filter((_type, index) => medicineMask & (1 << index)); progress.medicineTypes = [...new Set([...(progress.medicineTypes || []), ...importedMedicines])]; - progress.firstAidHeals = Math.max(progress.firstAidHeals, Math.min(50, Math.max(0, Math.floor(Number(packed[8] || 0) || 0)))); - progress.fightMochiFightCount = Math.max(progress.fightMochiFightCount, Math.min(CHAOS_FIGHT_TARGET, Math.max(0, Math.floor(Number(packed[9] || 0) || 0)))); - progress.shotCount = Math.max(progress.shotCount, Math.min(SNIPER_SHOT_TARGET, Math.max(0, Math.floor(Number(packed[10] || 0) || 0)))); - progress.loveMochiBirthCount = Math.max(progress.loveMochiBirthCount, Math.min(FERTILITY_BIRTH_TARGET, Math.max(0, Math.floor(Number(packed[11] || 0) || 0)))); + raiseProgressCounter("firstAidHeals", packed[8]); + raiseProgressCounter("fightMochiFightCount", packed[9]); + raiseProgressCounter("shotCount", packed[10]); + raiseProgressCounter("loveMochiBirthCount", packed[11]); const importedDailyStreak = Math.min(DAILY_PLAY_TARGET, Math.max(0, Math.floor(Number(packed[12] || 0) || 0))); const importedDailyLastDay = Math.min(131071, Math.max(0, Math.floor(Number(packed[13] || 0) || 0))); if (importedDailyLastDay > progress.dailyPlayLastDay) { @@ -1080,10 +1905,16 @@ } else if (importedDailyLastDay === progress.dailyPlayLastDay) { progress.dailyPlayStreak = Math.max(progress.dailyPlayStreak, importedDailyStreak); } - progress.statsButtonPressCount = Math.max(progress.statsButtonPressCount, Math.min(STATISTICIAN_TARGET, Math.max(0, Math.floor(Number(packed[14] || 0) || 0)))); - progress.totalDeathCount = Math.max(progress.totalDeathCount, Math.min(MEMENTO_MORI_TARGET, Math.max(0, Math.floor(Number(packed[15] || 0) || 0)))); - progress.manualTarinaiAddedCount = Math.max(progress.manualTarinaiAddedCount, Math.min(LIVELY_MAKING_TARGET, Math.max(0, Math.floor(Number(packed[16] || 0) || 0)))); - const progressChanged = previousProgress !== JSON.stringify(progress); + raiseProgressCounter("statsButtonPressCount", packed[14]); + raiseProgressCounter("totalDeathCount", packed[15]); + raiseProgressCounter("manualTarinaiAddedCount", packed[16]); + if (version >= 10 && mysteryDrugIds.length) { + progress.mysteryDrugTarinaiIds = [...new Set([...(progress.mysteryDrugTarinaiIds || []), ...mysteryDrugIds])].slice(0, MAD_SCIENTIST_TARGET); + } + raiseProgressCounter("directFeedCount", packed[18]); + raiseProgressCounter("robotCleanCount", packed[19]); + const progressChanged = previousProgress !== JSON.stringify({ progress, ledger: ensureProgressLedger() }); + if (progressChanged) markProgressMutation(); changed = changed || progressChanged; if (!state.unlocked[COMPLETIONIST_ID] && allOtherAchievementsUnlocked()) { @@ -1110,18 +1941,19 @@ recordIntervention({ ...detail, world }); const item = detail.item || null; if (item) { + if (!item._achievementPlayerPlaced || item._achievementPlayerPlacedCounted === false) world.achievementPlayerPlacedActiveCount = Math.max(0, Number(world.achievementPlayerPlacedActiveCount || 0) || 0) + 1; item._achievementPlayerPlaced = true; + item._achievementPlayerPlacedCounted = true; item._achievementPlacedAt = Math.max(0, Number(world.time || 0) || 0); } let changed = evaluateCleanFreak(world, detail); changed = evaluateMegalopolis(world, detail) || changed; changed = evaluateSandbox(world, detail) || changed; if (!state.unlocked.placed_objects_100) { - const progress = ensureProgress(); - progress.placementCount = Math.min(100, progress.placementCount + 1); + const count = incrementProgressCounter("placementCount"); saveState(); renderIfDialogOpen(); - if (progress.placementCount >= 100) changed = unlock("placed_objects_100", { ...detail, world, count: progress.placementCount }) || changed; + if (count >= ADDITIVE_PROGRESS_CAPS.placementCount) changed = unlock("placed_objects_100", { ...detail, world, count }) || changed; } return changed; } @@ -1137,15 +1969,14 @@ const placedAtRaw = item._achievementPlacedAt; const placedAt = placedAtRaw == null ? NaN : Number(placedAtRaw); if (!Number.isFinite(placedAt) || now < placedAt || now - placedAt > 30.0001) return changed; - const progress = ensureProgress(); if (!state.unlocked.unplanned_city_30) { const operationKey = detail.operationId == null ? "" : String(detail.operationId); if (operationKey && world._achievementLastQuickDeleteOperation === operationKey) return changed; if (operationKey) world._achievementLastQuickDeleteOperation = operationKey; - progress.quickDeleteCount = Math.min(30, progress.quickDeleteCount + 1); + const count = incrementProgressCounter("quickDeleteCount"); saveState(); renderIfDialogOpen(); - if (progress.quickDeleteCount >= 30) changed = unlock("unplanned_city_30", { ...detail, world, count: progress.quickDeleteCount }) || changed; + if (count >= ADDITIVE_PROGRESS_CAPS.quickDeleteCount) changed = unlock("unplanned_city_30", { ...detail, world, count }) || changed; } return changed; } @@ -1155,24 +1986,39 @@ if (action !== "undo" && action !== "redo") return false; const world = detailWorld(detail); if (world) recordIntervention({ ...detail, world, tool: action }); - const progress = ensureProgress(); const key = action === "undo" ? "undoCount" : "redoCount"; const achievementId = action === "undo" ? "undo_20" : "redo_20"; - progress[key] = Math.min(20, progress[key] + 1); + const count = incrementProgressCounter(key); saveState(); renderIfDialogOpen(); let changed = false; if (action === "undo" && Math.max(0, Number(detail.deadRestored || 0) || 0) >= 10) { changed = unlock("undo_mass_revival", { ...detail, count: Math.max(0, Number(detail.deadRestored || 0) || 0) }) || changed; } - if (progress[key] >= 20) changed = unlock(achievementId, { ...detail, count: progress[key] }) || changed; + if (count >= ADDITIVE_PROGRESS_CAPS[key]) changed = unlock(achievementId, { ...detail, count }) || changed; return changed; } + function mechanizedIndustryHasAllLinks(world = global.world) { + if (!world) return false; + return ["rope", "rod", "spring"].every(required => { + const bucket = world.itemsOfType?.(required); + if (Array.isArray(bucket)) return bucket.some(item => item && !item.dead); + return (world.items || []).some(item => item && !item.dead && item.type === required); + }); + } + function evaluateMechanizedIndustry(detail = {}) { - const progress = ensureProgress(); - const hasAllLinks = ["rope", "rod", "spring"].every(required => progress.linkTypes.includes(required)); - if (progress.signalActivated && hasAllLinks) return unlock("mechanized_industry", detail); + if (state.unlocked.mechanized_industry) return false; + const world = detailWorld(detail); + const source = detail.source || null; + const detectorDriven = Boolean(detail.detectorDriven) + || source?.type === "pressure_switch" + || (Array.isArray(detail.detectorSources) && detail.detectorSources.some(candidate => candidate?.type === "pressure_switch")); + const connectedTarget = Boolean(detail.connected) && detail.target && !detail.target.dead; + if (world && detectorDriven && connectedTarget && mechanizedIndustryHasAllLinks(world)) { + return unlock("mechanized_industry", { ...detail, world }); + } return false; } @@ -1180,23 +2026,10 @@ const linkType = String(type || detail.type || detail.item?.type || ""); const placementLinkTypes = ["rope", "rod", "spring", "wire", "insulated_wire"]; if (!placementLinkTypes.includes(linkType)) return false; - recordPlayerPlacement(detail); - if (state.unlocked.mechanized_industry || !["rope", "rod", "spring"].includes(linkType)) return false; - const progress = ensureProgress(); - progress.linkTypes = [...new Set([...(progress.linkTypes || []), linkType])]; - saveState(); - renderIfDialogOpen(); - return evaluateMechanizedIndustry({ ...detail, type: linkType }); + return recordPlayerPlacement(detail); } function recordSignalActivation(detail = {}) { - if (state.unlocked.mechanized_industry) return false; - const progress = ensureProgress(); - if (!progress.signalActivated) { - progress.signalActivated = true; - saveState(); - renderIfDialogOpen(); - } return evaluateMechanizedIndustry(detail); } @@ -1209,7 +2042,7 @@ function evaluateAntNestWithoutTarinai(worldRef = global.world, detail = {}) { if (!worldRef || state.unlocked.ant_nest_without_tarinai) return false; - const hasNest = (worldRef.items || []).some(item => item && !item.dead && item.type === "ant_nest"); + const hasNest = playstyleItemCount(worldRef, "ant_nest") > 0; if (!hasNest) return false; const aliveTarinai = (worldRef.tarinai || []).some(tarinai => tarinai && !tarinai.dead); if (aliveTarinai) return false; @@ -1253,13 +2086,12 @@ function recordAntKilled(detail = {}) { let changed = false; - const progress = ensureProgress(); const playerCaused = Boolean(detail.playerCaused || detail.ant?._achievementLastDamageSource?.danger); if (!state.unlocked.ants_killed_100 && playerCaused) { - progress.antKills = Math.min(100, progress.antKills + 1); + const count = incrementProgressCounter("antKills"); saveState(); renderIfDialogOpen(); - if (progress.antKills >= 100) changed = unlock("ants_killed_100", detail) || changed; + if (count >= ADDITIVE_PROGRESS_CAPS.antKills) changed = unlock("ants_killed_100", { ...detail, count }) || changed; } const world = detailWorld(detail); const ant = detail.ant || null; @@ -1291,11 +2123,12 @@ const world = detail.world || tarinai.world || global.world || null; const now = Math.max(0, Number(world?.time || 0) || 0); const dangerSource = dangerItemSource(source); - // This achievement tracks collateral damage caused by danger-category tools, - // not ordinary combat, hunger, disease, or ant attacks. - if (world && dangerSource) { - world.achievementLastTarinaiDamageAt = now; - world.achievementEnemyAntKills = 0; + // "Unharmed" means no actual damage from any cause while the streak is active. + if (world) { + if (Math.max(0, Math.floor(Number(world.achievementEnemyAntKills || 0) || 0)) > 0) { + world.achievementEnemyAntKills = 0; + renderIfDialogOpen(); + } } tarinai._achievementLastDamageSource = dangerSource ? { danger: true, @@ -1338,32 +2171,38 @@ const now = Math.max(0, Number(world.time || 0) || 0); const source = tarinai._achievementLastDamageSource || null; const lethalDanger = Boolean(detail.fromDamage || detail.achievementDangerKill); + const session = tarinai._achievementFightSession || null; if (!lethalDanger || !source?.danger || Math.abs(now - Number(source.at || 0)) > 0.05) return false; + if (!session?.id || !session.opponentId || Number(tarinai.fightTimer || 0) <= 0.04) return false; const tracker = fightPairTracker(world); if (!tracker) return false; + const maxGap = 6; for (const [key, pending] of [...tracker.entries()]) { - if (!pending) { + if (!pending || now - Number(pending.at || 0) > maxGap) { tracker.delete(key); continue; } - if (pending.firstId !== tarinai.id && pending.otherId === tarinai.id) { + if (pending.sessionId === session.id + && pending.firstId !== tarinai.id + && pending.otherId === tarinai.id + && session.opponentId === pending.firstId) { tracker.delete(key); - return unlock("fight_pair_danger_kill", { ...detail, pairKey: key, first: pending, secondSource: source }); + return unlock("fight_pair_danger_kill", { ...detail, pairKey: key, fightSessionId: session.id, first: pending, secondSource: source }); } } - const targets = [...new Set([...(Array.isArray(tarinai.fightTargetIds) ? tarinai.fightTargetIds : []), tarinai.fightTargetId].filter(Boolean))]; - for (const targetId of targets) { - const opponent = (world.tarinai || []).find(candidate => candidate && candidate.id === targetId) || null; - if (!opponent || opponent === tarinai) continue; - const activePair = Boolean(world.isAlreadyFightingPair?.(tarinai, opponent)) - || Boolean((tarinai.fightTimer || 0) > 0.04 && (opponent.fightTimer || 0) > 0.04); - if (!activePair) continue; - const key = world.fightPairKey?.(tarinai, opponent) - || [String(tarinai.id || ""), String(opponent.id || "")].sort().join(":"); - if (!key) continue; - tracker.set(key, { firstId: tarinai.id, otherId: opponent.id, at: now, source }); - return false; - } + const opponent = (world.tarinai || []).find(candidate => candidate && candidate.id === session.opponentId) || null; + if (!opponent || opponent === tarinai || opponent.dead) return false; + const opponentSession = opponent._achievementFightSession || null; + if (opponentSession?.id !== session.id || opponentSession.opponentId !== tarinai.id) return false; + const key = String(session.pairKey || world.fightPairKey?.(tarinai, opponent) || ""); + if (!key) return false; + tracker.set(key, { + firstId: tarinai.id, + otherId: opponent.id, + at: now, + source, + sessionId: session.id, + }); return false; } @@ -1422,7 +2261,7 @@ function evaluateSandbox(world = global.world, detail = {}) { if (!world || state.unlocked.sandbox_five_toilets) return false; - const count = (world.items || []).reduce((sum, item) => sum + (item && !item.dead && item.type === "toilet" ? 1 : 0), 0); + const count = playstyleItemCount(world, "toilet"); if (count < 5) return false; return unlock("sandbox_five_toilets", { ...detail, world, count }); } @@ -1451,6 +2290,7 @@ ? Math.min(DAILY_PLAY_TARGET, progress.dailyPlayStreak + 1) : 1; progress.dailyPlayLastDay = today; + markProgressMutation(); saveState(); renderIfDialogOpen(); if (progress.dailyPlayStreak >= DAILY_PLAY_TARGET) { @@ -1467,9 +2307,7 @@ elapsedMs = Math.max(0, explicitElapsed); } else { const timestamp = Number.isFinite(Number(detail.now)) ? Number(detail.now) : Date.now(); - if (!continuousPlayStartedAt || timestamp < continuousPlayStartedAt) continuousPlayStartedAt = timestamp; - continuousPlayLastHeartbeatAt = timestamp; - elapsedMs = Math.max(0, timestamp - continuousPlayStartedAt); + elapsedMs = continuousPlayElapsedMs(timestamp); } let changed = false; if (!state.unlocked.continuous_play_1_hour && elapsedMs >= CONTINUOUS_PLAY_TARGET_MS) { @@ -1483,23 +2321,43 @@ function recordBelowAbsoluteZeroItem(worldRef = global.world, detail = {}) { if (state.unlocked.below_absolute_zero_item || !worldRef) return false; - for (const item of worldRef.items || []) { - if (!item || item.dead) continue; + worldRef.ensureItemBuckets?.("achievement-absolute-zero"); + const testItem = (item) => { + if (!item || item.dead) return false; const temperature = Number(worldRef.temperatureAt?.(item.x, item.y, null)); - if (!Number.isFinite(temperature) || temperature >= ABSOLUTE_ZERO_C) continue; + if (!Number.isFinite(temperature) || temperature >= ABSOLUTE_ZERO_C) return false; return unlock("below_absolute_zero_item", { ...detail, world: worldRef, item, temperature }); + }; + // Evaluate the actual temperature field for every live item. This avoids + // coupling the achievement to a hard-coded list of present-day heat sources. + for (const item of worldRef.items || []) { + if (testItem(item)) return true; + } + for (const residue of worldRef.residues || []) { + if (testItem(residue)) return true; } return false; } + function importWorldAchievementProgress(detail = {}) { + const imported = Math.min(ROBOT_CLEAN_TARGET, Math.max(0, Math.floor(Number(detail.robotCleanCount || 0) || 0))); + const current = progressCounter("robotCleanCount"); + if (imported <= current) return false; + raiseProgressCounter("robotCleanCount", imported); + saveState(); + renderIfDialogOpen(); + return true; + } + function recordRobotClean(detail = {}) { if (state.unlocked.robot_cleaner_100) return false; const world = detailWorld(detail); const type = String(detail.type || detail.target?.type || ""); if (!world || !["zunchi", "ant_corpse", "trace", "splat"].includes(type)) return false; - world.achievementRobotCleanCount = Math.min(ROBOT_CLEAN_TARGET, Math.max(0, Math.floor(Number(world.achievementRobotCleanCount || 0) || 0)) + 1); + const count = incrementProgressCounter("robotCleanCount"); + if (count >= ROBOT_CLEAN_TARGET) return unlock("robot_cleaner_100", { ...detail, world, count }); + saveState(); renderIfDialogOpen(); - if (world.achievementRobotCleanCount >= ROBOT_CLEAN_TARGET) return unlock("robot_cleaner_100", { ...detail, world, count: world.achievementRobotCleanCount }); return false; } @@ -1510,10 +2368,13 @@ function evaluateCleanFreak(world = global.world, detail = {}) { if (!world || state.unlocked.clean_freak_robot_only) return false; - const liveItems = (world.items || []).filter(item => item && !item.dead); - if (!liveItems.length || liveItems.some(item => item.type !== "robot_cleaner")) return false; + const activeObjects = Math.max(0, Number(world.activeObjectCount?.() ?? (world.items || []).reduce((count, item) => count + (item && !item.dead ? 1 : 0), 0)) || 0); + const robotCount = Math.max(0, Number(world.itemCounts?.robot_cleaner || 0) || 0); + if (!activeObjects || robotCount !== activeObjects) return false; + const liveItems = world.itemsOfType?.("robot_cleaner") || []; if ((world.tarinai || []).some(tarinai => tarinai && !tarinai.dead)) return false; if ((world.ants || []).some(ant => ant && !ant.dead)) return false; + if ((world.residues || []).some(residue => residue && !residue.dead && Math.max(0, Number(residue.amount ?? 1) || 0) > 0)) return false; const qualifies = liveItems.some(robot => { const mask = Number(global.TarinaiItemDynamicToolSystem?.robotCleanerMask?.(robot) ?? robot.robotCleanerMask ?? 0) | 0; return (mask & ROBOT_ALL_TARGET_MASK) === ROBOT_ALL_TARGET_MASK @@ -1546,11 +2407,10 @@ if (state.unlocked.town_doctor_50) return false; const recovered = Number(detail.recovered ?? detail.amount ?? 0); if (!Number.isFinite(recovered) || recovered <= 0.0001) return false; - const progress = ensureProgress(); - progress.firstAidHeals = Math.min(50, progress.firstAidHeals + 1); + const count = incrementProgressCounter("firstAidHeals"); saveState(); renderIfDialogOpen(); - if (progress.firstAidHeals >= 50) return unlock("town_doctor_50", { ...detail, count: progress.firstAidHeals, recovered }); + if (count >= ADDITIVE_PROGRESS_CAPS.firstAidHeals) return unlock("town_doctor_50", { ...detail, count, recovered }); return false; } @@ -1564,16 +2424,28 @@ const world = detailWorld(detail); let changed = false; if (type === "fight_mochi" && tarinai && world) { - const serial = Math.max(1, Math.floor(Number(world.achievementFightMochiSerial || 0) || 0) + 1); - world.achievementFightMochiSerial = serial; tarinai._achievementFightMochiAt = Math.max(0, Number(world.time || 0) || 0); - tarinai._achievementFightMochiSerial = serial; tarinai._achievementFightMochiWorld = world; } + if (type === "mystery_drug" && tarinai && !state.unlocked.mad_scientist) { + const progress = ensureProgress(); + const identity = String(tarinai.familyKey || tarinai.id || ""); + if (identity && !progress.mysteryDrugTarinaiIds.includes(identity)) { + progress.mysteryDrugTarinaiIds = [...progress.mysteryDrugTarinaiIds, identity].slice(0, MAD_SCIENTIST_TARGET); + markProgressMutation(); + if (progress.mysteryDrugTarinaiIds.length >= MAD_SCIENTIST_TARGET) { + changed = unlock("mad_scientist", { ...detail, world, tarinai, count: progress.mysteryDrugTarinaiIds.length }) || changed; + } else { + saveState(); + renderIfDialogOpen(); + } + } + } if (MEDICINE_LEDGER_TYPES.includes(type) && !state.unlocked.medicine_ledger_all) { const progress = ensureProgress(); if (!progress.medicineTypes.includes(type)) { progress.medicineTypes = [...progress.medicineTypes, type]; + markProgressMutation(); saveState(); renderIfDialogOpen(); } @@ -1596,7 +2468,6 @@ if (foodGift) { tarinai._achievementDirectFeedCount = Math.max(0, Math.floor(Number(tarinai._achievementDirectFeedCount || 0) || 0)) + 1; world.achievementSelfSufficientStartAt = -1; - world.achievementLastDirectFeedAt = Math.max(0, Number(world.time || 0) || 0); } if (treatment) tarinai._achievementDirectTreatmentCount = Math.max(0, Math.floor(Number(tarinai._achievementDirectTreatmentCount || 0) || 0)) + 1; recordConsumableUse({ ...detail, world, tarinai, type }); @@ -1614,24 +2485,32 @@ (Number(tarinai.fightMochiTimer || 0) > 0.04) || Boolean(tarinai.hasFightMochiEffect?.()) )); if (!state.unlocked.chaos_seeker_666_fights && fightMochiInfluenced) { - const progress = ensureProgress(); - progress.fightMochiFightCount = Math.min(CHAOS_FIGHT_TARGET, progress.fightMochiFightCount + 1); - if (progress.fightMochiFightCount >= CHAOS_FIGHT_TARGET) { - changed = unlock("chaos_seeker_666_fights", { ...detail, world, count: progress.fightMochiFightCount, fightMochiInfluenced: true }) || changed; + const count = incrementProgressCounter("fightMochiFightCount"); + if (count >= CHAOS_FIGHT_TARGET) { + changed = unlock("chaos_seeker_666_fights", { ...detail, world, count, fightMochiInfluenced: true }) || changed; } else { saveState(); renderIfDialogOpen(); } } const now = Math.max(0, Number(world.time || 0) || 0); + const pairA = detail.a || null; + const pairB = detail.b || null; + if (pairA && pairB && pairA !== pairB) { + world.achievementFightSessionSerial = Math.max(0, Math.floor(Number(world.achievementFightSessionSerial || 0) || 0)) + 1; + const pairKey = world.fightPairKey?.(pairA, pairB) + || [String(pairA.id || ""), String(pairB.id || "")].sort().join(":"); + const sessionId = `${pairKey}@${world.achievementFightSessionSerial}`; + pairA._achievementFightSession = { id: sessionId, pairKey, opponentId: pairB.id, startedAt: now }; + pairB._achievementFightSession = { id: sessionId, pairKey, opponentId: pairA.id, startedAt: now }; + } const candidates = [detail.a, detail.b].filter(Boolean); for (const tarinai of candidates) { const givenAtRaw = tarinai._achievementFightMochiAt; const givenAt = givenAtRaw == null ? NaN : Number(givenAtRaw); - const serial = Math.floor(Number(tarinai._achievementFightMochiSerial || 0) || 0); - const validCurrentSessionMochi = serial > 0 && tarinai._achievementFightMochiWorld === world; + const validCurrentSessionMochi = tarinai._achievementFightMochiWorld === world; if (validCurrentSessionMochi && Number.isFinite(givenAt) && now >= givenAt && now - givenAt <= 30.0001) { - changed = unlock("fuel_to_fire", { ...detail, world, tarinai, elapsed: now - givenAt, serial }) || changed; + changed = unlock("fuel_to_fire", { ...detail, world, tarinai, elapsed: now - givenAt }) || changed; break; } } @@ -1640,9 +2519,8 @@ function recordShotFired(detail = {}) { if (state.unlocked.sniper_333_shots) return false; - const progress = ensureProgress(); - progress.shotCount = Math.min(SNIPER_SHOT_TARGET, progress.shotCount + 1); - if (progress.shotCount >= SNIPER_SHOT_TARGET) return unlock("sniper_333_shots", { ...detail, count: progress.shotCount }); + const count = incrementProgressCounter("shotCount"); + if (count >= SNIPER_SHOT_TARGET) return unlock("sniper_333_shots", { ...detail, count }); saveState(); renderIfDialogOpen(); return false; @@ -1650,10 +2528,9 @@ function recordLoveMochiBirth(detail = {}) { if (state.unlocked.fertility_seeker_721_love_births || !detail.loveMochiInfluenced) return false; - const progress = ensureProgress(); - progress.loveMochiBirthCount = Math.min(FERTILITY_BIRTH_TARGET, progress.loveMochiBirthCount + 1); - if (progress.loveMochiBirthCount >= FERTILITY_BIRTH_TARGET) { - return unlock("fertility_seeker_721_love_births", { ...detail, count: progress.loveMochiBirthCount }); + const count = incrementProgressCounter("loveMochiBirthCount"); + if (count >= FERTILITY_BIRTH_TARGET) { + return unlock("fertility_seeker_721_love_births", { ...detail, count }); } saveState(); renderIfDialogOpen(); @@ -1676,34 +2553,28 @@ if (!world) return false; runtimeByWorld.delete(world); dangerFightDeathsByWorld.delete(world); - world.achievementDirectFeedCount = 0; - world.achievementRobotCleanCount = 0; world.achievementEnemyAntKills = 0; - world.achievementLastTarinaiDamageAt = -Infinity; world.achievementSelfSufficientStartAt = -1; - world.achievementLastDirectFeedAt = -Infinity; world.achievementNoDeathStartAt = -1; world.achievementHappyStartAt = -1; - world.achievementFightMochiSerial = 0; world.achievementEliteFewStartAt = -1; for (const tarinai of world.tarinai || []) { if (!tarinai) continue; tarinai._achievementFightMochiAt = null; - tarinai._achievementFightMochiSerial = 0; tarinai._achievementFightMochiWorld = null; tarinai._achievementDirectFeedCount = 0; tarinai._achievementDirectTreatmentCount = 0; tarinai._achievementSaunaHotAt = null; tarinai._achievementSaunaWasHot = false; tarinai._achievementHeldStartedAt = null; + tarinai._achievementFightSession = null; } for (const item of world.items || []) { if (!item) continue; if (item.type === "sticky_bomb") item.stickyBombPassCount = 0; item._achievementPlacedAt = null; } - world.achievementNaturalSlaveGenerations = []; - world.achievementNaturalKingGenerations = []; + // Mystery-drug targets are a lifetime achievement and intentionally survive world resets. return true; } @@ -1740,12 +2611,11 @@ if (child?.isZunchiSlave) recordNaturalStatus("slave", { ...detail, world, tarinai: child, bornWithStatus: true }); if (child?.isTarinaiChampion) recordNaturalStatus("king", { ...detail, world, tarinai: child, bornWithStatus: true }); evaluateMegalopolis(world, detail); - const progress = ensureProgress(); if (!state.unlocked.great_mother_1000_births) { - progress.birthCount = Math.min(3333, progress.birthCount + 1); + const count = incrementProgressCounter("birthCount"); saveState(); renderIfDialogOpen(); - if (progress.birthCount >= 3333) unlock("great_mother_1000_births", { ...detail, count: progress.birthCount }); + if (count >= ADDITIVE_PROGRESS_CAPS.birthCount) unlock("great_mother_1000_births", { ...detail, count }); } if (state.unlocked.birth_50_in_60_seconds) return; const now = Number(world?.time || 0) || 0; @@ -1759,9 +2629,8 @@ function recordDeath(detail = {}) { recordFightPairDangerDeath(detail); if (!state.unlocked.memento_mori) { - const progress = ensureProgress(); - progress.totalDeathCount = Math.min(MEMENTO_MORI_TARGET, progress.totalDeathCount + 1); - if (progress.totalDeathCount >= MEMENTO_MORI_TARGET) unlock("memento_mori", { ...detail, count: progress.totalDeathCount }); + const count = incrementProgressCounter("totalDeathCount"); + if (count >= MEMENTO_MORI_TARGET) unlock("memento_mori", { ...detail, count }); else { scheduleProgressSave(); renderIfDialogOpen(); } } const reason = String(detail.reason || detail.tarinai?.deathReason || ""); @@ -1802,7 +2671,8 @@ const world = detail.world || tarinai?.world || null; if (kind === "slave") { unlock("natural_zunchi_slave", detail); - if (recordNaturalGeneration(world, tarinai, "achievementNaturalSlaveGenerations", 5)) { + if (tarinai?.isAcquiredTarinai) unlock("ochibi_natural_slave", detail); + if (recordNaturalGeneration(world, tarinai, "_achievementNaturalSlaveLineageDepth", 5)) { unlock("natural_zunchi_slave_5_generations", detail); } evaluateStatusEffectAchievements(tarinai, detail); @@ -1810,7 +2680,7 @@ } if (kind === "king") { unlock("natural_tarinai_king", detail); - if (recordNaturalGeneration(world, tarinai, "achievementNaturalKingGenerations", 3)) { + if (recordNaturalGeneration(world, tarinai, "_achievementNaturalKingLineageDepth", 3)) { unlock("natural_tarinai_king_3_generations", detail); } evaluateStatusEffectAchievements(tarinai, detail); @@ -1822,9 +2692,10 @@ if (!world) return false; recordDirectCare({ ...detail, world, foodGift: true }); if (state.unlocked.direct_feed_33) return false; - world.achievementDirectFeedCount = Math.min(33, Math.max(0, Math.floor(Number(world.achievementDirectFeedCount || 0) || 0)) + 1); + const count = incrementProgressCounter("directFeedCount"); + saveState(); renderIfDialogOpen(); - if (world.achievementDirectFeedCount >= 33) return unlock("direct_feed_33", { ...detail, world, count: world.achievementDirectFeedCount }); + if (count >= ADDITIVE_PROGRESS_CAPS.directFeedCount) return unlock("direct_feed_33", { ...detail, world, count }); return false; } @@ -1841,10 +2712,9 @@ function recordStatsButtonPress(detail = {}) { if (state.unlocked.statistician) return false; - const progress = ensureProgress(); - progress.statsButtonPressCount = Math.min(STATISTICIAN_TARGET, progress.statsButtonPressCount + 1); - if (progress.statsButtonPressCount >= STATISTICIAN_TARGET) { - return unlock("statistician", { ...detail, count: progress.statsButtonPressCount }); + const count = incrementProgressCounter("statsButtonPressCount"); + if (count >= STATISTICIAN_TARGET) { + return unlock("statistician", { ...detail, count }); } saveState(); renderIfDialogOpen(); @@ -1857,11 +2727,13 @@ } function recordManualTarinaiAdded(detail = {}) { + // Adding a Tarinai is a direct player intervention and must invalidate + // the no-operation window used by the surveillance-camera achievement. + recordIntervention({ ...detail, tool: detail.tool || "new-tarinai" }); if (state.unlocked.lively_making) return false; - const progress = ensureProgress(); - progress.manualTarinaiAddedCount = Math.min(LIVELY_MAKING_TARGET, progress.manualTarinaiAddedCount + 1); - if (progress.manualTarinaiAddedCount >= LIVELY_MAKING_TARGET) { - return unlock("lively_making", { ...detail, count: progress.manualTarinaiAddedCount }); + const count = incrementProgressCounter("manualTarinaiAddedCount"); + if (count >= LIVELY_MAKING_TARGET) { + return unlock("lively_making", { ...detail, count }); } saveState(); renderIfDialogOpen(); @@ -1976,7 +2848,7 @@ const moodId = String(mood?.id || worldRef.colonyMood?.id || ""); const day = Math.max(1, Math.floor(Number(worldRef.day || 1) || 1)); if (alive.length > 0 && moodId === "happy" && day >= 6 && !state.unlocked.minimalist_happy) { - const placedAlive = (worldRef.items || []).reduce((count, item) => count + (item && !item.dead && item._achievementPlayerPlaced ? 1 : 0), 0); + const placedAlive = Math.max(0, Number(worldRef.achievementPlayerPlacedActiveCount || 0) || 0); if (placedAlive <= 10) unlock("minimalist_happy", { world: worldRef, mood: mood || worldRef.colonyMood, placedAlive }); } if (!state.unlocked.colony_happy) { @@ -1994,7 +2866,7 @@ } if (!state.unlocked.self_sufficient) { - if (alive.length >= 20 && !(worldRef.items || []).some(item => item && !item.dead && item.type === "duplicator")) { + if (alive.length >= 20 && playstyleItemCount(worldRef, "duplicator") === 0) { let selfStart = Number(worldRef.achievementSelfSufficientStartAt); if (!Number.isFinite(selfStart) || selfStart < 0 || selfStart > now) { selfStart = now; @@ -2074,6 +2946,7 @@ } async function resetAchievements() { + await persistenceReadyPromise; const confirmed = await global.TarinaiGameDialogs?.confirm?.({ title: "\u5b9f\u7e3e\u306e\u30ea\u30bb\u30c3\u30c8", message: "\u3059\u3079\u3066\u306e\u5b9f\u7e3e\u89e3\u9664\u72b6\u614b\u3068\u3001\u5171\u6709\u96c6\u8a08\u4e0a\u306e\u81ea\u5206\u306e\u89e3\u9664\u8a18\u9332\u3092\u524a\u9664\u3057\u307e\u3059\u3002", @@ -2082,8 +2955,14 @@ danger: true, }); if (!confirmed) return false; + const identity = currentServerIdentity(); + persistenceGeneration += 1; + persistenceRevision = 0; state = blankState(); + if (identity) state.serverIdentity = { ...identity }; state.resetPending = true; + progressMutationRevision = 0; + progressSyncedRevision = 0; runtimeByWorld = new WeakMap(); dangerFightDeathsByWorld = new WeakMap(); wireShockTrackers = new WeakMap(); @@ -2091,8 +2970,9 @@ toastActive = false; emptyClickTimes = []; groundChangeTimes = []; - continuousPlayStartedAt = Date.now(); - continuousPlayLastHeartbeatAt = continuousPlayStartedAt; + continuousPlayAccumulatedMs = 0; + continuousPlayLastHeartbeatAt = Date.now(); + continuousPlayActive = !document.hidden; if (global.world) { resetWorldProgress(global.world); global.world.achievementLastInterventionAt = Math.max(0, Number(global.world.time || 0) || 0); @@ -2128,19 +3008,36 @@ } function openDialog() { - dom.dialog?.classList.remove("hidden"); + if (global.TarinaiManagedDialogs?.open) global.TarinaiManagedDialogs.open(dom.dialog, dom.button); + else { + dom.dialog?.classList.remove("hidden"); + dom.dialog?.setAttribute("aria-hidden", "false"); + } render({ forceList: true }); - dom.closeIconButton?.focus?.(); + if (!global.TarinaiManagedDialogs?.open) dom.closeIconButton?.focus?.(); void syncPending({ full: true }); } function closeDialog() { - dom.dialog?.classList.add("hidden"); - dom.button?.focus?.(); + if (global.TarinaiManagedDialogs?.close) global.TarinaiManagedDialogs.close(dom.dialog); + else { + dom.dialog?.classList.add("hidden"); + dom.dialog?.setAttribute("aria-hidden", "true"); + dom.button?.focus?.(); + } } document.addEventListener("visibilitychange", () => { - if (!document.hidden) continuousPlayLastHeartbeatAt = Date.now(); + const now = Date.now(); + if (document.hidden) { + if (continuousPlayActive && now >= continuousPlayLastHeartbeatAt) { + continuousPlayAccumulatedMs += now - continuousPlayLastHeartbeatAt; + } + continuousPlayActive = false; + } else { + continuousPlayLastHeartbeatAt = now; + continuousPlayActive = true; + } }); if (typeof global.setInterval === "function") { global.setInterval(() => { @@ -2153,7 +3050,7 @@ } dom.button?.addEventListener("click", () => { - global.audio?.uiClick?.(); + global.TarinaiAudio?.uiClick?.(); openDialog(); }); dom.closeButton?.addEventListener("click", closeDialog); @@ -2165,19 +3062,15 @@ dom.dialog?.addEventListener("click", event => { if (event.target === dom.dialog) closeDialog(); }); - document.addEventListener("keydown", event => { - if (event.key === "Escape" && !dom.dialog?.classList.contains("hidden")) closeDialog(); + dom.dialog?.addEventListener("tarinai:dialog-close-request", closeDialog); + global.addEventListener?.("pagehide", () => { + saveState(); + }); + document.addEventListener("visibilitychange", () => { + if (document.hidden) saveState(); }); - global.addEventListener?.("pagehide", saveState); const api = Object.freeze({ - definitions: DEFINITIONS, - categories: ACHIEVEMENT_CATEGORIES, - unlock, - open: openDialog, - close: closeDialog, - refresh() { return syncPending({ full: true }); }, - reset: resetAchievements, isUnlocked(id) { return Boolean(state.unlocked[String(id || "")]); }, recordBirth, recordDeath, @@ -2188,19 +3081,17 @@ recordConsumableUse, recordFirstAidRecovery, recordPlushiePokeFling, - evaluateStatusEffectAchievements, recordIgnition, recordIntervention, recordPlayerPlacement, recordPlayerDeletion, recordHistoryAction, recordRobotClean, + importWorldAchievementProgress, evaluateCleanFreak, recordFightStarted, recordShotFired, recordLoveMochiBirth, - evaluateMegalopolis, - recordHeldTarinai, recordFavoriteTarinai, recordStatsButtonPress, recordPushNotificationsEnabled, @@ -2209,7 +3100,6 @@ recordLinkPlaced, recordSignalActivation, recordAntPopulation, - evaluateAntNestWithoutTarinai, recordAntKilled, recordStickyBombPass, recordCircuitBoardSignalTransfer, @@ -2218,25 +3108,50 @@ recordSaveSlotsFilled, recordEmptyClick, recordGroundChange, - evaluateSandbox, - recordLowFps, - recordContinuousPlay, - recordDailyPlay, - recordBelowAbsoluteZeroItem, recordDamageSource, recordAntDamageSource, - debugUnlockAll: unlockAllAchievementsForDebug, exportSpellState, importSpellState, evaluateWorld, evaluateEvent, recordSelfZunchiDeath(detail = {}) { return unlock("self_zunchi_death", detail); }, + recordZunchiCollisionDeath(detail = {}) { return unlock("zunchi_collision_death", detail); }, recordSoccerBallDeath(detail = {}) { return unlock("soccer_ball_death", detail); }, }); global.TarinaiAchievements = api; - recordDailyPlay({ source: "load" }); - if (!state.unlocked[COMPLETIONIST_ID] && allOtherAchievementsUnlocked()) unlock(COMPLETIONIST_ID, { source: "load" }); - render(); - global.setTimeout(() => recordSaveSlotsFilled(), 0); - global.setTimeout(() => void syncPending({ full: true }), 700); + if (global.__TARINAI_TEST__) { + global.TarinaiAchievementTestHooks = Object.freeze({ + state() { return normalizeState(state); }, + growOnlyStateDelta, + mergeStateData, + blankState, + normalizeState, + progressCounter, + localProgressSnapshot, + recordFightPairDangerDeath, + recordNaturalGeneration, + definitions: DEFINITIONS, + categories: ACHIEVEMENT_CATEGORIES, + definition(id) { return definitionById.get(String(id || "")) || null; }, + refresh() { return syncPending({ full: true }); }, + reset: resetAchievements, + open: openDialog, + render(options = {}) { return render(options); }, + }); + } + setupPersistenceCrossTabSync(); + if (dom.buttonCount) dom.buttonCount.textContent = "…"; + if (dom.dialogCount) dom.dialogCount.textContent = `… / ${DEFINITIONS.length}`; + persistenceReadyPromise = hydrateDurableState().catch(() => { + persistenceHydrated = true; + persistStateNow(); + return true; + }).then(() => { + recordDailyPlay({ source: "load" }); + if (!state.unlocked[COMPLETIONIST_ID] && allOtherAchievementsUnlocked()) unlock(COMPLETIONIST_ID, { source: "load" }); + render(); + global.setTimeout(() => recordSaveSlotsFilled(), 0); + global.setTimeout(() => void syncPending({ full: true }), 700); + return true; + }); })(window); diff --git a/js/ants.js b/js/ants.js index f615baf..9fcd59d 100644 --- a/js/ants.js +++ b/js/ants.js @@ -100,7 +100,7 @@ class AntActor { this.targetRef = null; this.burnWanderAngle = rand(0, Math.PI * 2); this.hpBarTimer = Math.max(this.hpBarTimer || 0, 1.0); - this.world?.effects?.push(new Effect("ring", this.x, this.y, { size: Math.max(10, this.r * 2.8), life: 0.18, color: "rgba(255,110,36,0.56)" })); + this.world?.queueEffect?.("ring", this.x, this.y, { size: Math.max(10, this.r * 2.8), life: 0.18, color: "rgba(255,110,36,0.56)" }); return true; } @@ -108,7 +108,7 @@ class AntActor { if (!this.burning && !(this.burnTimer > 0)) return false; this.burning = false; this.burnTimer = 0; - this.world?.effects?.push(new Effect("ring", this.x, this.y, { size: Math.max(9, this.r * 2.2), life: 0.16, color: "rgba(108,192,236,0.58)" })); + this.world?.queueEffect?.("ring", this.x, this.y, { size: Math.max(9, this.r * 2.2), life: 0.16, color: "rgba(108,192,236,0.58)" }); return true; } @@ -158,7 +158,7 @@ class AntActor { if (distXY(this.x, this.y, it.x, it.y) <= contactRadius + Math.max(it.r || 16, 12)) globalThis.TarinaiItemDynamicToolSystem?.igniteGrassByFire?.(it, this, this.world, dt); } if (deterministicChance(this.world, "ant-fire-effect", dt * 2.0, this)) { - this.world?.effects?.push(new Effect("flame", this.x, this.y - this.r, { vx: rand(-2, 2), vy: rand(-14, -6), size: Math.max(4, this.r * 1.0), life: 0.22, color: "rgba(236,46,24,0.72)" })); + this.world?.queueEffect?.("flame", this.x, this.y - this.r, { vx: rand(-2, 2), vy: rand(-14, -6), size: Math.max(4, this.r * 1.0), life: 0.22, color: "rgba(236,46,24,0.72)" }); } if (this.burnTimer <= 0.01) this.extinguishFire("timeout"); return true; @@ -300,6 +300,7 @@ class AntActor { updateSearch(dt, home) { const target = this.chooseTarget(52); if (target) { + const alreadyCaptured = Boolean((target.antDraggedTimer || 0) > 0 && target.antDraggedBy); this.state = "drag"; this.targetId = target.id; this.targetToken = target.liveToken || 0; @@ -310,6 +311,7 @@ class AntActor { target.fearTimer = Math.max(target.fearTimer || 0, 0.55); target.thought = "\u30a2\u30ea\u306b\u904b\u3070\u308c\u3066\u3044\u308b"; target.recordChangeCause?.("\u30a2\u30ea\u306b\u904b\u3070\u308c\u305f", "\u72b6\u614b"); + if (!alreadyCaptured) this.world?.log?.(`${target.name}\u304c\u30a2\u30ea\u306b\u6355\u307e\u3063\u305f\u3002`, "event", { participants: [target] }); audio.antDrag?.(); this.world.drawListDirty = true; return; @@ -416,10 +418,6 @@ class AntActor { globalThis.TarinaiAchievements?.recordAntDamageSource?.(this, target, { world: this.world, reason: "tarinai_struggle" }); this.hp -= dt * struggle; - if ((this.world.time || 0) - (this.carryLogAt || -999) > 8 && Math.random() < dt * 0.04) { - this.carryLogAt = this.world.time || 0; - this.world.log(`${target.name}\u304c\u30a2\u30ea\u306b\u5f15\u3063\u5f35\u3089\u308c\u3066\u3044\u308b\u3002`, "event", { participants: [target] }); - } if (this.hp <= 0) this.dieAsCorpse(home); } @@ -431,7 +429,7 @@ class AntActor { const corpse = new Item("ant_corpse", this.x, this.y); corpse.amount = 24; this.world.addItem?.(corpse, "ant-corpse"); - this.world.effects?.push(new Effect("zunchi_miasma", this.x, this.y - 4, { size: 10, life: 0.44, color: "rgba(82,61,42,0.28)" })); + this.world.queueEffect?.("zunchi_miasma", this.x, this.y - 4, { size: 10, life: 0.44, color: "rgba(82,61,42,0.28)" }); if (home) syncAntNestCount(this.world, home); this.world.ensureItemBuckets?.("ant-corpse"); this.world.drawListDirty = true; diff --git a/js/assets.js b/js/assets.js index ebf8742..a7799bb 100644 --- a/js/assets.js +++ b/js/assets.js @@ -16,6 +16,8 @@ const DECOR_ASSETS = [ { id: "oshibyo", path: "assets/objects/oshibyo.webp" }, { id: "oshibyo_stuck", path: "assets/objects/oshibyo_stuck.webp" }, { id: "plushie_bear", path: "assets/objects/plushie_bear.png" }, + { id: "acquired_tarinai_overlay", path: "assets/sprites/tarinai_acquired_overlay.png" }, + { id: "mamekusaredake", path: "assets/objects/mamekusaredake.png" }, ]; const ALPHA_BOUNDS = { @@ -45,6 +47,7 @@ const ALPHA_BOUNDS = { stress_dizzy: { x: 16, y: 21, w: 480, h: 433, imageW: 512, imageH: 468 }, stress_sweat: { x: 16, y: 26, w: 480, h: 428, imageW: 512, imageH: 468 }, intimidate: { x: 98, y: 16, w: 316, h: 438, imageW: 512, imageH: 468 }, + intimidate_alt: { x: 45, y: 48, w: 422, h: 379, imageW: 512, imageH: 468 }, zunchi_slave: { x: 17, y: 22, w: 478, h: 431, imageW: 512, imageH: 468 }, hungry_70: { x: 0, y: 0, w: 430, h: 366, imageW: 430, imageH: 366 }, zunchi_slave_alt: { x: 42, y: 22, w: 425, h: 426, imageW: 512, imageH: 468 }, @@ -77,8 +80,8 @@ let imageLoadTimeoutsTotal = 0; const SUNBATH_IMAGE_IDS = new Set(SPRITES .map(asset => asset?.id || "") .filter(id => String(id).startsWith("sunbath"))); -const INITIAL_IMAGE_IDS = new Set(["smile", "hungry_70", "hot_1", "hot_2", "hot_3", "cold_1", "cold_2", "cold_3", "zunchi_slave", "zunchi_slave_alt", "zunchi", "zunchi_02", "genkotsu", "pushpin", "pushpin_stuck", "oshibyo", "oshibyo_stuck", ...SUNBATH_IMAGE_IDS]); -const EARLY_IMAGE_IDS = new Set(["smile", "angry", "teary", "jito", "drool", "cry", "sleep", "pokan", "normal_smirk", "normal_tongue", "normal_happy", "hot_1", "hot_2", "hot_3", "cold_1", "cold_2", "cold_3", "weak", "hurt", "hurt2", "fear", "flee", "flee_fear2", "fear_blue", "fear_cry", "sleep2", "stress_dizzy", "stress_sweat", "intimidate", "birth_ritual", "zunchi_slave", "zunchi_slave_alt", "hungry_70", "zunchi", "zunchi_02", "genkotsu", "pushpin", "pushpin_stuck", "oshibyo", "oshibyo_stuck", ...SUNBATH_IMAGE_IDS]); +const INITIAL_IMAGE_IDS = new Set(["smile", "sleep", "hungry_70", "hot_1", "hot_2", "hot_3", "cold_1", "cold_2", "cold_3", "zunchi_slave", "zunchi_slave_alt", "zunchi", "zunchi_02", "genkotsu", "pushpin", "pushpin_stuck", "oshibyo", "oshibyo_stuck", ...SUNBATH_IMAGE_IDS]); +const EARLY_IMAGE_IDS = new Set(["smile", "angry", "teary", "jito", "drool", "cry", "sleep", "pokan", "normal_smirk", "normal_tongue", "normal_happy", "hot_1", "hot_2", "hot_3", "cold_1", "cold_2", "cold_3", "weak", "hurt", "hurt2", "fear", "flee", "flee_fear2", "fear_blue", "fear_cry", "sleep2", "stress_dizzy", "stress_sweat", "intimidate", "intimidate_alt", "birth_ritual", "zunchi_slave", "zunchi_slave_alt", "hungry_70", "zunchi", "zunchi_02", "genkotsu", "pushpin", "pushpin_stuck", "oshibyo", "oshibyo_stuck", ...SUNBATH_IMAGE_IDS]); function trimCanvasCache(cache, limit = 128) { while (cache.size > limit) { diff --git a/js/audio.js b/js/audio.js index 1620371..32e55c4 100644 --- a/js/audio.js +++ b/js/audio.js @@ -297,6 +297,7 @@ const audio = { explode() { if (!this.playSample("sfx_firecracker_explode", 0.30, "ops")) this.play("sfx_firecracker_explode", { category: "ops", minGap: 0.30 }); }, phase() { this.play("sfx_phase", { category: "notify", minGap: 1.0 }); }, notify() { this.play("sfx_notify", { category: "notify", minGap: 0.12 }); }, + achievementUnlock() { this.ensure(); this.play("sfx_achievement_unlock", { category: "notify", minGap: 0.35 }); }, uiClick() { this.play("sfx_ui_click", { category: "ops", minGap: 0.035 }); }, uiFold() { this.play("sfx_ui_fold", { category: "ops", minGap: 0.08 }); }, place(type = "") { @@ -313,6 +314,7 @@ const audio = { waterHose() { this.play("sfx_water_hose", { category: "ops", minGap: 0.20 }); }, shoot() { this.play("sfx_shoot", { category: "ops", minGap: 0.045 }); }, boltAction() { this.play("sfx_bolt_action", { category: "ops", minGap: 0.10 }); }, + bell() { if (!this.playSample("sfx_bell", 0.16, "ops")) this.play("sfx_bell", { category: "ops", minGap: 0.16 }); }, ballHit() { this.play("sfx_ball_hit", { category: "ops", minGap: 0.08 }); }, stoneImpact() { this.play("sfx_stone_impact", { category: "ops", minGap: 0.18 }); }, genkotsuImpact() { this.play("sfx_genkotsu_impact", { category: "ops", minGap: 0.20 }); setTimeout(() => this.play("sfx_ground_rumble", { category: "ops", minGap: 0.20 }), 80); }, diff --git a/js/circuit_board_system.js b/js/circuit_board_system.js index 38cdc4e..2131fb2 100644 --- a/js/circuit_board_system.js +++ b/js/circuit_board_system.js @@ -395,13 +395,23 @@ result.boardId = board.id || ""; result.direction = port.direction; result.signalActive = port.direction === "output" ? Boolean(board._circuitOutputState?.[port.id]) : Boolean(board._circuitInputState?.[port.id]); + result._signalDetectorSources = port.direction === "output" + ? [...(board._circuitOutputDetectorSources?.[port.id] || [])] + : [...(board._circuitInputDetectorSources?.[port.id] || [])]; return result; } - function evaluate(board, inputValues = null) { + function evaluate(board, inputValues = null, inputProvenance = null) { const config = ensureConfig(board); const inputs = Object.create(null); - for (const port of config.inputs) inputs[port.id] = Boolean(inputValues ? inputValues[port.id] : board?._circuitInputState?.[port.id]); + const inputDetectorSources = Object.create(null); + for (const port of config.inputs) { + inputs[port.id] = Boolean(inputValues ? inputValues[port.id] : board?._circuitInputState?.[port.id]); + const rawSources = inputProvenance ? inputProvenance[port.id] : board?._circuitInputDetectorSources?.[port.id]; + inputDetectorSources[port.id] = inputs[port.id] + ? [...new Set(Array.isArray(rawSources) ? rawSources.filter(Boolean) : [])] + : []; + } const parent = new Map(); const rank = new Map(); @@ -511,18 +521,74 @@ return Boolean(value); } + const netDetectorSources = new Map(); + const nodeDetectorSources = Object.create(null); + const visitingSourceNodes = new Set(); + const visitingSourceNets = new Set(); + const unionSources = (...lists) => [...new Set(lists.flatMap(list => Array.isArray(list) ? list : []))]; + + function driverDetectorSources(token) { + if (token.startsWith("i:")) { + const id = token.slice(2); + return inputs[id] ? inputDetectorSources[id] || [] : []; + } + const match = /^n:([^:]+):o$/.exec(token); + return match ? nodeSourceValue(match[1]) : []; + } + + function netSourceValue(token) { + const root = find(token); + if (netDetectorSources.has(root)) return netDetectorSources.get(root); + if (visitingSourceNets.has(root)) return []; + visitingSourceNets.add(root); + let sources = []; + for (const member of members.get(root) || [token]) { + if ((member.startsWith("i:") || /^n:[^:]+:o$/.test(member)) && driverValue(member)) { + sources = unionSources(sources, driverDetectorSources(member)); + } + } + visitingSourceNets.delete(root); + netDetectorSources.set(root, sources); + return sources; + } + + function nodeSourceValue(id) { + if (Object.prototype.hasOwnProperty.call(nodeDetectorSources, id)) return nodeDetectorSources[id]; + if (visitingSourceNodes.has(id) || !nodeValue(id)) return []; + const node = nodeMap.get(id); + if (!node || unstableNodes.has(id) || node.type === "on" || node.type === "not") { + nodeDetectorSources[id] = []; + return []; + } + visitingSourceNodes.add(id); + let sources = netSourceValue(`n:${id}:a`); + if (node.type === "and") sources = unionSources(sources, netSourceValue(`n:${id}:b`)); + visitingSourceNodes.delete(id); + nodeDetectorSources[id] = sources; + return sources; + } + const outputs = Object.create(null); - for (const port of config.outputs) outputs[port.id] = netValue(`o:${port.id}`); + const outputDetectorSources = Object.create(null); + for (const port of config.outputs) { + outputs[port.id] = netValue(`o:${port.id}`); + outputDetectorSources[port.id] = outputs[port.id] ? netSourceValue(`o:${port.id}`) : []; + } if (board) { board._circuitInputState = inputs; + board._circuitInputDetectorSources = inputDetectorSources; board._circuitNodeState = nodeValues; board._circuitOutputState = outputs; + board._circuitOutputDetectorSources = outputDetectorSources; for (const port of config.outputs) { const term = terminal(board, `o:${port.id}`); - if (term) term.signalActive = Boolean(outputs[port.id]); + if (term) { + term.signalActive = Boolean(outputs[port.id]); + term._signalDetectorSources = [...(outputDetectorSources[port.id] || [])]; + } } } - return { inputs, nodes: nodeValues, outputs }; + return { inputs, nodes: nodeValues, outputs, inputDetectorSources, outputDetectorSources }; } function nearestPin(config, x, y, maxDistance = 17) { @@ -565,8 +631,6 @@ return null; } - const distanceToSegment = (px, py, ax, ay, bx, by) => global.TarinaiGeometry.pointSegmentDistance(px, py, ax, ay, bx, by); - function wirePath(config, wire) { const a = endpointPosition(config, wire.a); const b = endpointPosition(config, wire.b); @@ -579,7 +643,7 @@ for (let i = config.wires.length - 1; i >= 0; i -= 1) { const path = wirePath(config, config.wires[i]); if (path.length < 2) continue; - const d = distanceToSegment(x, y, path[0].x, path[0].y, path[1].x, path[1].y); + const d = global.TarinaiGeometry.pointSegmentDistance(x, y, path[0].x, path[0].y, path[1].x, path[1].y); if (d <= bestD) { bestD = d; best = { wire: config.wires[i], index: i, distance: d }; } } return best; @@ -608,7 +672,7 @@ } function pointOnSegment(point, a, b) { - return distanceToSegment(point.x, point.y, a.x, a.y, b.x, b.y) < 0.6 + return global.TarinaiGeometry.pointSegmentDistance(point.x, point.y, a.x, a.y, b.x, b.y) < 0.6 && point.x >= Math.min(a.x, b.x) - 0.6 && point.x <= Math.max(a.x, b.x) + 0.6 && point.y >= Math.min(a.y, b.y) - 0.6 && point.y <= Math.max(a.y, b.y) + 0.6; } @@ -700,7 +764,11 @@ dialog = document.createElement("div"); dialog.id = "circuitBoardEditor"; dialog.className = "rotator-editor circuit-grid-editor hidden"; - dialog.innerHTML = `