diff --git a/CMakeLists.txt b/CMakeLists.txt index c4218f1..c581300 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,6 +2,7 @@ cmake_minimum_required(VERSION 3.21) project("Industrial Genesis" VERSION "0.0.1") find_package(Gettext REQUIRED) +find_package(Threads REQUIRED) file(GLOB PO_FILES "${CMAKE_SOURCE_DIR}/po/*.po") @@ -12,10 +13,14 @@ endif() foreach(po_file IN LISTS PO_FILES) get_filename_component(lang ${po_file} NAME_WE) - set(mo_file "${CMAKE_CURRENT_BINARY_DIR}/locale/${lang}/LC_MESSAGES/${PROJECT_NAME}.mo") + # 编译产物放在 mo/ 而不是 locale/:locale/ 是 POST_BUILD 的拷贝目标, + # 两者同目录会变成"把目录拷到自己身上"。 + set(mo_file "${CMAKE_CURRENT_BINARY_DIR}/mo/${lang}/LC_MESSAGES/${PROJECT_NAME}.mo") add_custom_command( OUTPUT ${mo_file} + COMMAND ${CMAKE_COMMAND} -E make_directory + "${CMAKE_CURRENT_BINARY_DIR}/mo/${lang}/LC_MESSAGES" COMMAND ${GETTEXT_MSGFMT_EXECUTABLE} -o ${mo_file} ${po_file} DEPENDS ${po_file} COMMENT "Compiling translation for ${lang}" @@ -28,7 +33,32 @@ endforeach() add_subdirectory(lib/raylib-6.0) add_subdirectory(lib/json-c-json-c-0.19-20260627) -add_executable(Industrial_Genesis src/main.c src/json.c src/ui.c src/texture.c src/timer.c src/tools.c) +add_executable(Industrial_Genesis + src/main.c + src/json.c + src/ui.c + src/texture.c + src/timer.c + src/tools.c + # 时间与天文 + src/astro.c + src/weather.c + src/hydro.c + # 世界生成 + src/terrain.c + src/chunk.c + src/compound.c + src/noise.c + src/random.c + src/climate.c + src/river.c + # 世界状态与地图视图 + src/world.c + src/map.c + src/landing.c + # 局部游戏层(1 格 = 1 米) + src/game.c +) target_compile_definitions(Industrial_Genesis PRIVATE _RELEASE_) target_include_directories(Industrial_Genesis PRIVATE lib/raylib-6.0/src/) target_include_directories(Industrial_Genesis PRIVATE lib/json-c-json-c-0.19-20260627/) @@ -36,9 +66,14 @@ target_include_directories(Industrial_Genesis PRIVATE lib/libuv-1.52.1/) target_link_libraries(Industrial_Genesis PRIVATE raylib) target_link_libraries(Industrial_Genesis PRIVATE json-c) target_link_libraries(Industrial_Genesis PRIVATE uv) +target_link_libraries(Industrial_Genesis PRIVATE Threads::Threads) add_custom_target(translations ALL DEPENDS ${MO_FILES}) +# 没有这行时,`cmake --build build --target Industrial_Genesis` 不会碰 +# translations,运行时用的还是上一次的旧 .mo。 +add_dependencies(Industrial_Genesis translations) + add_custom_command(TARGET Industrial_Genesis POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_CURRENT_SOURCE_DIR}/assets" @@ -48,7 +83,7 @@ add_custom_command(TARGET Industrial_Genesis POST_BUILD add_custom_command(TARGET Industrial_Genesis POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_directory - "${CMAKE_CURRENT_SOURCE_DIR}/locale" + "${CMAKE_CURRENT_BINARY_DIR}/mo" "$/locale" COMMENT "Copying locale files to runtime directory" ) @@ -62,7 +97,7 @@ add_custom_command(TARGET Industrial_Genesis POST_BUILD install(TARGETS Industrial_Genesis RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/) install(DIRECTORY assets DESTINATION .) -install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/locale DESTINATION .) +install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/mo/ DESTINATION locale) install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/config DESTINATION .) install(CODE " diff --git a/po/en_US.po b/po/en_US.po index 2f50d06..9f85d25 100644 --- a/po/en_US.po +++ b/po/en_US.po @@ -126,7 +126,7 @@ msgid "difficulty.easy" msgstr "Easy" msgid "difficulty.normal" -msgstr "Noraml" +msgstr "Normal" msgid "difficulty.hard" msgstr "Hard" @@ -138,7 +138,7 @@ msgid "ore.scarce" msgstr "Scarce" msgid "ore.normal" -msgstr "Noraml" +msgstr "Normal" msgid "ore.abundant" msgstr "Abundant" @@ -153,4 +153,175 @@ msgid "realism.standard" msgstr "Standard" msgid "realism.hardcore" -msgstr "Hardcore" \ No newline at end of file +msgstr "Hardcore" + +#: main.c +msgid "world.generating" +msgstr "Generating world..." + +#: map.c +msgid "map.mode.elevation" +msgstr "Elevation" + +msgid "map.mode.surface" +msgstr "Surface" + +msgid "map.mode.rock" +msgstr "Rock type" + +msgid "map.mode.temperature" +msgstr "Temperature" + +msgid "map.mode.precipitation" +msgstr "Precipitation" + +msgid "map.mode.moisture" +msgstr "Moisture" + + +msgid "map.mode.river" +msgstr "Rivers" + +msgid "map.mode.seasonality" +msgstr "Seasonality" + +msgid "map.hud.seed" +msgstr "Seed" + +msgid "map.hud.center" +msgstr "Center" + +msgid "map.hud.scale" +msgstr "Scale" + +msgid "map.hud.north" +msgstr "N" + +msgid "map.hud.south" +msgstr "S" + +msgid "map.hud.east" +msgstr "E" + +msgid "map.hud.west" +msgstr "W" + +msgid "map.hud.max_zoom" +msgstr "Maximum zoom reached" + +msgid "map.surface.bare_rock" +msgstr "Bare rock" + +msgid "map.surface.soil" +msgstr "Soil" + +msgid "map.surface.sand" +msgstr "Sand" + +msgid "map.surface.grass" +msgstr "Grass" + +msgid "map.surface.forest" +msgstr "Forest" + +msgid "map.surface.water" +msgstr "Water" + +msgid "map.surface.snow" +msgstr "Snow" + +msgid "map.surface.ice" +msgstr "Ice" + +msgid "map.surface.tundra" +msgstr "Tundra" + +msgid "map.surface.taiga" +msgstr "Taiga" + +msgid "map.surface.savanna" +msgstr "Savanna" + +msgid "map.surface.shrub" +msgstr "Shrubland" + +msgid "map.surface.swamp" +msgstr "Wetland" + +msgid "map.rock.granite" +msgstr "Granite" + +msgid "map.rock.basalt" +msgstr "Basalt" + +msgid "map.rock.limestone" +msgstr "Limestone" + +msgid "map.rock.sandstone" +msgstr "Sandstone" + +msgid "map.rock.shale" +msgstr "Shale" + +msgid "map.rock.schist" +msgstr "Schist" + +msgid "map.rock.gneiss" +msgstr "Gneiss" +msgid "map.mode.snow" +msgstr "Snow cover" + +msgid "map.mode.water_temp" +msgstr "Water temperature & ice" + +msgid "map.mode.tide" +msgstr "Tidal range" + +msgid "map.hud.year" +msgstr "Year" + +msgid "map.hud.day" +msgstr "Day" + +msgid "game.landing.hint" +msgstr "Click the map, then Enter to land here (M in game: back to map)" + +# landing site survey +msgid "world.survey" +msgstr "Surveying landing sites..." + +msgid "landing.title" +msgstr "Landing site survey" + +msgid "landing.iron" +msgstr "Iron ore" + +msgid "landing.copper" +msgstr "Copper ore" + +msgid "landing.coal" +msgstr "Coal" + +msgid "landing.forest" +msgstr "Forest" + +msgid "landing.river" +msgstr "River" + +msgid "landing.monsoon" +msgstr "Monsoon" + +msgid "landing.monsoon_val" +msgstr "wet-season %.2f rain %.0f mm/yr" + +msgid "landing.site_stats" +msgstr "elev %.0f m slope %.2f mean T %.1f C" + +msgid "landing.thresholds" +msgstr "ore thresholds (world p88): Fe %.3f Cu %.3f C %.3f" + +msgid "landing.hint" +msgstr "Q/E change site Shift+1-6 pick wheel zoom WASD pan 1-0 recolour Enter land" + +msgid "landing.none" +msgstr "no landing site satisfies the requirements in this world" diff --git a/po/zh_CN.po b/po/zh_CN.po index 86df403..38f5125 100644 --- a/po/zh_CN.po +++ b/po/zh_CN.po @@ -153,4 +153,175 @@ msgid "realism.standard" msgstr "标准" msgid "realism.hardcore" -msgstr "硬核" \ No newline at end of file +msgstr "硬核" + +#: main.c +msgid "world.generating" +msgstr "正在生成世界……" + +#: map.c +msgid "map.mode.elevation" +msgstr "高程" + +msgid "map.mode.surface" +msgstr "地表" + +msgid "map.mode.rock" +msgstr "岩石类型" + +msgid "map.mode.temperature" +msgstr "温度" + +msgid "map.mode.precipitation" +msgstr "降水" + +msgid "map.mode.moisture" +msgstr "湿润度" + + +msgid "map.mode.river" +msgstr "水系" + +msgid "map.mode.seasonality" +msgstr "季节振幅" + +msgid "map.hud.seed" +msgstr "种子" + +msgid "map.hud.center" +msgstr "中心" + +msgid "map.hud.scale" +msgstr "比例" + +msgid "map.hud.north" +msgstr "北" + +msgid "map.hud.south" +msgstr "南" + +msgid "map.hud.east" +msgstr "东" + +msgid "map.hud.west" +msgstr "西" + +msgid "map.hud.max_zoom" +msgstr "已到最大缩放" + +msgid "map.surface.bare_rock" +msgstr "裸岩" + +msgid "map.surface.soil" +msgstr "土壤" + +msgid "map.surface.sand" +msgstr "沙地" + +msgid "map.surface.grass" +msgstr "草地" + +msgid "map.surface.forest" +msgstr "森林" + +msgid "map.surface.water" +msgstr "水域" + +msgid "map.surface.snow" +msgstr "雪" + +msgid "map.surface.ice" +msgstr "冰" + +msgid "map.surface.tundra" +msgstr "苔原" + +msgid "map.surface.taiga" +msgstr "针叶林" + +msgid "map.surface.savanna" +msgstr "稀树草原" + +msgid "map.surface.shrub" +msgstr "灌丛" + +msgid "map.surface.swamp" +msgstr "湿地" + +msgid "map.rock.granite" +msgstr "花岗岩" + +msgid "map.rock.basalt" +msgstr "玄武岩" + +msgid "map.rock.limestone" +msgstr "石灰岩" + +msgid "map.rock.sandstone" +msgstr "砂岩" + +msgid "map.rock.shale" +msgstr "页岩" + +msgid "map.rock.schist" +msgstr "片岩" + +msgid "map.rock.gneiss" +msgstr "片麻岩" +msgid "map.mode.snow" +msgstr "积雪" + +msgid "map.mode.water_temp" +msgstr "水温与冰情" + +msgid "map.mode.tide" +msgstr "潮差" + +msgid "map.hud.year" +msgstr "年" + +msgid "map.hud.day" +msgstr "第几天" + +msgid "game.landing.hint" +msgstr "把准星移到想降落的地方,按 Enter 着陆(游戏中按 M 回到地图)" + +# 着陆点选址 +msgid "world.survey" +msgstr "正在勘选着陆点..." + +msgid "landing.title" +msgstr "着陆点选址" + +msgid "landing.iron" +msgstr "铁矿" + +msgid "landing.copper" +msgstr "铜矿" + +msgid "landing.coal" +msgstr "煤矿" + +msgid "landing.forest" +msgstr "森林" + +msgid "landing.river" +msgstr "河流" + +msgid "landing.monsoon" +msgstr "季风" + +msgid "landing.monsoon_val" +msgstr "雨季强度 %.2f 年降水 %.0f mm" + +msgid "landing.site_stats" +msgstr "海拔 %.0f m 坡度 %.2f 年均温 %.1f C" + +msgid "landing.thresholds" +msgstr "矿点判据(本世界 p88):铁 %.3f 铜 %.3f 煤 %.3f" + +msgid "landing.hint" +msgstr "Q/E 换点 Shift+1-6 直选 滚轮缩放 WASD 平移 1-0 换配色 Enter 着陆" + +msgid "landing.none" +msgstr "这个世界没有找到满足条件的着陆点" diff --git a/src/astro.c b/src/astro.c new file mode 100644 index 0000000..22b797d --- /dev/null +++ b/src/astro.c @@ -0,0 +1,287 @@ +#include "astro.h" +#include "terrain.h" +#include "random.h" + +#include +#include + +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif +#define DEG2RAD_A (M_PI / 180.0) +#define RAD2DEG_A (180.0 / M_PI) + +// 天文参数的随机偏移通道 +enum { + ASTRO_CH_TILT = 0, + ASTRO_CH_YEAR, + ASTRO_CH_DAY, + ASTRO_CH_MOON, + ASTRO_CH_MOON_INCL, + ASTRO_CH_ECC, + ASTRO_CH_EQUINOX, + ASTRO_CH_SOLAR +}; + +// [0,1) 的确定性随机数 +static double rnd01(uint64_t seed, int ch) { + return (double)(game_hash(seed, 0xA57A0000u + (uint64_t)ch, 0) >> 11) + / 9007199254740992.0; +} +// [-1,1) +static double rnd11(uint64_t seed, int ch) { + return rnd01(seed, ch) * 2.0 - 1.0; +} + +void planet_params_init(struct Planet_Params *p, uint64_t seed) { + memset(p, 0, sizeof(*p)); + p->seed = seed; + + // 以地球为基准,叠一个"较小"的种子偏移。 + // 幅度是刻意控制的:地轴倾角 21~26°(保证有明显四季但不会极端), + // 年长 ±4%,日长 ±6%,卫星周期 ±5%。 + p->axial_tilt_deg = EARTH_AXIAL_TILT + 2.5 * rnd11(seed, ASTRO_CH_TILT); + p->year_days = EARTH_YEAR_DAYS * (1.0 + 0.040 * rnd11(seed, ASTRO_CH_YEAR)); + p->day_hours = EARTH_DAY_HOURS * (1.0 + 0.060 * rnd11(seed, ASTRO_CH_DAY)); + p->moon_period_days = EARTH_MOON_DAYS * (1.0 + 0.050 * rnd11(seed, ASTRO_CH_MOON)); + p->moon_inclination_deg = EARTH_MOON_INCL + 3.0 * rnd11(seed, ASTRO_CH_MOON_INCL); + p->eccentricity = EARTH_ECCENTRICITY + 0.012 * rnd11(seed, ASTRO_CH_ECC); + if (p->eccentricity < 0.001) p->eccentricity = 0.001; + p->solar_constant = EARTH_SOLAR_CONSTANT * (1.0 + 0.05 * rnd11(seed, ASTRO_CH_SOLAR)); + + // 历法起点:春分落在一年的前 1/4 附近,再给一点偏移, + // 这样不同存档的"元旦"落在不同季节。 + p->equinox_day = p->year_days * (0.22 + 0.06 * rnd11(seed, ASTRO_CH_EQUINOX)); + + p->day_seconds = p->day_hours * 3600.0; + p->year_seconds = p->year_days * p->day_seconds; + p->moon_seconds = p->moon_period_days * p->day_seconds; +} + +// =============================================================== +// 历法 +// =============================================================== + +double astro_day_of_year(const struct Planet_Params *p, const struct Game_Time *t) { + double days = t->seconds / p->day_seconds; + double d = fmod(days, p->year_days); + if (d < 0.0) d += p->year_days; + return d; +} + +double astro_day_frac(const struct Planet_Params *p, const struct Game_Time *t, + double lon_deg) { + double days = t->seconds / p->day_seconds; + double f = days - floor(days); + // 经度换算成小时:15° = 1 小时 + f += lon_deg / 360.0; + f -= floor(f); + return f; +} + +double astro_local_hour(const struct Planet_Params *p, const struct Game_Time *t, + double lon_deg) { + return astro_day_frac(p, t, lon_deg) * 24.0; +} + +// 近日点的位置:从春分往前推约 0.21 年(地球上是 1 月 3 日) +static double perihelion_day(const struct Planet_Params *p) { + double d = p->equinox_day - 0.21 * p->year_days; + if (d < 0.0) d += p->year_days; + return d; +} + +double astro_solar_declination(const struct Planet_Params *p, + const struct Game_Time *t) { + double doy = astro_day_of_year(p, t); + // 平黄经:0 = 春分 + double lambda = 2.0 * M_PI * (doy - p->equinox_day) / p->year_days; + // 中心差:轨道偏心让真黄经略微偏离平黄经 + double M = 2.0 * M_PI * (doy - perihelion_day(p)) / p->year_days; + double nu = lambda + 2.0 * p->eccentricity * sin(M); + double s = sin(p->axial_tilt_deg * DEG2RAD_A) * sin(nu); + if (s > 1.0) s = 1.0; + if (s < -1.0) s = -1.0; + return asin(s) * RAD2DEG_A; +} + +// 日地距离相对值(1 = 平均值) +static double sun_dist_ratio(const struct Planet_Params *p, + const struct Game_Time *t) { + double doy = astro_day_of_year(p, t); + double M = 2.0 * M_PI * (doy - perihelion_day(p)) / p->year_days; + return 1.0 - p->eccentricity * cos(M); +} + +double astro_solar_cos_zenith(const struct Planet_Params *p, + const struct Game_Time *t, + double lat_deg, double lon_deg) { + double lat = lat_deg * DEG2RAD_A; + double dec = astro_solar_declination(p, t) * DEG2RAD_A; + double H = (astro_day_frac(p, t, lon_deg) - 0.5) * 2.0 * M_PI; // 正午 = 0 + return sin(lat) * sin(dec) + cos(lat) * cos(dec) * cos(H); +} + +double astro_insolation(const struct Planet_Params *p, const struct Game_Time *t, + double lat_deg, double lon_deg) { + double r = sun_dist_ratio(p, t); + double cz = astro_solar_cos_zenith(p, t, lat_deg, lon_deg); + if (cz <= 0.0) return 0.0; + return p->solar_constant / (r * r) * cz; +} + +double astro_daily_insolation(const struct Planet_Params *p, + const struct Game_Time *t, double lat_deg) { + double lat = lat_deg * DEG2RAD_A; + double dec = astro_solar_declination(p, t) * DEG2RAD_A; + double r = sun_dist_ratio(p, t); + double I0 = p->solar_constant / (r * r); + + // 日落时角 + double x = -tan(lat) * tan(dec); + if (x > 1.0) return 0.0; // 极夜 + if (x < -1.0) x = -1.0; // 极昼 + double ws = acos(x); + + double v = ws * sin(lat) * sin(dec) + cos(lat) * cos(dec) * sin(ws); + if (v < 0.0) v = 0.0; + return I0 / M_PI * v; +} + +void astro_insolation_range(const struct Planet_Params *p, double lat_deg, + double *out_min, double *out_max, double *out_mean) { + // 一年采 96 个点足够——日平均辐射是平滑的 + const int N = 96; + double mn = 1e30, mx = -1e30, sum = 0.0; + for (int i = 0; i < N; i++) { + struct Game_Time t = game_time_at((double)i / N * p->year_seconds); + double v = astro_daily_insolation(p, &t, lat_deg); + if (v < mn) mn = v; + if (v > mx) mx = v; + sum += v; + } + if (out_min) *out_min = mn; + if (out_max) *out_max = mx; + if (out_mean) *out_mean = sum / N; +} + +double astro_season_phase(const struct Planet_Params *p, + const struct Game_Time *t, double lat_deg) { + double mn, mx, mean; + astro_insolation_range(p, lat_deg, &mn, &mx, &mean); + double half = (mx - mn) * 0.5; + if (half < 1e-6) return 0.0; // 赤道:没有季节 + double v = astro_daily_insolation(p, t, lat_deg); + double s = (v - mean) / half; + return s < -1.0 ? -1.0 : (s > 1.0 ? 1.0 : s); +} + +// =============================================================== +// 月相 +// =============================================================== + +double astro_lunar_phase(const struct Planet_Params *p, const struct Game_Time *t) { + double ph = fmod(t->seconds / p->moon_seconds, 1.0); + if (ph < 0.0) ph += 1.0; + return ph; +} + +double astro_moon_illumination(const struct Planet_Params *p, + const struct Game_Time *t) { + double ph = astro_lunar_phase(p, t); + return (1.0 - cos(2.0 * M_PI * ph)) * 0.5; +} + +double astro_moonlight(const struct Planet_Params *p, const struct Game_Time *t) { + // 月亮轨道有倾角,所以不是每次满月都最高;用倾角做一个轻微调制 + double ph = astro_lunar_phase(p, t); + double incl_f = cos(p->moon_inclination_deg * DEG2RAD_A * + sin(2.0 * M_PI * ph)); + // 亮度按 1/r²:满月落在近地点时(超级月亮)比远地点亮 30% + double rd = astro_moon_dist_factor(p, t); + double bright = 0.62 + 0.38 * (2.0 - rd); // rd 1.42 -> 1.08, 0.72 -> 1.10 + if (bright > 1.0) bright = 1.0; + double m = astro_moon_illumination(p, t) * (0.85 + 0.15 * incl_f) * bright; + return m < 0.0 ? 0.0 : (m > 1.0 ? 1.0 : m); +} + +// =============================================================== +// 科里奥利 +// =============================================================== + +double astro_omega(const struct Planet_Params *p) { + return 2.0 * M_PI / p->day_seconds; +} + +double astro_coriolis(const struct Planet_Params *p, double lat_deg) { + return 2.0 * astro_omega(p) * sin(lat_deg * DEG2RAD_A); +} + +double astro_coriolis_beta(const struct Planet_Params *p, double lat_deg) { + // f = 2Ω sin φ,而在这张等距圆柱投影的平面世界上 + // φ = 90 - y/WORLD_H*180 => dφ/dy = -π/WORLD_H + // 所以 df/dy = 2Ω cos φ · dφ/dy + return -2.0 * astro_omega(p) * cos(lat_deg * DEG2RAD_A) * M_PI / (double)WORLD_H; +} + +// =============================================================== +// 潮汐 +// =============================================================== + +// 月球轨道的近点月与交点退行周期(天) +#define ANOMALISTIC_MONTH 27.554549 +#define NODAL_PERIOD_YEARS 18.613 + +double astro_moon_dist_factor(const struct Planet_Params *p, + const struct Game_Time *t) { + // 月球轨道偏心率 0.0549。r = a(1 - e·cos M),引潮力按 (a/r)^3 变化, + // 所以近地点比远地点强 2*(1+3e)/(1-3e) 倍(约 1.42)。 + double m_anom = 2.0 * M_PI * (t->seconds / p->day_seconds) / + ANOMALISTIC_MONTH; + double e = 0.0549; + double r = 1.0 - e * cos(m_anom); + return 1.0 / (r * r * r); +} + +double astro_tide_m(const struct Planet_Params *p, const struct Game_Time *t, + double lat_deg, double lon_deg, double local_range_m, + double form) { + (void)lon_deg; + // 太阴日比太阳日长约 1/27.3(月球在公转,地球要多转一点才追上) + double lunar_day_s = p->day_seconds * (1.0 + 1.0 / p->moon_period_days); + + // 主要分潮 + double m2 = cos(2.0 * M_PI * t->seconds / (lunar_day_s * 0.5)); + double s2 = cos(2.0 * M_PI * t->seconds / (p->day_seconds * 0.5)); + double k1 = cos(2.0 * M_PI * t->seconds / p->day_seconds); + double o1 = cos(2.0 * M_PI * t->seconds / lunar_day_s); + + // 近地点:引潮力按 (a/r)^3,归一化到平均值 1 + double dist_f = astro_moon_dist_factor(p, t); + dist_f = 0.5 + 0.5 * dist_f; // 只让 M2/O1 跟着月球走 + + // 朔望大潮:朔和望时日月同轴,两者叠加;上下弦时互相抵消。 + // 注意周期是月相的两倍(一个月里有两次大潮)。 + double ph = astro_lunar_phase(p, t); + double align = cos(4.0 * M_PI * ph); // +1 = 大潮,-1 = 小潮 + double spring = 0.65 + 0.35 * align; + + // 交点潮:月球轨道升交点 18.61 年退行一周,M2 的振幅随之 ±3.7% + double nodal = 1.0 - 0.037 * cos(2.0 * M_PI * t->seconds / + (p->day_seconds * 365.2422 * + NODAL_PERIOD_YEARS)); + + // 纬度因子:半日分潮近似不随纬度变(真实潮是动力潮,不是平衡潮), + // 全日分潮按 sin2φ 衰减——赤道上一天两次潮一样高,没有日不等。 + double lat = lat_deg * DEG2RAD_A; + double diurnal_lat = fabs(sin(2.0 * lat)); + + // 潮型因子把总振幅分给半日/全日两组 + double f = form < 0.0 ? 0.0 : form; + double a_sd = 1.0 / (1.0 + f); + double a_d = f / (1.0 + f); + + double v = a_sd * dist_f * (0.75 * m2 + 0.25 * s2) + + a_d * dist_f * diurnal_lat * (0.55 * k1 + 0.45 * o1); + return local_range_m * 0.5 * spring * nodal * v; +} diff --git a/src/astro.h b/src/astro.h new file mode 100644 index 0000000..9aa0ab8 --- /dev/null +++ b/src/astro.h @@ -0,0 +1,159 @@ +#ifndef ASTRO_H +#define ASTRO_H + +#include +#include + +// =============================================================== +// 行星参数与天文历 +// =============================================================== +// 时间结构(用户指定): +// 游戏内 1 秒 = 现实 1 秒,1 秒 = 30 游戏刻 +// 1 游戏日 = 自转周期;1 游戏年 = 公转周期 +// +// 行星参数以地球为基准,再叠一个由世界种子决定的小幅随机偏移—— +// 所以每个存档的地轴倾角、年长、日长、卫星周期都略有不同, +// 季节的强弱、昼夜长短、潮汐节奏也就跟着不同。 +// +// 坐标约定(世界是正方形平面,等价于等距圆柱投影): +// latitude = climate_latitude(wy),北纬 90° -> 南纬 -90° +// longitude = wx / WORLD_W * 360 - 180,单位度 +// --------------------------------------------------------------- + +#define TICKS_PER_SECOND 30 +#define TICKS_PER_MINUTE (TICKS_PER_SECOND * 60) +#define TICKS_PER_HOUR (TICKS_PER_MINUTE * 60) + +// 地球基准值 +#define EARTH_AXIAL_TILT 23.44 // 度 +#define EARTH_YEAR_DAYS 365.2422 +#define EARTH_DAY_HOURS 23.9345 // 恒星日 +#define EARTH_MOON_DAYS 27.3217 // 恒星月 +#define EARTH_MOON_INCL 5.145 // 度 +#define EARTH_ECCENTRICITY 0.0167 +#define EARTH_SOLAR_CONSTANT 1361.0 // W/m^2,大气层顶 + +struct Planet_Params { + uint64_t seed; + + // --- 被种子微扰的天文参数 --- + double axial_tilt_deg; // 地轴倾角:季节强弱的总开关 + double year_days; // 公转周期 + double day_hours; // 自转周期 + double moon_period_days; // 卫星公转周期 + double moon_inclination_deg; // 卫星轨道对黄道倾角 + double eccentricity; // 轨道偏心率:影响日地距离的年变化 + double equinox_day; // 春分点在一整年里的位置(0..year_days) + double solar_constant; // 大气层顶太阳常数 W/m^2 + + // --- 由上面推导出来的、每帧都要用的常量 --- + double day_seconds; + double year_seconds; + double moon_seconds; +}; + +void planet_params_init(struct Planet_Params *p, uint64_t seed); + +// =============================================================== +// 世界时间 +// =============================================================== + +struct Game_Time { + uint64_t tick; // 游戏刻(1 秒 = 30 刻) + double seconds; // = tick / 30 +}; + +static inline struct Game_Time game_time_at(double seconds) { + struct Game_Time t; + t.seconds = seconds; + t.tick = (uint64_t)(seconds * TICKS_PER_SECOND); + return t; +} +static inline void game_time_advance(struct Game_Time *t, double dt_seconds) { + t->seconds += dt_seconds; + t->tick = (uint64_t)(t->seconds * TICKS_PER_SECOND); +} + +// =============================================================== +// 查询 +// =============================================================== + +// 一年中的第几天(0 .. year_days) +double astro_day_of_year(const struct Planet_Params *p, const struct Game_Time *t); + +// 一天中的位置 0..1(0 = 当地午夜,0.5 = 当地正午) +double astro_day_frac(const struct Planet_Params *p, const struct Game_Time *t, + double lon_deg); + +// 太阳赤纬(度)。这是季节的根源:+23.44 = 北半球夏至。 +double astro_solar_declination(const struct Planet_Params *p, + const struct Game_Time *t); + +// 当地时间(小时,0..24) +double astro_local_hour(const struct Planet_Params *p, const struct Game_Time *t, + double lon_deg); + +// 太阳高度角的余弦(<=0 表示太阳在地平线下) +double astro_solar_cos_zenith(const struct Planet_Params *p, + const struct Game_Time *t, + double lat_deg, double lon_deg); + +// 瞬时天文辐射 W/m^2(大气层顶,含日地距离修正) +double astro_insolation(const struct Planet_Params *p, const struct Game_Time *t, + double lat_deg, double lon_deg); + +// 日平均天文辐射 W/m^2——气候的真正驱动量 +double astro_daily_insolation(const struct Planet_Params *p, + const struct Game_Time *t, double lat_deg); + +// 该纬度全年的日平均天文辐射极值(算季节振幅、归一化相位要用) +void astro_insolation_range(const struct Planet_Params *p, double lat_deg, + double *out_min, double *out_max, double *out_mean); + +// ---- 月相 ---- +// 0 = 新月,0.5 = 满月 +double astro_lunar_phase(const struct Planet_Params *p, const struct Game_Time *t); +// 月面被照亮的比例 0..1 +double astro_moon_illumination(const struct Planet_Params *p, + const struct Game_Time *t); +// 月相抬头(用于"随月相变化"的其它系统)0..1,满月 = 1 +double astro_moonlight(const struct Planet_Params *p, const struct Game_Time *t); + +// ---- 潮汐 ---- +// 相对平均海平面的潮位(米)。 +// +// 分潮: +// M2 太阴半日潮(周期 = 半个太阴日)—— 主分潮 +// S2 太阳半日潮(周期 = 半个太阳日) +// K1/O1 日月全日潮(周期 = 一个太阴/太阳日)—— 混合潮和全日潮的来源 +// 调制: +// 朔望大潮/小潮(周期是月相的两倍:朔和望都是大潮) +// 近地点大潮(近点月 27.55 天,月球近地点时引潮力按 1/r³ 增强 ~16%, +// 和朔望叠加就是"超级月亮大潮") +// 交点潮(18.61 年,M2 振幅 ±3.7%) +// 纬度:全日分潮按 sin2φ 衰减,所以赤道上是纯半日潮(无日不等) +// +// form = 潮型因子 (K1+O1)/(M2+S2):<0.25 半日潮,0.25~1.5 混合潮,>1.5 全日潮。 +// 真实海洋里三种都有,取决于海盆形状,所以它是个地理参数(hydro.c 生成)。 +double astro_tide_m(const struct Planet_Params *p, const struct Game_Time *t, + double lat_deg, double lon_deg, double local_range_m, + double form); + +// 月球距离因子 (a/r)^3:近地点 ~1.17,远地点 ~0.85。 +// 月光亮度、引潮力都用它。 +double astro_moon_dist_factor(const struct Planet_Params *p, + const struct Game_Time *t); + +// ---- 科里奥利 ---- +// 自转角速度(由自转周期决定,所以种子改了日长,科里奥利力也跟着变) +double astro_omega(const struct Planet_Params *p); +// 科里奥利参数 f = 2·Ω·sin φ,单位 1/s。赤道为 0,两极最大。 +double astro_coriolis(const struct Planet_Params *p, double lat_deg); +// f 随纬度变化率 df/dy(1/(m·s))。台风北偏(β 漂移)就是它造成的。 +double astro_coriolis_beta(const struct Planet_Params *p, double lat_deg); + +// 一年中的季节相位 -1..1(+1 = 当地盛夏)。供 UI / 其它系统用。 +double astro_season_phase(const struct Planet_Params *p, + const struct Game_Time *t, double lat_deg); + +#endif diff --git a/src/chunk.c b/src/chunk.c index cf6f750..dd68b31 100644 --- a/src/chunk.c +++ b/src/chunk.c @@ -1,5 +1,21 @@ #include "chunk.h" #include "noise.h" +#include "climate.h" +#include "world.h" +#include "weather.h" + +#include + +// 水面封冻的判据:冰厚超过这个值就算冰面而不是明水。 +// 海冰和湖冰的冰厚都由 river.c 的 compute_ice 算好,这里只做判定。 +#define ICE_COVER_MIN 0.05 + +// 陡到挂不住土的坡度。见 classify_surface。 +// 陡崖阈值。原来是 0.75,但那是按 40km 网格的坡度分布定的——那个尺度上 +// 坡度根本到不了 0.75(实测最大 0.35),所以"裸岩"这个分支从来没触发过。 +// 现在有了 20m 基线的真实坡面坡度(实测均值 0.13、最大 0.49),阈值按新 +// 分布重新定:0.45 约对应最陡的 1% 陆地,也就是真正的崖壁。 +#define BARE_ROCK_SLOPE 0.45 // ---------- 坐标辅助 ---------- @@ -19,23 +35,18 @@ struct Vector2_double tile_world_pos(int cx, int cy, int tx, int ty) { } // ---------- 宏观高程:从 World_Block 插值 ---------- - -static int wrap_block_x(int bx) { - bx = bx % (int)WORLD_BLOCK_COUNT_X; - if (bx < 0) bx += (int)WORLD_BLOCK_COUNT_X; - return bx; -} - -static int wrap_block_y(int by) { - if (by < 0) by = 0; - if (by >= (int)WORLD_BLOCK_COUNT_Y) by = (int)WORLD_BLOCK_COUNT_Y - 1; - return by; -} +// wrap_block_x / wrap_block_y 由 terrain.h 导出 static double block_elev_at(struct World_Block *blocks, int bx, int by) { bx = wrap_block_x(bx); by = wrap_block_y(by); - return blocks[by * WORLD_BLOCK_COUNT_X + bx].elevation; + return blocks[by * (int)WORLD_BLOCK_COUNT_X + bx].elevation; +} + +// 块与块之间用 smoothstep 而不是线性插值:线性插值只有 C0 连续, +// 梯度在 512km 的块边界上跳变,山体阴影会把这些边界画成一整张方格网。 +static double block_lerp_t(double t) { + return t * t * (3.0 - 2.0 * t); } static double macro_elevation_at(struct World_Block *blocks, @@ -44,8 +55,8 @@ static double macro_elevation_at(struct World_Block *blocks, double by = wy / (double)WORLD_BLOCK_SIZE - 0.5; int ix = (int)floor(bx); int iy = (int)floor(by); - double fx = bx - ix; - double fy = by - iy; + double fx = block_lerp_t(bx - ix); + double fy = block_lerp_t(by - iy); double e00 = block_elev_at(blocks, ix, iy); double e10 = block_elev_at(blocks, ix + 1, iy); @@ -58,192 +69,416 @@ static double macro_elevation_at(struct World_Block *blocks, } // ---------- 高程场 ---------- +// 宏观高程来自 512km 的板块网格,而板块内部几乎是常数——如果只叠几十米的 +// 细噪声,整块大陆就是一块 1.1km 高的平板,区域内视图会一片死平。 +// 所以这里再按"离海平面的高度 + 构造辐合量"调制一个中尺度起伏场: +// 稳定克拉通是缓丘,造山带才是真正的山脉,深海平原则接近平坦。 + +static double macro_convergence_at(struct World_Block *blocks, + double wx, double wy) { + double bx = wx / (double)WORLD_BLOCK_SIZE - 0.5; + double by = wy / (double)WORLD_BLOCK_SIZE - 0.5; + int ix = (int)floor(bx); + int iy = (int)floor(by); + double fx = block_lerp_t(bx - ix), fy = block_lerp_t(by - iy); + + int cx = (int)WORLD_BLOCK_COUNT_X; + int x0 = wrap_block_x(ix), x1 = wrap_block_x(ix + 1); + int y0 = wrap_block_y(iy), y1 = wrap_block_y(iy + 1); + + double a = blocks[y0 * cx + x0].convergence * (1.0 - fx) + + blocks[y0 * cx + x1].convergence * fx; + double b = blocks[y1 * cx + x0].convergence * (1.0 - fx) + + blocks[y1 * cx + x1].convergence * fx; + return a * (1.0 - fy) + b * fy; +} + +// 局部起伏半幅(米)。构造辐合越强、离海平面越高,地面越崎岖。 +static double relief_amplitude_at(struct World_Block *blocks, + double wx, double wy) { + double macro = macro_elevation_at(blocks, wx, wy); + double conv = macro_convergence_at(blocks, wx, wy); + double h = (macro < 0.0) ? -macro : macro; + + if (macro < 0.0) { + // 洋底:大陆架和洋中脊崎岖,深海平原平坦 + double relief = 600.0 - h * 0.08; + return relief < 120.0 ? 120.0 : relief; + } + double relief = 150.0 + h * 0.60; + if (conv > 0.0) relief += conv * 260.0; + return relief > 3200.0 ? 3200.0 : relief; +} + +// 给水文网格(40km)用的带限基准地形。 +// elevation_at 里的 8km / 400m 倍频远低于网格分辨率,直接采样会变成 +// 逐格白噪声——40km 网格上凭空多出成千上万个闭合洼地,填洼之后 +// 12% 的陆地都成了"湖"。这里只保留 100km / 50km 两个倍频, +// 更细的起伏留给下面的采样层叠加(delta 是 40km 尺度,不会冲突)。 +double terrain_relief_amplitude(double wx, double wy, const struct World *w) { + return relief_amplitude_at(w->blocks, wx, wy); +} + +double terrain_base_elevation_coarse(double wx, double wy, const struct World *w) { + double macro = macro_elevation_at(w->blocks, wx, wy); + double relief = relief_amplitude_at(w->blocks, wx, wy); + // 120km + 60km 两个倍频:都明显大于 40km 网格,不会被采样成假洼地。 + double mega = fractal_noise(w->seed, CHUNK_NOISE_MED, wx, wy, 120000.0, 2, 0.35); + return macro + (mega - 0.5) * relief; +} + +static double ground_detail_at(double relief, double wx, double wy, + uint64_t seed); static double elevation_at(struct World_Block *blocks, - double wx, double wy, uint64_t seed) { - double e = macro_elevation_at(blocks, wx, wy); + double wx, double wy, uint64_t seed, int lod) { + double macro = macro_elevation_at(blocks, wx, wy); + double relief = relief_amplitude_at(blocks, wx, wy); - double med = fractal_noise(seed, CHUNK_NOISE_MED, wx, wy, 100.0, 4, 0.5); - double fine = fractal_noise(seed, CHUNK_NOISE_FINE, wx, wy, 15.0, 3, 0.5); - double detail = fractal_noise(seed, CHUNK_NOISE_DETAIL, wx, wy, 3.0, 2, 0.5); + // 三个尺度:山系(≈100km) / 丘陵(≈8km) / 起伏(≈400m) + double mega = fractal_noise(seed, CHUNK_NOISE_MED, wx, wy, 100000.0, 4, 0.5); + double e = macro + (mega - 0.5) * relief; - e += (med - 0.5) * 60.0; - e += (fine - 0.5) * 6.0; - e += (detail - 0.5) * 1.0; + // lod >= 2:连 8km / 400m 两个倍频也丢掉。一个像素跨 4km 以上时, + // 它们只会变成逐像素的椒盐噪声,采样时间却占大头。 + if (lod < 2) { + double meso = fractal_noise(seed, CHUNK_NOISE_FINE, wx, wy, 8000.0, 3, 0.5); + double micro = fractal_noise(seed, CHUNK_NOISE_DETAIL, wx, wy, 400.0, 3, 0.5); + e += (meso - 0.5) * relief * 0.30; + e += (micro - 0.5) * relief * 0.03; + } + + // 米级细节只在地面视图里看得见。地图上一个像素动辄几百米, + // 叠上去只是给山体阴影加噪声,却要多跑 6 个 value_noise。 + if (lod <= 0) e += ground_detail_at(relief, wx, wy, seed); return e; } -// ---------- 气候 ---------- - -static double latitude_of(double wy) { - double half = WORLD_H * 0.5; - double t = wy / half; - return -t * 90.0; +// 米级细尺度:给 1m/格 的局部视图用。上面三个倍频最细只到 400m, +// 站在地面看世界是一张光滑平面。这里补 60m / 15m / 4m 三层, +// 让地表有沟坎、垄脊、碎石坡。 +// +// 幅度 = 常数 + 与起伏半幅成正比:平原(relief 小)只有一两米的微波, +// 山地能到十几米。常数项保证极平坦的沉积平原也不是绝对平面。 +// 注意这三层**不参与**河流层(river.c 用的是 coarse 版),所以河网、 +// 流域、气候反馈都不受它们影响;受影响的只有 chunk 层的高程、坡度和 +// 由坡度决定的地表分类——这正是用户要的。 +// 起伏半幅用软饱和:山地不该按线性一直放大,否则 2000m 起伏的山区 +// 会变成一片 60m 波长的断崖阵,地表分类全塌成裸岩。 +static double ground_detail_at(double relief, double wx, double wy, uint64_t seed) { + double r = relief / (1.0 + relief / 900.0); + // 幅度是**标定**出来的:目标是把陆地平均坡度从 0.06 提到 0.13~0.15 + // (实测农田平原 0.02~0.05、丘陵 0.1~0.2、山地 0.3~0.7)。 + double dl = 8.0 + r * 0.0270; // ≈60m 波长:缓坡、土坎 + double dm = 2.0 + r * 0.0048; // ≈15m 波长:冲沟、垄 + double ds = 0.5 + r * 0.0010; // ≈4m 波长:碎石、草墩 + double gl = fractal_noise(seed, CHUNK_NOISE_GROUND_L, wx, wy, 60.0, 2, 0.5); + double gm = fractal_noise(seed, CHUNK_NOISE_GROUND_M, wx, wy, 15.0, 2, 0.5); + double gs = fractal_noise(seed, CHUNK_NOISE_GROUND_S, wx, wy, 4.0, 2, 0.5); + return (gl - 0.5) * dl + (gm - 0.5) * dm + (gs - 0.5) * ds; } -static double base_temperature(double lat, double elevation) { - double T = 30.0 - 60.0 * fabs(lat) / 90.0; - T -= elevation * 0.0065; - return T; -} - -static double base_moisture(double lat, double wx, double wy, uint64_t seed) { - double abs_lat = fabs(lat); - double m; - if (abs_lat < 10.0) m = 0.85; - else if (abs_lat < 25.0) m = 0.85 - (abs_lat - 10.0) * 0.05; - else if (abs_lat < 35.0) m = 0.10; - else if (abs_lat < 55.0) m = 0.10 + (abs_lat - 35.0) * 0.025; - else m = 0.60; - - double n = fractal_noise(seed, CHUNK_NOISE_MOIST, wx, wy, 2000.0, 3, 0.5); - m = m * (0.7 + 0.6 * n); - if (m < 0.0) m = 0.0; - if (m > 1.0) m = 1.0; - return m; +// 坡面坡度与坡向:20m 基线的中心差分。 +// 基线要明显大于细尺度噪声的波长(4~15m),否则量到的是"石头缝"而不是 +// "山坡",地表分类会被微地形噪声淹没。 +#define SLOPE_BASE_M 20.0 +static void slope_aspect_at(double wx, double wy, const struct World *w, + double *slope_out, double *aspect_out) { + double ex1 = terrain_base_elevation(wx + SLOPE_BASE_M, wy, w); + double ex0 = terrain_base_elevation(wx - SLOPE_BASE_M, wy, w); + double ey1 = terrain_base_elevation(wx, wy + SLOPE_BASE_M, w); + double ey0 = terrain_base_elevation(wx, wy - SLOPE_BASE_M, w); + double gx = (ex1 - ex0) / (2.0 * SLOPE_BASE_M); + double gy = (ey1 - ey0) / (2.0 * SLOPE_BASE_M); + if (slope_out) *slope_out = sqrt(gx * gx + gy * gy); + if (aspect_out) *aspect_out = atan2(gy, gx); } // ---------- 岩石类型 ---------- +// plate_blend_at() 混合板块属性,rock_weights_blend() 给出 7 种岩石的连续权重, +// 只在需要标量 rock_type 时取权重最大者(与 test/test_mineral_map.c 一致)。 -static enum Rock_Type rock_from_plate(struct Plate *plate, uint64_t seed, - double wx, double wy) { - double n = fractal_noise(seed, CHUNK_NOISE_ROCK, wx, wy, 800.0, 3, 0.5); - - if (plate->is_ocean) return ROCK_BASALT; - - if (plate->age > 2500) { - if (n < 0.4) return ROCK_GRANITE; - if (n < 0.7) return ROCK_GNEISS; - return ROCK_SCHIST; +static enum Rock_Type dominant_rock(const double rock_w[ROCK_COUNT]) { + int best = 0; + for (int r = 1; r < ROCK_COUNT; r++) { + if (rock_w[r] > rock_w[best]) best = r; } - if (plate->thick > 50) { - if (n < 0.5) return ROCK_GRANITE; - if (n < 0.8) return ROCK_SCHIST; - return ROCK_GNEISS; - } - if (n < 0.35) return ROCK_LIMESTONE; - if (n < 0.70) return ROCK_SANDSTONE; - return ROCK_SHALE; + return (enum Rock_Type)best; } -// ---------- 地表、土壤、植被 ---------- +// ---------- 地表 / 生物群系 ---------- +// 气候给出年均温 T、年温差半幅 A、降水 M;这里把它们翻译成地表类型。 +// 判据顺序就是优先级:先排除水/陡崖/常年积雪,再按"温度带 × 水分"分。 -static void surface_from_climate(struct Tile *t, enum Rock_Type rock) { +static double smoothstep01(double t) { + if (t < 0.0) t = 0.0; + if (t > 1.0) t = 1.0; + return t * t * (3.0 - 2.0 * t); +} + +static double clamp01_chunk(double x) { + return x < 0.0 ? 0.0 : (x > 1.0 ? 1.0 : x); +} + +double vegetation_potential(double temperature, double moisture, + double seasonal_amplitude, double slope) { + double temp_f = smoothstep01((temperature + 8.0) / 18.0); + double water_f = smoothstep01((moisture - 0.12) / 0.30); + double cont_f = 1.0 - 0.35 * smoothstep01((seasonal_amplitude - 15.0) / 20.0); + // 坡度抑制:平地不打折,约 30° 时降到 1/4 + double slope_f = 1.0 - 0.75 * smoothstep01((slope - 0.05) / 0.45); + return temp_f * water_f * slope_f * cont_f; +} + +static void classify_surface(struct Tile *t, enum Rock_Type rock) { + double E = t->elevation; double T = t->temperature; double M = t->moisture; + double A = t->seasonal_amplitude; double S = t->slope; - if (t->elevation < 0.0) { - t->surface_type = SURFACE_WATER; + t->soil_type = SOIL_SILT; + t->vegetation = 0.0; + t->fertility = 0.0; + + // ---- 1. 水面 / 海冰 / 湖冰 ---- + // water_depth 是河流层给出的湖水深度:湖面以上的岸边仍然算陆地, + // 所以湖岸线是跟着地形走的,不是 40km 的方格。 + // 结不结冰由 river.c 算出的冰厚决定(湖冰走 Stefan 定律, + // 所以深湖比浅湖封冻晚、冰更薄,冻融也受季节振幅影响)。 + if (E < 0.0 || t->water_depth > 0.0f) { + t->surface_type = (t->ice_thick >= ICE_COVER_MIN) + ? SURFACE_ICE : SURFACE_WATER; t->soil_type = SOIL_NONE; - t->vegetation = 0.0; - t->fertility = 0.0; return; } - - if (T < -5.0) { - t->surface_type = (T < -20.0) ? SURFACE_ICE : SURFACE_SNOW; - t->soil_type = SOIL_NONE; - t->vegetation = 0.0; - t->fertility = 0.0; - return; - } - - if (S > 0.8) { + // ---- 2. 陡崖:这个斜率以上的坡面挂不住土 ---- + // 阈值是按本模型实际的坡度分布定的(见 test/dbg_river.c 的坡度直方图): + // 0.75 约对应最陡的 2~3% 陆地。真实的悬崖是米级的,40km 网格上 + // 只能用"平均坡度很陡"来近似。 + if (S > BARE_ROCK_SLOPE) { t->surface_type = SURFACE_BARE_ROCK; t->soil_type = SOIL_NONE; - t->vegetation = 0.0; - t->fertility = 0.0; return; } - double veg = 0.0; - if (T > 5.0 && M > 0.3) { - double base = M * (T / 30.0); - if (base > 1.0) base = 1.0; - veg = base * (1.0 - S); - } + double veg = vegetation_potential(T, M, A, S); t->vegetation = veg; - if (M < 0.25 && T > 15.0) { - t->surface_type = SURFACE_SAND; - t->soil_type = SOIL_SAND; - } else if (veg > 0.5) { - t->surface_type = SURFACE_FOREST; - t->soil_type = SOIL_LOAM; - } else if (veg > 0.15) { - t->surface_type = SURFACE_GRASS; - t->soil_type = SOIL_LOAM; - } else { - t->surface_type = SURFACE_SOIL; - t->soil_type = (rock == ROCK_LIMESTONE) ? SOIL_CLAY : SOIL_SILT; + // ---- 3. 温度带 × 湿润度 ---- + // M 是对数干旱指数(0.5 约等于 P = 0.45·PET),阈值按各带实际需要的 + // 年降水量定:温带森林约 400mm 起,热带雨林约 1750mm 起。 + if (T < -10.0) { + t->surface_type = SURFACE_SNOW; + t->soil_type = SOIL_NONE; + } else if (T < 0.0) { + t->surface_type = SURFACE_TUNDRA; + t->soil_type = SOIL_PEAT; + } else if (T < 6.0) { // 亚寒带:针叶林 / 寒漠 + if (M < 0.28) { t->surface_type = SURFACE_TUNDRA; t->soil_type = SOIL_PEAT; } + else { t->surface_type = SURFACE_TAIGA; t->soil_type = SOIL_LOAM; } + } else if (T < 20.0) { // 温带 / 亚热带 + if (M < 0.26) { t->surface_type = SURFACE_SAND; t->soil_type = SOIL_SAND; } + else if (M < 0.40) { t->surface_type = SURFACE_SHRUB; t->soil_type = SOIL_SILT; } + else if (M < 0.55) { t->surface_type = SURFACE_GRASS; t->soil_type = SOIL_SILT; } + else if (M < 0.82) { + t->surface_type = SURFACE_FOREST; + t->soil_type = (rock == ROCK_LIMESTONE) ? SOIL_CLAY : SOIL_LOAM; + } else { t->surface_type = SURFACE_SWAMP; t->soil_type = SOIL_PEAT; } + } else { // 热带 + if (M < 0.30) { t->surface_type = SURFACE_SAND; t->soil_type = SOIL_SAND; } + else if (M < 0.62) { t->surface_type = SURFACE_SAVANNA; t->soil_type = SOIL_SILT; } + else if (M < 0.82) { + t->surface_type = SURFACE_FOREST; + t->soil_type = (rock == ROCK_LIMESTONE) ? SOIL_CLAY : SOIL_LOAM; + } else { t->surface_type = SURFACE_SWAMP; t->soil_type = SOIL_PEAT; } } t->fertility = veg * M; } +// ---------- 单点采样 ---------- +// 高程 + 气候 + 板块混合 + 岩石权重是 chunk 生成和地图视图的共同前置, +// 抽出来避免两处逻辑漂移。 + +double terrain_base_elevation(double wx, double wy, const struct World *w) { + return elevation_at(w->blocks, wx, wy, w->seed, 0); +} + +// 地图用的降精度版:lod > 0 时丢掉米级细节。 +// 地图上一个像素动辄几十米到几十公里,这些细节根本投影不出来, +// 但它们占了单点采样一半的时间(6 个 value_noise)。 +double terrain_base_elevation_lod(double wx, double wy, + const struct World *w, int lod) { + return elevation_at(w->blocks, wx, wy, w->seed, lod); +} + +static void geology_core(struct Tile *t, + struct Plate_Blend *plate_blend, + double rock_w[ROCK_COUNT], + double wx, double wy, const struct World *w, + int lod) { + // ---- 地形:构造基准 + 河流的区域侵蚀/淤积 - 河谷下切 ---- + double z = terrain_base_elevation_lod(wx, wy, w, lod); + + struct River_Sample rs; + river_sample(w->rivers, wx, wy, &rs); + z += rs.delta; + z -= rs.carve; + + // 湖泊:地形低于湖面就是水下 + double water_z; + if (river_submerged(w->rivers, wx, wy, z, &water_z)) { + t->water_depth = (float)(water_z - z); + t->elevation = water_z; + } else { + t->water_depth = 0.0f; + t->elevation = z; + } + + struct Climate_Sample cs; + climate_sample(&w->climate, w->seed, wx, wy, t->elevation, &cs); + + // ---- 河岸湿润度 ---- + // 尼罗河穿过撒哈拉,两岸照样葱绿——靠的不是降水变多,是水就在旁边。 + // 这里把"离河道的距离"直接折进可供植物利用的水分。 + double ripa = 0.0; + if (rs.valley_half > 0.0) { + double u = rs.dist / rs.valley_half; + ripa = exp(-u * u); + } + double wet_boost = 0.80 * ripa; + if (t->water_depth > 0.0f) wet_boost = 0.90; // 开阔水面 + double M = cs.moisture; + M = M + (1.0 - M) * wet_boost; + + t->temperature = cs.temperature; + t->moisture = M; + // 水体热惯量大:河湖附近年温差被压平 + t->seasonal_amplitude = (float)(cs.seasonal_amplitude * + (1.0 - 0.35 * ripa - (t->water_depth > 0.0f ? 0.2 : 0.0))); + t->precipitation = (float)cs.precipitation; + t->precip_mm = (float)cs.precip_mm; + + // ---- 河流状态量(通航、冰情、泥沙)---- + t->water_temp = (float)rs.water_temp; + t->ice_thick = (float)rs.ice_thick; + t->sed_conc = (float)rs.sed_conc; + t->jam_risk = (float)rs.jam_risk; + t->river_depth = (rs.is_channel && rs.dist <= rs.width * 0.5) + ? (float)rs.depth_max : 0.0f; + // 枯水期、3 米龙骨下富余 15% 时的最大吃水:反解断面水深 + if (t->river_depth > 0.0f) { + double hmax = (rs.depth_low > 0.0) ? rs.depth_low : rs.depth_max; + t->navigable_draft = (float)(hmax / 1.15); + } else { + t->navigable_draft = 0.0f; + } + + // ---- 坡度 ---- + // 河谷断面的坡度是解析求导出来的(每像素都做四次差分采样太贵)。 + // 河谷之外的坡度由局部起伏幅度估算:实测起伏半幅 150m 的平原地面 + // 坡度约 3%,起伏 2000m 的山地约 20%,和真实地形同量级。 + double relief = relief_amplitude_at(w->blocks, wx, wy); + // 坡度 = 构造坡面(20m 基线的有限差分,含米级细节)与河谷坡(解析) + // 按平方和合成。0.015(≈0.86°)是下限:完全水平的平原也要有一点 + // 排水坡度,否则坡面扩散和地表分类都退化。 + double gmag = 0.0, gasp = 0.0; + if (lod <= 0) { + slope_aspect_at(wx, wy, w, &gmag, &gasp); + } else { + // 地图尺度上 20m 基线的差分没有意义(一个像素跨几百米), + // 而且它占单点采样 70% 的时间。用起伏半幅线性换算成等效坡度。 + // 系数是标定出来的(见 test/dbg_lodslope.c):把 LOD 坡度的 + // p10/p50/p90 对准真实坡度的 0.053/0.119/0.216(略偏高,宁可让地图上 + // 的高山看着有点岩壁,也不要让整片陆地变成裸岩)。 + // 注意别拍脑袋——乱填一个系数会让地图上整个陆地都判成裸岩。 + gmag = 0.00015 * relief; + gasp = 0.0; // 地图配色不用坡向 + } + t->slope = sqrt(rs.slope * rs.slope + gmag * gmag) + 0.015; + t->aspect = gasp; + + // 板块属性在 World_Block 边界上是离散的,先做空间混合再取岩石权重, + // 否则会出现 512km 网格状的硬缝。 + plate_blend_at(w->blocks, w->plates, wx, wy, plate_blend); + + double rock_n = fractal_noise(w->seed, CHUNK_NOISE_ROCK, wx, wy, 800.0, 3, 0.5); + rock_weights_blend(plate_blend, rock_n, rock_w); + + t->rock_type = (uint8_t)dominant_rock(rock_w); +} + +void terrain_sample(struct Tile *t, double wx, double wy, const struct World *w) { + terrain_sample_lod(t, wx, wy, w, 0); +} + +// lod = 0:完整精度(米级细节 + 20m 基线坡度),地面视图用。 +// lod > 0:地图用。丢掉米级细节,坡度改用起伏半幅估算—— +// 地形/气候/岩石/化合物都不变,只是不再解析亚像素的结构。 +void terrain_sample_lod(struct Tile *t, double wx, double wy, + const struct World *w, int lod) { + struct Plate_Blend plate_blend; + double rock_w[ROCK_COUNT]; + + geology_core(t, &plate_blend, rock_w, wx, wy, w, lod); + classify_surface(t, (enum Rock_Type)t->rock_type); +} + +void terrain_sample_at(struct Tile *t, double wx, double wy, + const struct World *w, double t_seconds) { + terrain_sample(t, wx, wy, w); + if (t_seconds < 0.0 || w->weather.bands <= 0) return; + + // 用瞬时天气覆盖气候量。地形和化合物不动——它们不随天气变。 + struct Weather_Sample ws; + weather_sample((struct World *)w, wx, wy, t->elevation, t_seconds, &ws); + t->temperature = ws.temperature; + t->precipitation = (float)clamp01_chunk(ws.precipitation / 40.0); + t->precip_mm = (float)(ws.precip_24h * 365.0 / 24.0); + t->seasonal_amplitude = (float)(t->seasonal_amplitude); // 年景不变 + t->water_temp = (float)ws.temperature; + t->ice_thick = (float)ws.ice_thick; + t->jam_risk = (float)ws.jam_risk; + // 湿润度随降水与季风走 + double m = clamp01_chunk(0.25 + ws.monsoon_rain * 0.5 + + ws.precipitation / 60.0 + ws.humidity * 0.2); + t->moisture = m; + classify_surface(t, (enum Rock_Type)t->rock_type); +} + +void tile_sample(struct Tile *t, double wx, double wy, const struct World *w) { + tile_sample_with(t, wx, wy, w, &w->settings); +} + +// 显式指定化合物参数:调试/测试里要在同一个世界、同一个坐标上比较 +// 不同"创建世界选项"对矿物组成的影响(见 test_map.c 的接线对照表)。 +void tile_sample_with(struct Tile *t, double wx, double wy, + const struct World *w, + const struct Compound_Settings *settings) { + struct Plate_Blend plate_blend; + double rock_w[ROCK_COUNT]; + + geology_core(t, &plate_blend, rock_w, wx, wy, w, 0); + tile_generate_compounds(t, rock_w, &plate_blend, wx, wy, w->seed, settings); + classify_surface(t, (enum Rock_Type)t->rock_type); +} + // ---------- 主生成函数 ---------- -struct Chunk *chunk_generate(int cx, int cy, uint64_t seed, - struct World_Block *blocks, - struct Plate_list plates) { +struct Chunk *chunk_generate(int cx, int cy, const struct World *w) { struct Chunk *chunk = malloc(sizeof(struct Chunk)); chunk->cx = cx; chunk->cy = cy; - // 第一遍:高程 + // 一次采样搞定:geology_core 会把高程、坡度、气候、地表全部填好。 + // 原来这里是"先算高程、再用 1m 基线差分算坡度、最后再单点采样"三遍, + // 但 1m 基线相对于地形起伏尺度太短,算出来的坡度恒等于 0 + // (裸岩判据因此从来没触发过),所以坡度改由河谷断面解析求导得到。 for (int ty = 0; ty < CHUNK_TILE_COUNT; ty++) { for (int tx = 0; tx < CHUNK_TILE_COUNT; tx++) { struct Vector2_double pos = tile_world_pos(cx, cy, tx, ty); - struct Tile *t = &chunk->tiles[ty][tx]; - t->elevation = elevation_at(blocks, pos.x, pos.y, seed); - } - } - - // 第二遍:坡度 - for (int ty = 0; ty < CHUNK_TILE_COUNT; ty++) { - for (int tx = 0; tx < CHUNK_TILE_COUNT; tx++) { - struct Vector2_double pos = tile_world_pos(cx, cy, tx, ty); - struct Tile *t = &chunk->tiles[ty][tx]; - - double eE = elevation_at(blocks, pos.x + TILE_SIZE, pos.y, seed); - double eW = elevation_at(blocks, pos.x - TILE_SIZE, pos.y, seed); - double eS = elevation_at(blocks, pos.x, pos.y + TILE_SIZE, seed); - double eN = elevation_at(blocks, pos.x, pos.y - TILE_SIZE, seed); - - double dx = (eE - eW) * 0.5; - double dy = (eS - eN) * 0.5; - double grad = sqrt(dx * dx + dy * dy); - - t->slope = atan(grad); - t->aspect = atan2(dy, dx); - } - } - - for (int ty = 0; ty < CHUNK_TILE_COUNT; ty++) { - for (int tx = 0; tx < CHUNK_TILE_COUNT; tx++) { - struct Vector2_double pos = tile_world_pos(cx, cy, tx, ty); - struct Tile *t = &chunk->tiles[ty][tx]; - - double lat = latitude_of(pos.y); - t->temperature = base_temperature(lat, t->elevation); - t->moisture = base_moisture(lat, pos.x, pos.y, seed); - - int bx = (int)(pos.x / (double)WORLD_BLOCK_SIZE); - int by = (int)(pos.y / (double)WORLD_BLOCK_SIZE); - bx = wrap_block_x(bx); - by = wrap_block_y(by); - int b_idx = by * WORLD_BLOCK_COUNT_X + bx; - struct Plate *plate = plates._p + blocks[b_idx].plate_id; - - enum Rock_Type rock = rock_from_plate(plate, seed, pos.x, pos.y); - t->rock_type = (uint8_t)rock; - - // 化合物级组分生成 - tile_generate_compounds(t, (int)rock, plate, - pos.x, pos.y, seed, NULL); - - surface_from_climate(t, rock); + tile_sample(&chunk->tiles[ty][tx], pos.x, pos.y, w); } } @@ -252,4 +487,4 @@ struct Chunk *chunk_generate(int cx, int cy, uint64_t seed, void chunk_free(struct Chunk *c) { free(c); -} \ No newline at end of file +} diff --git a/src/chunk.h b/src/chunk.h index 05f936e..1a80c79 100644 --- a/src/chunk.h +++ b/src/chunk.h @@ -1,5 +1,6 @@ #include "terrain.h" #include "compound.h" +#include "river.h" #ifndef TERRAIN_CHUNK_H #define TERRAIN_CHUNK_H @@ -9,6 +10,9 @@ #define CHUNK_HALF 8.0 #define CHUNK_TILE_COUNT 16 +struct World; // 完整定义见 world.h + +// 地表/生物群系。新值一律追加在 ICE 之后,避免改动已有数值。 enum Surface_Type { SURFACE_BARE_ROCK = 0, SURFACE_SOIL, @@ -18,6 +22,11 @@ enum Surface_Type { SURFACE_WATER, SURFACE_SNOW, SURFACE_ICE, + SURFACE_TUNDRA, + SURFACE_TAIGA, + SURFACE_SAVANNA, + SURFACE_SHRUB, + SURFACE_SWAMP, SURFACE_COUNT }; @@ -43,6 +52,16 @@ struct Tile { uint8_t soil_type; uint8_t rock_type; uint8_t _pad; + float seasonal_amplitude; // 年温差半幅 K + float precipitation; // 归一化降水 0..1 + float precip_mm; // 年降水 毫米/年 + float river_depth; // 所在河道的水深 m(0 = 不在河上) + float navigable_draft; // 枯水期能通过的最大吃水 m(3m 富余 15%) + float water_depth; // 湖泊/河道水深 m,0 = 露出水面 + float water_temp; // 水温 ℃ + float ice_thick; // 冰厚 m(Stefan 定律;海冰用经验阈值) + float sed_conc; // 含沙量 kg/m^3 + float jam_risk; // 凌汛(冰坝)风险 0..1 // 归一化化合物组分,sum ≈ 1.0,索引见 Compound_Id float compound[COMPOUND_COUNT]; }; @@ -52,13 +71,56 @@ struct Chunk { struct Tile tiles[CHUNK_TILE_COUNT][CHUNK_TILE_COUNT]; }; -struct Chunk *chunk_generate(int cx, int cy, uint64_t seed, - struct World_Block *blocks, - struct Plate_list plates); +// 采样世界任意一点的"地质 + 地形 + 气候 + 地表",但不算 104 种化合物(便宜)。 +// slope / aspect / water_depth 都由本函数写入,调用方 memset 清零即可。 +void terrain_sample(struct Tile *t, double wx, double wy, const struct World *w); + +// 带精度档位的采样。lod = 0 是完整精度(米级细节 + 20m 基线坡度)—— +// 1 格 = 1 米的地面视图必须用这个。lod > 0 是**地图**用的降精度版: +// 丢掉 60/15/4m 三层细节,坡度改用起伏半幅估算,地形/气候/岩石/地表 +// 判据都不变(只是不再解析亚像素结构),单点采样快 3 倍左右。 +void terrain_sample_lod(struct Tile *t, double wx, double wy, + const struct World *w, int lod); + +// 构造基准地形(板块 + 分形起伏),不含河流改造。河流层自己要用。 +double terrain_base_elevation(double wx, double wy, const struct World *w); + +// 同上的降精度版(见 terrain_sample_lod) +double terrain_base_elevation_lod(double wx, double wy, + const struct World *w, int lod); + +// 局部起伏半幅(米)。泥沙层用它反推坡面坡度——40km 网格上的"坡面 +// 坡度"没有意义,但起伏幅度有,而且它才是产沙的真正驱动。 +double terrain_relief_amplitude(double wx, double wy, const struct World *w); + +// 同上,但去掉水文网格(40km)分辨不出来的高频起伏。河流层必须用这个, +// 否则会把亚网格噪声当成真实地形,到处挖出假洼地。 +double terrain_base_elevation_coarse(double wx, double wy, const struct World *w); + +// 植被潜力 0..1:低温、缺水各自限制,陡坡和极端大陆性再打折。 +// classify_surface 和河流层共用同一套判据,避免两处漂移。 +double vegetation_potential(double temperature, double moisture, + double seasonal_amplitude, double slope); + +// 带时间的采样:地形 / 岩石 / 化合物仍然只算一次(它们不随天气变), +// 但气候量换成**瞬时值**——季节、昼夜、季风、台风。 +// t_seconds < 0 时等价于 terrain_sample。 +void terrain_sample_at(struct Tile *t, double wx, double wy, + const struct World *w, double t_seconds); + +// 在 terrain_sample 基础上继续算化合物组分(贵,约 30 倍)。 +void tile_sample(struct Tile *t, double wx, double wy, const struct World *w); + +// 同 tile_sample,但显式指定化合物参数(默认用 w->settings)。 +void tile_sample_with(struct Tile *t, double wx, double wy, + const struct World *w, + const struct Compound_Settings *settings); + +struct Chunk *chunk_generate(int cx, int cy, const struct World *w); void chunk_free(struct Chunk *c); struct Vector2_double chunk_origin(int cx, int cy); struct Vector2_double tile_world_pos(int cx, int cy, int tx, int ty); -#endif \ No newline at end of file +#endif diff --git a/src/climate.c b/src/climate.c new file mode 100644 index 0000000..e6bf8ee --- /dev/null +++ b/src/climate.c @@ -0,0 +1,522 @@ +#include "climate.h" +#include "noise.h" +#include "random.h" + +#include +#include +#include + +// =============================================================== +// 可调参数(改气候手感全在这里) +// =============================================================== + +#define CLIMATE_SWEEPS 120 +#define CLIMATE_SWEEP_EPS 1e-3 +#define ADVECT_OFFSET 1.00 // 上风采样回退多少块;1.0 = 纯迎风差分(扩散最小) + +// --- 蒸发 --- +#define EVAP_OCEAN 1.00 // 暖洋面在参考温度下的蒸发潜力 +#define EVAP_LAND 0.30 // 陆地受土壤水分限制;再高会让内陆自己"造雨" +#define EVAP_T_REF 30.0 // 参考温度:这里的饱和水汽压定为 1.0 +#define EVAP_T_MIN -5.0 // 低于此温度基本不蒸发 + +// --- 大气持水能力(Clausius-Clapeyron 的线性化) --- +#define SAT_REF 1.00 +#define SAT_T_REF 15.0 +#define SAT_T_SCALE 20.0 // 每升高 20K,饱和容量约 e 倍 + +// --- 降雨 --- +// 每个平流步(一块 ≈ 512km)冲掉多少水汽。基准值决定"水汽能走多远": +// ro=0.06 对应 e 折距离约 16 块 ≈ 8000km,和真实水汽停留时间(≈10 天)同量级。 +// 早先 RAIN_BASE=0.02 / RAIN_ORO=0.55 时,海洋降水只有 cap*0.02 而迎风坡 +// 高达 cap*0.57,两者差 27 倍——于是全球 98 分位落在海岸山脉上, +// 整个内陆被归一化成"沙漠"。地形项必须和基准项同量级。 +#define RAIN_BASE 0.060 // 每经过一块的基础冲刷(锋面/气旋) +#define RAIN_T_SCALE 25.0 // 暖空气降雨效率更高 +#define RAIN_ORO 0.22 // 每抬升 1km 的额外冲刷 +#define RAIN_CONV 0.120 // 赤道辐合带的对流降雨 +#define RAIN_CONV_T 24.0 +#define RAIN_STORM 0.090 // 中纬风暴轴的锋面降雨 + +// --- 环流结构 --- +// 这个模式是纯水平的,没有哈得来环流,所以"赤道多雨、副热带干旱" +// 必须显式写进去:否则水汽只沿纬向走,30° 的空气从没经过赤道, +// 永远不会变干,全球降水会糊成一条平滑的纬向带。 +#define ITCZ_WIDTH 8.0 // 赤道辐合带半宽(度) +#define STORM_LAT 52.0 // 中纬风暴轴中心 +#define STORM_WIDTH 11.0 +#define SUBTROPICAL_LAT 30.0 // 副热带高压中心 +#define SUBTROPICAL_WIDTH 9.0 +#define SUBTROPICAL_SINK 0.55 // 每块被下沉气流抽走的水汽比例(不计入降水) + +// --- 大陆度 / 季节 --- +#define CONTINENTALITY_L0 1500e3 // 大陆度衰减尺度(米) +#define SEASONAL_OCEAN 0.50 // 海洋热容大,年温差小 +#define SEASONAL_LAND 1.15 // 内陆极端;太大西伯利亚会到 70K 年较差 +#define TEMP_LAPSE 0.0065 // K/m +#define TEMP_CONT_DROP 3.0 // 内陆年均温额外降低的上限(K) + +// --- 降水标定 / 显示 --- +#define PRECIP_OCEAN_MEAN 1100.0 // 海洋块平均降水标定值(毫米/年) +#define PRECIP_DISPLAY_MIN 1500.0 // 配色参考值的下限 +#define PRECIP_DISPLAY_MAX 6000.0 // 配色参考值的上限 + +// --- 干旱指数 MI = P/PET --- +// MI 跨越两个数量级(0.05 的撒哈拉 ~ 4 的雨林),线性映射会把生物群系 +// 全挤在中间,所以按对数分档。PET 本身见 climate_pet_mm()。 +#define ARIDITY_MIN 0.05 +#define ARIDITY_MAX 4.0 + +// 陆地蒸发再循环的强度:land_wet=0.5(默认)时倍率正好是 1.0, +// 所以不给反馈时的气候和以前完全一致。 +#define LAND_WET_BIAS 0.4 +#define LAND_WET_GAIN 1.2 + + +#ifndef DEG2RAD +#define DEG2RAD 0.017453292519943295 +#endif + +// =============================================================== +// 基础工具 +// =============================================================== + +double climate_latitude(double wy) { + // 注意不能用 WORLD_H*0.5 当极半径:那会让纬度在半个世界内就从 0 掉到 -90, + // 下半张地图全跑到极区以外,整片变成冰原。 + return 90.0 - (wy / (double)WORLD_H) * 180.0; +} + +double climate_pet_mm(double temperature) { + double pet = CLIMATE_PET_REF_MM * exp(temperature / CLIMATE_PET_T_SCALE); + return pet < 20.0 ? 20.0 : pet; +} + +double climate_runoff_mm(double precip_mm, double temperature) { + if (precip_mm <= 0.0) return 0.0; + double pet = climate_pet_mm(temperature); + double x = pet / precip_mm; // 干燥度 + double r = precip_mm * (1.0 - x * tanh(1.0 / x)); + return r > 0.0 ? r : 0.0; +} + +static double clampd(double x, double lo, double hi) { + return x < lo ? lo : (x > hi ? hi : x); +} + +static double climate_smoothstep(double t) { + t = clampd(t, 0.0, 1.0); + return t * t * (3.0 - 2.0 * t); +} + +// 年均温:以 cos(纬度) 近似太阳辐射,再叠海拔递减率。 +// 海洋点的 elevation 为负,要夹到 0——否则海底会按递减率被"加热", +// 算出来的不是海表温度。 +static double base_temperature(double lat, double elevation) { + double T = 28.0 - 55.0 * (1.0 - cos(lat * DEG2RAD)); + double e = elevation > 0.0 ? elevation : 0.0; + return T - e * TEMP_LAPSE; +} + +// 行星风带,按纬度平滑过渡(避免 30°/60° 出现硬边): +// 0–30° 信风:吹向西(东风),同时向赤道辐合 +// 30–60° 西风:吹向东,同时向极 +// 60–90° 极地东风:吹向西(东风),同时向赤道 +// +// 注意坐标系:+y 是**向南**(wy 越大纬度越低)。所有经向分量都按这个约定。 +// 这套纬向+经向的带结构本身就是科里奥利力 + 角动量守恒的产物——信风 +// 之所以是东北风/东南风而不是正北/正南风,就是地转偏向把向赤道的气流 +// 向右(北半球)/向左(南半球)压出来的。所以这里直接给出**近地面**的 +// 实测风向,不再二次偏转(那会重复计入)。 +static void wind_at_lat(double lat, double *wx, double *wy) { + double a = fabs(lat); + double s = (lat >= 0.0) ? 1.0 : -1.0; + + double t1 = climate_smoothstep((a - 22.0) / 16.0); + double t2 = climate_smoothstep((a - 52.0) / 16.0); + + double zonal = -1.0 * (1.0 - t1) + 1.0 * t1 * (1.0 - t2) + (-1.0) * t2; + // 经向:+1 = 向南(北半球向赤道)。信风向赤道、西风向极、极地东风向赤道。 + double merid = s * (1.0 - t1) + (-s) * t1 * (1.0 - t2) + s * t2; + + double len = sqrt(zonal * zonal + merid * merid); + if (len < 1e-9) { *wx = -1.0; *wy = 0.0; return; } + *wx = zonal / len; + *wy = merid / len; +} + +// =============================================================== +// 双线性采样(x 环绕、y 夹紧) +// =============================================================== + +static double block_blend_t(double t) { + return t * t * (3.0 - 2.0 * t); +} + +static double field_at(const float *f, double wx, double wy) { + double bx = wx / (double)WORLD_BLOCK_SIZE - 0.5; + double by = wy / (double)WORLD_BLOCK_SIZE - 0.5; + int ix = (int)floor(bx); + int iy = (int)floor(by); + // 用 smoothstep 而不是线性权重:线性插值只有 C0 连续,梯度会在 512km + // 的块边界上跳变,大陆度(进而温度/海冰线)会显出一张方格网。 + double fx = block_blend_t(bx - ix); + double fy = block_blend_t(by - iy); + + int x0 = wrap_block_x(ix), x1 = wrap_block_x(ix + 1); + int y0 = wrap_block_y(iy), y1 = wrap_block_y(iy + 1); + int cx = (int)WORLD_BLOCK_COUNT_X; + + double a = f[y0 * cx + x0] * (1.0 - fx) + f[y0 * cx + x1] * fx; + double b = f[y1 * cx + x0] * (1.0 - fx) + f[y1 * cx + x1] * fx; + return a * (1.0 - fy) + b * fy; +} + +// =============================================================== +// 到最近海洋块的距离(两遍 chamfer 距离变换) +// =============================================================== + +static void build_ocean_dist(float *dist, struct World_Block *blocks) { + const int CX = (int)WORLD_BLOCK_COUNT_X; + const int CY = (int)WORLD_BLOCK_COUNT_Y; + const float DIAG = 1.41421356f; + const float INF = 1e9f; + + for (int i = 0; i < CX * CY; i++) + dist[i] = (blocks[i].elevation < 0.0) ? 0.0f : INF; + + // 前向 + for (int j = 0; j < CY; j++) { + for (int k = 0; k < CX; k++) { + int idx = j * CX + k; + float d = dist[idx]; + int km = wrap_block_x(k - 1), kp = wrap_block_x(k + 1); + if (j > 0) { + float u = dist[(j - 1) * CX + k]; + if (u + 1.0f < d) d = u + 1.0f; + u = dist[(j - 1) * CX + km]; + if (u + DIAG < d) d = u + DIAG; + u = dist[(j - 1) * CX + kp]; + if (u + DIAG < d) d = u + DIAG; + } + float l = dist[j * CX + km]; + if (l + 1.0f < d) d = l + 1.0f; + dist[idx] = d; + } + } + + // 后向 + for (int j = CY - 1; j >= 0; j--) { + for (int k = CX - 1; k >= 0; k--) { + int idx = j * CX + k; + float d = dist[idx]; + int km = wrap_block_x(k - 1), kp = wrap_block_x(k + 1); + if (j < CY - 1) { + float u = dist[(j + 1) * CX + k]; + if (u + 1.0f < d) d = u + 1.0f; + u = dist[(j + 1) * CX + km]; + if (u + DIAG < d) d = u + DIAG; + u = dist[(j + 1) * CX + kp]; + if (u + DIAG < d) d = u + DIAG; + } + float r = dist[j * CX + kp]; + if (r + 1.0f < d) d = r + 1.0f; + dist[idx] = d; + } + } + + for (int i = 0; i < CX * CY; i++) { + float d = dist[i]; + dist[i] = (d >= INF * 0.5f) ? (float)WORLD_W : d * (float)WORLD_BLOCK_SIZE; + } +} + +// 直方图求分位数,用来把降水场归一化到 0..1 +static double percentile(const double *v, int n, double p) { + double mn = v[0], mx = v[0]; + for (int i = 1; i < n; i++) { + if (v[i] < mn) mn = v[i]; + if (v[i] > mx) mx = v[i]; + } + if (mx - mn < 1e-12) return mx; + + enum { BINS = 512 }; + static int hist[BINS]; + memset(hist, 0, sizeof(hist)); + + for (int i = 0; i < n; i++) { + int b = (int)((v[i] - mn) / (mx - mn) * BINS); + if (b < 0) b = 0; + if (b >= BINS) b = BINS - 1; + hist[b]++; + } + int target = (int)(p * n), acc = 0; + for (int b = 0; b < BINS; b++) { + acc += hist[b]; + if (acc >= target) return mn + ((double)b + 0.5) * (mx - mn) / BINS; + } + return mx; +} + +// =============================================================== +// 水汽平流求解 +// =============================================================== +// W[b] = E[b] + W[上风] * (1 - 冲刷率) +// 降水[b] = W[上风] * 冲刷率 +// +// 上风块由该纬度带的行星风决定;风向是纯纬向+经向的带结构, +// 所以沿风向反复扫掠就能收敛(高斯-赛德尔)。 +// 温度决定空气的饱和容量(暖空气能带更多水),蒸发只在暖洋面显著。 +// 抬升(地形)和对流(高温)决定冲刷率——这自然给出迎风坡多雨、 +// 背风坡雨影、内陆干旱、副热带干燥。 + +void climate_field_build(struct Climate_Field *cf, uint64_t seed, + struct World_Block *blocks, struct Plate_list plates) { + (void)plates; + const int CX = (int)WORLD_BLOCK_COUNT_X; + const int CY = (int)WORLD_BLOCK_COUNT_Y; + const int N = CX * CY; + + // 河流层会反复重算气候场,所以必须先把上一轮释放掉,否则每次迭代漏 50KB。 + free(cf->precip); cf->precip = NULL; + free(cf->ocean_dist); cf->ocean_dist = NULL; + + cf->precip = calloc(N, sizeof(float)); + cf->ocean_dist = malloc(sizeof(float) * N); + if (cf->precip == NULL || cf->ocean_dist == NULL) { + climate_field_free(cf); + return; + } + + // land_wet 由气候层持有并跨重算保留(河流层每轮往里写) + if (cf->land_wet == NULL) { + cf->land_wet = malloc(sizeof(float) * N); + if (cf->land_wet != NULL) + for (int i = 0; i < N; i++) cf->land_wet[i] = 0.5f; + } + + build_ocean_dist(cf->ocean_dist, blocks); + + // ---- 逐块的温度、蒸发潜力、饱和容量 ---- + double *W = calloc(N, sizeof(double)); // 大气含水量 + double *E = malloc(sizeof(double) * N); // 蒸发 + double *cap = malloc(sizeof(double) * N); // 饱和容量 + double *elev = malloc(sizeof(double) * N); + if (!W || !E || !cap || !elev) { + free(W); free(E); free(cap); free(elev); + climate_field_free(cf); + return; + } + + for (int j = 0; j < CY; j++) { + double lat = climate_latitude(((double)j + 0.5) * WORLD_BLOCK_SIZE); + for (int k = 0; k < CX; k++) { + int idx = j * CX + k; + double e = blocks[idx].elevation; + elev[idx] = e; + + double T = base_temperature(lat, e); + // 蒸发潜力按**饱和水汽压**走(Clausius-Clapeyron),而不是温度 + // 的线性函数:-5℃ 的饱和水汽压只有 30℃ 的 1/10,线性插值会 + // 把极地海洋的蒸发量高估十几倍,整个极地会变成多雨区。 + // 蒸发潜力:温度线性斜坡,-5℃ 以下截零。 + // + // 试过改成物理上更正确的 Clausius-Clapeyron(e_s(T)/e_s(30℃), + // 指数尺度 13.5K),结果是极地降水从 0 涨到 37mm,但副热带和 + // 热带的降水被海洋均值归一化挤掉两成(赤道 1714→1388mm, + // 赤道径流 774→563mm),中纬反而更干。原因是这个模式的极地 + // 干燥不是"蒸发太少"造成的,而是**单层水平水汽模式**的固有限制: + // 空气的饱和容量跟着**当地**温度走,气团向极走一路降温、水汽 + // 一路被榨干,到极地已经是干空气。要修得加一层中高层水汽 + + // 涡动扩散通量(中纬气旋往极地输送水汽),那是另一个量级的改动。 + // 所以这里保留原来的标定值,把"极地降水偏少"记为已知限制。 + double warm = clampd((T - EVAP_T_MIN) / (EVAP_T_REF - EVAP_T_MIN), 0.0, 1.0); + + // 陆地蒸发受水分可得性限制:有河、有湖、有湿润植被的地方 + // 蒸发强,下风方向降水就多。海洋不受这个约束。 + double wet = 1.0; + if (e >= 0.0 && cf->land_wet != NULL) { + wet = LAND_WET_BIAS + LAND_WET_GAIN * clampd(cf->land_wet[idx], 0.0, 1.0); + } + E[idx] = (e < 0.0 ? EVAP_OCEAN : EVAP_LAND * wet) * warm; + cap[idx] = SAT_REF * exp((T - SAT_T_REF) / SAT_T_SCALE); + if (cap[idx] < 0.05) cap[idx] = 0.05; + } + } + + // ---- 扫掠求解 ---- + double *rain = calloc(N, sizeof(double)); + if (rain == NULL) { + free(W); free(E); free(cap); free(elev); + climate_field_free(cf); + return; + } + + for (int sweep = 0; sweep < CLIMATE_SWEEPS; sweep++) { + double max_delta = 0.0; + + for (int j = 0; j < CY; j++) { + double lat = climate_latitude(((double)j + 0.5) * WORLD_BLOCK_SIZE); + double wvx, wvy; + wind_at_lat(lat, &wvx, &wvy); + + for (int k = 0; k < CX; k++) { + int idx = j * CX + k; + + // 沿风的来向回退 ADVECT_OFFSET 块,双线性取上风值 + double ux = (double)k - wvx * ADVECT_OFFSET; + double uy = (double)j - wvy * ADVECT_OFFSET; + int ix = (int)floor(ux), iy = (int)floor(uy); + double fx = ux - ix, fy = uy - iy; + int x0 = wrap_block_x(ix), x1 = wrap_block_x(ix + 1); + int y0 = wrap_block_y(iy), y1 = wrap_block_y(iy + 1); + + double w_up = W[y0 * CX + x0] * (1 - fx) * (1 - fy) + + W[y0 * CX + x1] * fx * (1 - fy) + + W[y1 * CX + x0] * (1 - fx) * fy + + W[y1 * CX + x1] * fx * fy; + + double e_up = elev[y0 * CX + x0] * (1 - fx) * (1 - fy) + + elev[y0 * CX + x1] * fx * (1 - fy) + + elev[y1 * CX + x0] * (1 - fx) * fy + + elev[y1 * CX + x1] * fx * fy; + + double T = base_temperature(lat, elev[idx]); + + // 环流结构:赤道辐合带、中纬风暴轴、副热带高压 + double al = fabs(lat); + double dst = al - STORM_LAT; + double storm = exp(-(dst * dst) / (2.0 * STORM_WIDTH * STORM_WIDTH)); + double itcz = exp(-(lat * lat) / (2.0 * ITCZ_WIDTH * ITCZ_WIDTH)); + double dsb = al - SUBTROPICAL_LAT; + double sthz = exp(-(dsb * dsb) / (2.0 * SUBTROPICAL_WIDTH * SUBTROPICAL_WIDTH)); + + // 冲刷率:基础(锋面)+ 地形抬升 + 赤道对流 + 中纬风暴 + // 对流/风暴项按饱和度缩放:空气本来就干的地方刮不出雨 + double sat = clampd(w_up / cap[idx], 0.0, 1.0); + double lift = elev[idx] - e_up; + double ro = RAIN_BASE * exp((T - SAT_T_REF) / RAIN_T_SCALE) + + RAIN_ORO * (lift > 0.0 ? lift : 0.0) / 1000.0 + + RAIN_CONV * itcz * sat + + RAIN_STORM * storm * sat; + ro = clampd(ro, 0.0, 0.90); + + double w_new = E[idx] + w_up * (1.0 - ro); + + // 副热带高压的下沉气流把水汽抽向高层——这部分既不下落成雨, + // 也不留在近地面,所以是纯粹的汇。这是纯水平模式里唯一能 + // 造出"副热带沙漠"的机制:贸易风进入这一带后迅速变干。 + w_new -= SUBTROPICAL_SINK * sthz * w_new; + + // 过饱和部分当场成雨,而不是凭空消失 + if (w_new > cap[idx]) { + rain[idx] = w_up * ro + (w_new - cap[idx]); + w_new = cap[idx]; + } else { + rain[idx] = w_up * ro; + } + if (w_new < 0.0) w_new = 0.0; + + double d = fabs(w_new - W[idx]); + if (d > max_delta) max_delta = d; + + W[idx] = w_new; + } + } + if (max_delta < CLIMATE_SWEEP_EPS) break; + } + + // ---- 标定成物理单位 ---- + // 相对场只定了形状,绝对量级是任意的(E 和 cap 都以 SAT_REF 为单位)。 + // 用"海洋块平均降水"把它锚定到 1100 mm/年,这样干旱指数 P/PET 才有意义。 + double sum_ocean = 0.0; + int n_ocean = 0; + for (int i = 0; i < N; i++) { + if (blocks[i].elevation < 0.0) { sum_ocean += rain[i]; n_ocean++; } + } + double mean_ocean = (n_ocean > 0) ? sum_ocean / n_ocean : 1.0; + double mm_scale = (mean_ocean > 1e-9) ? (PRECIP_OCEAN_MEAN / mean_ocean) : 1.0; + + for (int i = 0; i < N; i++) + cf->precip[i] = (float)(rain[i] * mm_scale); + + cf->precip_p98 = (float)(percentile(rain, N, 0.98) * mm_scale); + if (!(cf->precip_p98 > PRECIP_DISPLAY_MIN)) cf->precip_p98 = (float)PRECIP_DISPLAY_MIN; + if (cf->precip_p98 > PRECIP_DISPLAY_MAX) cf->precip_p98 = (float)PRECIP_DISPLAY_MAX; + + free(W); free(E); free(cap); free(elev); free(rain); +} + +void climate_field_free(struct Climate_Field *cf) { + if (cf == NULL) return; + free(cf->precip); + free(cf->ocean_dist); + free(cf->land_wet); + cf->precip = NULL; + cf->ocean_dist = NULL; + cf->land_wet = NULL; +} + +double climate_precip_at(const struct Climate_Field *cf, double wx, double wy) { + if (cf == NULL || cf->precip == NULL) return 0.0; + return field_at(cf->precip, wx, wy); +} + +double climate_ocean_dist_at(const struct Climate_Field *cf, double wx, double wy) { + if (cf == NULL || cf->ocean_dist == NULL) return 0.0; + return field_at(cf->ocean_dist, wx, wy); +} + +// =============================================================== +// 逐点采样 +// =============================================================== + +void climate_sample(const struct Climate_Field *cf, uint64_t seed, + double wx, double wy, double elevation, + struct Climate_Sample *out) { + double lat = climate_latitude(wy); + + // ---- 温度 ---- + double T = base_temperature(lat, elevation); + + // 大陆度:离海越远的年均温越低(冬季降温幅度大于夏季升温) + double ocean_m = field_at(cf->ocean_dist, wx, wy); + double cont = ocean_m / (ocean_m + CONTINENTALITY_L0); + double lat_w = clampd((fabs(lat) - 30.0) / 40.0, 0.0, 1.0); + T -= cont * TEMP_CONT_DROP * lat_w; + + // ---- 季节振幅:海洋被热容调制,内陆极端 --- + // 用 (1-cos lat) 的 0.70 次幂而不是线性:线性的在副热带偏小、在极地偏大。 + // 标定目标是大陆内部的年较差半幅:20N 约 6K、30N 约 10K、45N 约 15K、 + // 60N 约 20K(北京 15.5K、哈尔滨 21K)。这组数决定了季风的强度。 + double amp_base = 3.0 + 26.0 * pow(1.0 - cos(lat * DEG2RAD), 0.70); + double amp = amp_base * (SEASONAL_OCEAN + (SEASONAL_LAND - SEASONAL_OCEAN) * cont); + + // ---- 降水(毫米/年)---- + double P = field_at(cf->precip, wx, wy); + + // 局地尺度扰动:让降水不是纯粹的大尺度平滑场。 + // 特征尺度要明显大于全球视图的一个像素(≈45km),否则生物群系阈值 + // 会在像素之间反复穿越,整张地图变成椒盐噪点。 + double n = fractal_noise(seed, CHUNK_NOISE_MOIST, wx, wy, 12000.0, 3, 0.5); + P *= (0.88 + 0.24 * n); + if (P < 0.0) P = 0.0; + + // ---- 干旱指数 ---- + // 潜在蒸散:温度决定"空气有多渴"。同样 500mm 降水,在赤道是荒漠, + // 在 0℃ 的高纬足够长针叶林——只看降水量的分类器做不到这件事。 + double pet = climate_pet_mm(T); + double mi = P / pet; + if (mi < 1e-6) mi = 1e-6; + + // 对数分档:生物群系的阈值在 MI 上是对数等距的 + double M = (log(mi) - log(ARIDITY_MIN)) / (log(ARIDITY_MAX) - log(ARIDITY_MIN)); + M = clampd(M, 0.0, 1.0); + + out->temperature = T; + out->seasonal_amplitude = amp; + out->moisture = M; + out->precip_mm = P; + out->precipitation = clampd(P / (double)cf->precip_p98, 0.0, 1.0); + wind_at_lat(lat, &out->wind_x, &out->wind_y); +} diff --git a/src/climate.h b/src/climate.h new file mode 100644 index 0000000..5a56d5c --- /dev/null +++ b/src/climate.h @@ -0,0 +1,76 @@ +#ifndef CLIMATE_H +#define CLIMATE_H + +#include +#include "terrain.h" + +// =============================================================== +// 气候场 +// =============================================================== +// 温度是逐点可算的(纬度 + 海拔 + 大陆度),但降水不行: +// 水汽要被风带着走,沿途蒸发、抬升、降雨,这是个沿风向的输运过程, +// 必须先在全球尺度上解一次。所以分成两层: +// +// climate_field_build() 世界创建时跑一次,在 World_Block 网格(80x80)上 +// 做沿岸上风平流 + 地形/对流降雨,得到降水场 +// climate_sample() 任意点采样,查表插值 + 局部噪声,很便宜 +// +// 逐点的温度/风带/季节振幅也在 climate_sample 里算。 +// --------------------------------------------------------------- + +struct Climate_Field { + float *precip; // 年降水,毫米/年(World_Block 分辨率) + float *ocean_dist; // 到最近海洋块的距离(米),用于大陆度 + float precip_p98; // 全球降水的 98 分位(毫米/年),只用于显示归一化 + // 陆地蒸发的水分可得性 0..1,由河流层写入(见 river.c 的 climate_feedback)。 + // 水面/湿润植被越多,陆地蒸发越强,下风方向降水也就越多—— + // 这就是水汽再循环,亚马逊约 40% 的降水来自它。NULL = 处处均匀。 + float *land_wet; +}; + +// 降水与"可供植物利用的水分"是两件事,分开存: +// precipitation 是雨量本身(0..1,按全球 98 分位归一化,给地图配色用) +// moisture 是干旱指数 MI = P/PET 映射到 0..1(给生物群系用) +// 否则热带雨林和寒带针叶林会得到同一个 M 值——前者雨多但蒸发也强, +// 后者雨少但几乎不蒸发,两者对植被其实同样"湿润"。 +struct Climate_Sample { + double temperature; // 年均温 ℃ + double seasonal_amplitude; // 年温差半幅 K + double moisture; // 干旱指数映射 0..1(供生物群系使用) + double precipitation; // 归一化降水 0..1(显示用) + double precip_mm; // 年降水 毫米/年(诊断用) + double wind_x, wind_y; // 归一化盛行风向(风吹向的方向) +}; + +// 世界创建时调用一次(必须在 plate_init 之后,因为要用到高程) +void climate_field_build(struct Climate_Field *cf, uint64_t seed, + struct World_Block *blocks, struct Plate_list plates); +void climate_field_free(struct Climate_Field *cf); + +// 世界 y 轴从北极端 (0) 到南极端 (WORLD_H),赤道在正中 +double climate_latitude(double wy); + +// 潜在蒸散(毫米/年)。只跟温度有关:0℃ 约 200mm,20℃ 约 1050mm,30℃ 约 2450mm, +// 和 Thornthwaite 的量级一致。降水减掉它就是年径流深,河流层要用。 +#define CLIMATE_PET_REF_MM 200.0 +#define CLIMATE_PET_T_SCALE 12.0 +double climate_pet_mm(double temperature); + +// 年径流深(毫米/年),Budyko 水量平衡: +// R = P * (1 - (PET/P) * tanh(P/PET)) +// 比"P 减 PET,负数截零"真实得多——后者在 P 略小于 PET 的地方会突然 +// 掉到 0,于是整个热带陆地一滴水都流不出来(PET 1150 > P 1100), +// 河流层会退化成一堆干河床。Budyko 是平滑过渡的。 +double climate_runoff_mm(double precip_mm, double temperature); + +// 在降水场上取一点(毫米/年)。天气层要按太阳赤纬整体平移这张场, +// 所以必须能单独取降水而不触发整套气候采样。 +double climate_precip_at(const struct Climate_Field *cf, double wx, double wy); +double climate_ocean_dist_at(const struct Climate_Field *cf, double wx, double wy); + +// 采样某点气候。elevation 传该点的地形高程(米,海洋为负)。 +void climate_sample(const struct Climate_Field *cf, uint64_t seed, + double wx, double wy, double elevation, + struct Climate_Sample *out); + +#endif diff --git a/src/compound.c b/src/compound.c index 05ad299..20b53fc 100644 --- a/src/compound.c +++ b/src/compound.c @@ -5,72 +5,7 @@ #include "noise.h" #include -// ================================================================ -// 板块属性空间混合 -// ================================================================ -// 板块分配是 512km 的 World_Block 级别离散值,直接在边界硬切换会产生 -// 视觉硬缝。这里用高斯核对附近 World_Block 的板块属性做加权平均。 -// sigma 取 0.7 个 World_Block,过渡带约 ±500km,看起来是自然的渐变。 - -#define PLATE_BLEND_RADIUS 2 -#define PLATE_BLEND_SIGMA (WORLD_BLOCK_SIZE * 0.2) - -void plate_blend_at(struct World_Block *blocks, - struct Plate_list plates, - double wx, double wy, - struct Plate_Blend *out) { - int cx = (int)floor(wx / (double)WORLD_BLOCK_SIZE); - int cy = (int)floor(wy / (double)WORLD_BLOCK_SIZE); - - const double sigma2 = PLATE_BLEND_SIGMA * PLATE_BLEND_SIGMA; - const double inv_2s2 = 1.0 / (2.0 * sigma2); - - double total = 0.0; - double sum_oc = 0.0; - double sum_age = 0.0; - double sum_thk = 0.0; - double sum_sx = 0.0; - double sum_sy = 0.0; - - for (int dy = -PLATE_BLEND_RADIUS; dy <= PLATE_BLEND_RADIUS; dy++) { - for (int dx = -PLATE_BLEND_RADIUS; dx <= PLATE_BLEND_RADIUS; dx++) { - int bx = wrap_block_x(cx + dx); - int by = wrap_block_y(cy + dy); - int bi = by * WORLD_BLOCK_COUNT_X + bx; - - double bxc = ((double)bx + 0.5) * WORLD_BLOCK_SIZE; - double byc = ((double)by + 0.5) * WORLD_BLOCK_SIZE; - - double ddx = bxc - wx; - if (ddx > WORLD_W * 0.5) ddx -= WORLD_W; - if (ddx < -WORLD_W * 0.5) ddx += WORLD_W; - double ddy = byc - wy; - - double w = exp(-(ddx*ddx + ddy*ddy) * inv_2s2); - - int pid = blocks[bi].plate_id; - struct Plate *p = plates._p + pid; - - sum_oc += w * (p->is_ocean ? 1.0 : 0.0); - sum_age += w * (double)p->age; - sum_thk += w * p->thick; - sum_sx += w * p->speed.x; - sum_sy += w * p->speed.y; - total += w; - } - } - - if (total < 1e-12) { - out->is_ocean = 0; out->age = 0; out->thick = 0; - out->speed_x = 0; out->speed_y = 0; - return; - } - out->is_ocean = sum_oc / total; - out->age = sum_age / total; - out->thick = sum_thk / total; - out->speed_x = sum_sx / total; - out->speed_y = sum_sy / total; -} +// 板块属性混合已下沉到 terrain.c(plate_blend_at),它对板块/高程也要用。 // ================================================================ // 岩石类型权重(连续) @@ -79,6 +14,12 @@ void plate_blend_at(struct World_Block *blocks, static double clamp01(double x) { return x < 0.0 ? 0.0 : (x > 1.0 ? 1.0 : x); } + +// 造岩端元:QUARTZ..ANHYDRITE 这一段是硅酸盐/氧化物/碳酸盐/蒸发岩/黏土。 +// 它们构成岩石本身,不该被"矿物丰度"选项整体放大。 +bool compound_is_rock_forming(enum Compound_Id c) { + return c >= CP_QUARTZ && c <= CP_ANHYDRITE; +} static double smooth01(double x) { x = clamp01(x); return x * x * (3.0 - 2.0 * x); @@ -551,7 +492,9 @@ const struct Compound_Settings COMPOUND_SETTINGS_DEFAULT = { 1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0, // 非金属/宝石 13 1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0 - } + }, + .threshold_shift = 0.0, + .geology_gamma = 1.0 }; // --------------------------------------------------------------- @@ -585,12 +528,17 @@ void tile_generate_compounds(struct Tile *t, double w[COMPOUND_COUNT]; double sum = 0.0; + // geology_gamma 合法值必须 > 0;非法值按"不干预"处理 + double gamma = settings->geology_gamma; + if (!(gamma > 0.0)) gamma = 1.0; + bool use_gamma = (gamma != 1.0); + for (int c = 0; c < COMPOUND_COUNT; c++) { const struct Compound_Params *p = &CP_PARAMS[c]; double n = fractal_noise(seed, CHUNK_NOISE_MINERAL_BASE + c, wx, wy, p->scale, p->octaves, p->persistence); - double v = n - p->threshold; + double v = n - (p->threshold + settings->threshold_shift); if (v < 0.0) v = 0.0; v *= p->abundance * settings->abundance[c]; @@ -599,6 +547,9 @@ void tile_generate_compounds(struct Tile *t, v *= environment_multiplier((enum Compound_Id)c, t->elevation, t->temperature, t->moisture); + // gamma < 1 把分布压平(处处都有矿),> 1 让地质约束更尖锐(贫富分化) + if (use_gamma) v = pow(v, gamma); + w[c] = v; sum += v; } diff --git a/src/compound.h b/src/compound.h index e06736e..3a479b5 100644 --- a/src/compound.h +++ b/src/compound.h @@ -2,6 +2,7 @@ #define TERRAIN_COMPOUND_H #include +#include #include "terrain.h" // --------------------------------------------------------------- @@ -143,29 +144,19 @@ enum Compound_Id { }; struct Compound_Settings { - double abundance[COMPOUND_COUNT]; + double abundance[COMPOUND_COUNT]; // 每种化合物的世界丰度倍率 + double threshold_shift; // 叠加到 CP_PARAMS.threshold:>0 矿更稀有 + double geology_gamma; // 地质乘数的幂次:<1 削弱地质约束,>1 强化 }; +// 造岩矿物(含碳酸盐/蒸发岩/黏土)不参与 ore_abundance 的倍率 +bool compound_is_rock_forming(enum Compound_Id c); + extern const struct Compound_Settings COMPOUND_SETTINGS_DEFAULT; struct Tile; struct Plate; -// ---- 新增:连续化的板块属性 ---- -struct Plate_Blend { - double is_ocean; // 0 = 全陆地,1 = 全海洋,中间是过渡 - double age; - double thick; - double speed_x, speed_y; -}; - -// 在 (wx, wy) 处用高斯核对附近 World_Block 的板块属性做空间混合 -void plate_blend_at(struct World_Block *blocks, - struct Plate_list plates, - double wx, double wy, - struct Plate_Blend *out); - -// 根据混合板块属性 + 岩石噪声,输出 7 种岩石类型的连续权重(和为 1) void rock_weights_blend(const struct Plate_Blend *pb, double rock_n, double out_w[ROCK_COUNT]); diff --git a/src/game.c b/src/game.c new file mode 100644 index 0000000..58bb0ff --- /dev/null +++ b/src/game.c @@ -0,0 +1,1225 @@ +#include "game.h" +#include "chunk.h" +#include "hydro.h" +#include "astro.h" +#include "weather.h" +#include "climate.h" +#include "river.h" +#include "noise.h" +#include "random.h" + +#include +#include +#include +#include + +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif +#define G_D2R (M_PI / 180.0) +#define G_R2D (180.0 / M_PI) + +// =============================================================== +// 参数 +// =============================================================== + +// ---- 工程师 ---- +#define PLAYER_WALK 2.6 // m/s,负重步行的量级 +#define PLAYER_RUN 5.2 +#define PLAYER_RADIUS 0.35 // m,碰撞半径 +#define WADE_MAX_DEPTH 0.70 // 超过这个水深走不动(要游) +#define SWIM_SPEED 0.9 +#define CLIMB_MAX_SLOPE 0.90 // 这个坡度以上爬不上去 +#define STAMINA_DRAIN 0.055 // 每秒(跑步) +#define STAMINA_REGEN 0.030 + + +// ---- 渲染 ---- +#define SHADE_MIN 0.68 +#define SHADE_MAX 1.30 +#define NIGHT_MIN 0.42 // 夜里最暗到这个亮度(有月光时更亮) +#define NIGHT_BLUE 0.10 // 夜间往蓝里偏多少(暗视觉偏蓝) + +// =============================================================== +// 地表配色(米级视角用,比世界地图更沉、更饱和) +// =============================================================== + +static struct Color surface_base(uint8_t s) { + switch (s) { + case SURFACE_BARE_ROCK: return (struct Color){139, 132, 125, 255}; + case SURFACE_SOIL: return (struct Color){112, 86, 60, 255}; + case SURFACE_SAND: return (struct Color){206, 186, 132, 255}; + case SURFACE_GRASS: return (struct Color){104, 140, 72, 255}; + case SURFACE_FOREST: return (struct Color){ 52, 92, 52, 255}; + case SURFACE_WATER: return (struct Color){ 46, 88, 132, 255}; + case SURFACE_SNOW: return (struct Color){238, 240, 246, 255}; + case SURFACE_ICE: return (struct Color){198, 224, 240, 255}; + case SURFACE_TUNDRA: return (struct Color){146, 143, 128, 255}; + case SURFACE_TAIGA: return (struct Color){ 44, 78, 64, 255}; + case SURFACE_SAVANNA: return (struct Color){176, 164, 96, 255}; + case SURFACE_SHRUB: return (struct Color){134, 132, 94, 255}; + case SURFACE_SWAMP: return (struct Color){ 66, 90, 74, 255}; + default: return (struct Color){255, 0, 255, 255}; + } +} + +static const char *surface_label(uint8_t s) { + switch (s) { + case SURFACE_BARE_ROCK: return "bare rock"; + case SURFACE_SOIL: return "soil"; + case SURFACE_SAND: return "sand"; + case SURFACE_GRASS: return "grass"; + case SURFACE_FOREST: return "forest"; + case SURFACE_WATER: return "water"; + case SURFACE_SNOW: return "snow"; + case SURFACE_ICE: return "ice"; + case SURFACE_TUNDRA: return "tundra"; + case SURFACE_TAIGA: return "taiga"; + case SURFACE_SAVANNA: return "savanna"; + case SURFACE_SHRUB: return "shrub"; + case SURFACE_SWAMP: return "swamp"; + default: return "?"; + } +} + +// 岩石基色:让地表带上地质味道(花岗岩偏肉红、玄武岩偏青黑、 +// 石灰岩偏白、砂岩偏黄)。只混一点点,不能盖过生物群系。 +static struct Color rock_tint(uint8_t r) { + switch (r) { + case ROCK_GRANITE: return (struct Color){146, 116, 108, 255}; + case ROCK_BASALT: return (struct Color){ 74, 76, 82, 255}; + case ROCK_LIMESTONE: return (struct Color){196, 194, 176, 255}; + case ROCK_SANDSTONE: return (struct Color){188, 152, 106, 255}; + case ROCK_SHALE: return (struct Color){ 96, 98, 100, 255}; + case ROCK_SCHIST: return (struct Color){104, 112, 116, 255}; + case ROCK_GNEISS: return (struct Color){130, 126, 132, 255}; + default: return (struct Color){128, 128, 128, 255}; + } +} + +static struct Color col_mul(struct Color c, double k) { + int r = (int)(c.r * k), g = (int)(c.g * k), b = (int)(c.b * k); + if (r < 0) r = 0; if (r > 255) r = 255; + if (g < 0) g = 0; if (g > 255) g = 255; + if (b < 0) b = 0; if (b > 255) b = 255; + return (struct Color){(unsigned char)r, (unsigned char)g, + (unsigned char)b, 255}; +} + +static struct Color col_lerp(struct Color a, struct Color b, double t) { + if (t < 0.0) t = 0.0; + if (t > 1.0) t = 1.0; + return (struct Color){ + (unsigned char)(a.r + (b.r - a.r) * t), + (unsigned char)(a.g + (b.g - a.g) * t), + (unsigned char)(a.b + (b.b - a.b) * t), 255}; +} + +// 无窗口时 GetTime() 不一定可用(headless 出图验证要用),所以包一层 +static double g_now(void) { + return IsWindowReady() ? (double)GetTime() : 0.0; +} + +static double gclamp(double x, double lo, double hi) { + return x < lo ? lo : (x > hi ? hi : x); +} + +// 体感温度(风寒指数):环境温度 ≤10℃ 且风速 >1.3 m/s 时有效,v 用 km/h。 +// 这是个**天气读数**,不是本体状态,所以留在 HUD 里显示。 +static double wind_chill_c(double T, double v_ms) { + double v = v_ms * 3.6; + if (T > 10.0 || v < 4.8) return T; + return 13.12 + 0.6215 * T - 11.37 * pow(v, 0.16) + + 0.3965 * T * pow(v, 0.16); +} + +// 每格的确定性扰动:让画面不是一片死板的纯色 +static double tile_variation(int gx, int gy, uint64_t seed, int salt) { + uint64_t h = game_hash(seed, 0x7A11E000u + (uint64_t)salt, + ((uint64_t)(uint32_t)gx << 32) | (uint32_t)gy); + return (double)(h >> 40) / 16777216.0; // 0..1 +} + +// =============================================================== +// 渲染分块 +// =============================================================== +// 存的是**不随时间变**的那部分(高程、坡度、地表、岩石、水深)。 +// 随时间变的量(气温、雪盖、冰、云、昼夜)走粗网格覆盖层,在绘制时叠加, +// 这样走一步不用把整个缓存重算一遍。 + +struct Game_Render_Tile { + float elev; + float shade; // 局部山体阴影亮度 + float water_depth; + float slope; + uint8_t surface; + uint8_t rock; + uint8_t soil; + uint8_t tone; // 烘焙好的色调扰动 0..255(每帧算噪声太贵) +}; + +struct Game_Render_Chunk { + int cx, cy; + bool valid; + uint32_t last_used; + struct Game_Render_Tile t[GAME_CHUNK_TILES][GAME_CHUNK_TILES]; +}; + +// 随时间变的天气覆盖层(粗网格) +struct Game_Overlay { + float temp; // 气温 ℃ + float snow; // 积雪覆盖率 0..1 + float ice; // 冰厚 m + float cloud; // 云量 0..1 + float precip; // 降水 mm/h + float light; // 环境光 0..1(昼夜) + float wind; // 风速 m/s +}; + +// =============================================================== +// 世界坐标 <-> 格 +// =============================================================== +// chunk_origin(cx,cy) = (cx*16-8, cy*16-8),格 (tx,ty) 中心在 origin+(tx+0.5,ty+0.5)。 +// 所以世界坐标 wx 落在的**全局格号**是 floor(wx + 8)。 + +static inline long g_tile_index(double w) { + return (long)floor(w + (double)CHUNK_HALF); +} + +// 采样点夹到世界范围内:两极的边界行不能采到 y<0 / y>=WORLD_H +static inline double g_clamp_y(double wy) { + double h = (double)WORLD_H; + if (wy < 0.5) wy = 0.5; + if (wy > h - 0.5) wy = h - 0.5; + return wy; +} + +// 视图左上角对应的世界坐标。 +// +// 必须用**连续的** 像素半宽/缩放,而不是"可见格数(取整)的一半"。 +// 后者会让视野宽度随缩放跳变:tile_px=12、屏宽 640 时 ntx=ceil(640/12)=54, +// 半宽 27 格,于是玩家(相机跟着他)被画在 27*12 = 324 像素处而不是 320, +// 换个缩放档又变成 325 —— 滚轮一转,人就在屏幕上左右乱窜。 +static void view_origin(const struct Game_State *g, int w, int h, + double *ox, double *oy) { + double tpx = g->tile_px; + if (tpx < 1.0) tpx = 1.0; + if (ox) *ox = g->cam_wx - 0.5 * (double)w / tpx; + if (oy) *oy = g->cam_wy - 0.5 * (double)h / tpx; +} + +static inline long g_floor_div(long a, long b) { + long q = a / b; + if ((a % b != 0) && ((a < 0) != (b < 0))) q--; + return q; +} + +// y 方向不环绕(两极是边界),x 方向环绕 +static inline int g_wrap_cx(int cx) { + int n = (int)(WORLD_W / CHUNK_SIZE); + cx %= n; + return cx < 0 ? cx + n : cx; +} + +static bool g_chunk_in_range(int cy) { + int n = (int)(WORLD_H / CHUNK_SIZE); + return cy >= 0 && cy < n; +} + +// 生成一个渲染分块的**地形**(不含天气) +// +// 高程要多采一圈"围裙"(18x18 而不是 16x16)。山体阴影是格心差分, +// 如果边缘格拿不到东/南邻居,就只能按"坡度为 0"处理,于是每个 16m 分块的 +// 最右一列和最下一行都会比内部亮一档 —— 满屏看过去就是一张方格网, +// 玩家反馈的"区块之间有缝隙"就是这个。 +static void render_chunk_fill(struct Game_State *g, struct Game_Render_Chunk *rc) { + struct World *w = g->world; + double ox = (double)rc->cx * CHUNK_SIZE - CHUNK_HALF; + double oy = (double)rc->cy * CHUNK_SIZE - CHUNK_HALF; + + enum { AP = GAME_CHUNK_TILES + 2 }; + double e[AP][AP]; + + for (int j = 0; j < AP; j++) { + double wy = g_clamp_y(oy + (double)(j - 1) + 0.5); + for (int i = 0; i < AP; i++) { + double wx = ox + (double)(i - 1) + 0.5; + struct Tile t; + memset(&t, 0, sizeof(t)); + terrain_sample(&t, wx, wy, w); + e[j][i] = t.elevation; + + if (i < 1 || i > GAME_CHUNK_TILES) continue; + if (j < 1 || j > GAME_CHUNK_TILES) continue; + + struct Game_Render_Tile *rt = &rc->t[j - 1][i - 1]; + rt->elev = (float)t.elevation; + rt->slope = (float)t.slope; + rt->water_depth = t.water_depth; + rt->surface = t.surface_type; + rt->rock = t.rock_type; + rt->soil = t.soil_type; + rt->shade = 1.0f; + // 色调扰动:8m 斑块 + 2m 颗粒。烘焙进分块,绘制时零成本。 + double n1 = fractal_noise(w->seed, CHUNK_NOISE_GROUND_M, + wx, wy, 8.0, 2, 0.5); + double n2 = fractal_noise(w->seed, CHUNK_NOISE_GROUND_S, + wx + 11.0, wy - 7.0, 2.0, 2, 0.5); + rt->tone = (uint8_t)gclamp((n1 * 0.65 + n2 * 0.35) * 255.0, 0, 255); + } + } + + // ---- 局部山体阴影 ---- + // 用格心之间的高差算法线。光源放在西北方、约 45° 高——这是地图制图的 + // 常规约定,凹凸方向符合直觉。 + for (int ty = 0; ty < GAME_CHUNK_TILES; ty++) { + for (int tx = 0; tx < GAME_CHUNK_TILES; tx++) { + double e0 = e[ty + 1][tx + 1]; + double gx = e[ty + 1][tx + 2] - e0; + double gy = e[ty + 2][tx + 1] - e0; + // 光源方向 L = (-0.707, -0.707, 0.707) + double nx = -gx, ny = -gy, nz = 1.0; + double len = sqrt(nx * nx + ny * ny + nz * nz); + if (len < 1e-9) len = 1.0; + double diff = (nx * -0.707 + ny * -0.707 + nz * 0.707) / len; + rc->t[ty][tx].shade = (float)gclamp(0.55 + 0.80 * diff, + SHADE_MIN, SHADE_MAX); + } + } + rc->valid = true; +} + +static struct Game_Render_Chunk *render_chunk_get(struct Game_State *g, + int cx, int cy, bool *gen) { + if (gen) *gen = false; + if (!g_chunk_in_range(cy)) return NULL; + cx = g_wrap_cx(cx); + + struct Game_Render_Chunk *empty = NULL; + struct Game_Render_Chunk *lru = NULL; + for (int i = 0; i < g->chunk_count; i++) { + struct Game_Render_Chunk *rc = &g->chunks[i]; + if (rc->valid && rc->cx == cx && rc->cy == cy) { + rc->last_used = g->frame_id; + return rc; + } + if (!rc->valid && empty == NULL) empty = rc; + if (lru == NULL || rc->last_used < lru->last_used) lru = rc; + } + struct Game_Render_Chunk *rc = empty ? empty : lru; + if (rc == NULL) return NULL; + if (gen) *gen = true; + rc->cx = cx; + rc->cy = cy; + rc->last_used = g->frame_id; + return rc; +} + +// =============================================================== +// 天气覆盖层 +// =============================================================== + +// 覆盖层网格:尺寸有上限(否则低缩放下会退化成"每格采一次天气"), +// 而且带缓存——相机没动、时间没走就不重采。 +static bool overlay_needs_refresh(const struct Game_State *g, int ntx, int nty) { + if (!g->ov_valid || g->ov == NULL) return true; + if (g->ov_step <= 0) return true; + if (fabs(g->cam_wx - g->ov_cam_x) > (double)g->ov_step * 0.5) return true; + if (fabs(g->cam_wy - g->ov_cam_y) > (double)g->ov_step * 0.5) return true; + if (g->world->now.seconds - g->ov_time > GAME_OVERLAY_REFRESH_S) return true; + if (g->world->now.seconds < g->ov_time) return true; // 时间倒流(换世界) + if (g->ov_w * GAME_OVERLAY_STEP > ntx + GAME_OVERLAY_STEP * 2) return true; + if (g->ov_h * GAME_OVERLAY_STEP > nty + GAME_OVERLAY_STEP * 2) return true; + (void)ntx; + return false; +} + +static void overlay_sample(struct Game_State *g, int ntx, int nty, + double ox, double oy) { + struct World *w = g->world; + double t = w->now.seconds; + (void)oy; + + // 间隔:保证网格不超过上限 + int step = GAME_OVERLAY_STEP; + while (ntx / step + 3 > GAME_OVERLAY_MAX_X || + nty / step + 3 > GAME_OVERLAY_MAX_Y) step *= 2; + + g->ov_step = step; + g->ov_w = ntx / step + 3; + g->ov_h = nty / step + 3; + if (g->ov_w < 2) g->ov_w = 2; + if (g->ov_h < 2) g->ov_h = 2; + + int need = g->ov_w * g->ov_h; + if (need > g->ov_cap) { + struct Game_Overlay *n = realloc(g->ov, sizeof(struct Game_Overlay) * (size_t)need); + if (n == NULL) { g->ov_valid = false; return; } + g->ov = n; + g->ov_cap = need; + } + + // 网格点 i 落在屏幕格 i*step 的**中心**:世界坐标 = origin + i*step + 0.5。 + // 锚在连续原点上(不是"相机 - 取整的格数/2"),否则网格会随缩放跳半格。 + for (int j = 0; j < g->ov_h; j++) { + for (int i = 0; i < g->ov_w; i++) { + double wx = ox + (double)(i * step) + 0.5; + double wy = g_clamp_y(oy + (double)(j * step) + 0.5); + struct Weather_Sample ws; + // 高程必须传真实地形高程:气候采样里气温有海拔递减率, + // 传 0 会让高原按海平面算,整整高出几度。 + double el = terrain_base_elevation(wx, wy, w); + weather_sample(w, wx, wy, el, t, &ws); + + struct Game_Overlay *o = &g->ov[j * g->ov_w + i]; + o->temp = (float)ws.temperature; + o->snow = (float)ws.snow_cover; + o->ice = (float)ws.ice_thick; + o->cloud = (float)ws.cloud; + o->precip = (float)ws.precipitation; + o->wind = (float)ws.wind_speed; + // 环境光:白天按太阳高度,夜里按月光。 + // 映射要按**感知**来:太阳高度 0~60° 是主要的亮度区间, + // 线性映射到 25° 就饱和会让清晨和正午一样亮、而凌晨黑到看不见。 + double day = gclamp((ws.solar_elev + 5.0) / 45.0, 0.0, 1.0); + o->light = (float)gclamp(0.42 + 0.68 * day + 0.15 * ws.moonlight, + NIGHT_MIN, 1.15); + } + } + g->ov_valid = true; + g->ov_cam_x = g->cam_wx; + g->ov_cam_y = g->cam_wy; + g->ov_time = t; +} + +static void overlay_at(const struct Game_State *g, double tx, double ty, + struct Game_Overlay *out) { + int step = g->ov_step > 0 ? g->ov_step : GAME_OVERLAY_STEP; + // 和 overlay_sample 的锚点对齐:格 k 的中心 -> 网格坐标 (k+0.5)/step + double fx = (tx + 0.5) / (double)step; + double fy = (ty + 0.5) / (double)step; + int ix = (int)floor(fx), iy = (int)floor(fy); + double ax = fx - ix, ay = fy - iy; + if (g->ov == NULL || g->ov_w < 2 || g->ov_h < 2) { + memset(out, 0, sizeof(*out)); + out->light = 1.0f; + return; + } + int x0 = ix < 0 ? 0 : (ix >= g->ov_w - 1 ? g->ov_w - 2 : ix); + int y0 = iy < 0 ? 0 : (iy >= g->ov_h - 1 ? g->ov_h - 2 : iy); + int x1 = x0 + 1, y1 = y0 + 1; + const struct Game_Overlay *a = &g->ov[y0 * g->ov_w + x0]; + const struct Game_Overlay *b = &g->ov[y0 * g->ov_w + x1]; + const struct Game_Overlay *c = &g->ov[y1 * g->ov_w + x0]; + const struct Game_Overlay *d = &g->ov[y1 * g->ov_w + x1]; +#define OV_LERP(f) \ + out->f = (float)(((a->f * (1 - ax) + b->f * ax) * (1 - ay) + \ + (c->f * (1 - ax) + d->f * ax) * ay)) + OV_LERP(temp); OV_LERP(snow); OV_LERP(ice); OV_LERP(cloud); + OV_LERP(precip); OV_LERP(light); OV_LERP(wind); +#undef OV_LERP +} + +// =============================================================== +// 渲染 +// =============================================================== + +// 把一格的颜色算出来 +static struct Color tile_color(const struct Game_State *g, + const struct Game_Render_Tile *rt, + const struct Game_Overlay *ov, + int gx, int gy, double wx, double wy) { + struct Color c = surface_base(rt->surface); + + // 岩石色调混入:地表不是纯色块,底下是什么岩性看得出来 + c = col_lerp(c, rock_tint(rt->rock), 0.22); + + // 烘焙好的色调扰动 + 逐格哈希抖动 + double tone = rt->tone / 255.0; + double v1 = tile_variation(gx / 4, gy / 4, g->world->seed, 1); + double v2 = tile_variation(gx, gy, g->world->seed, 2); + c = col_mul(c, 0.84 + 0.22 * tone + 0.08 * v1 + 0.05 * v2); + + // 水面:浅水透出底质、深水变暗 + if (rt->surface == SURFACE_WATER || rt->water_depth > 0.0f) { + double d = rt->water_depth > 0.0f ? rt->water_depth : 0.2; + double shallow = exp(-d / 3.0); + struct Color deep = (struct Color){26, 52, 86, 255}; + struct Color shal = (struct Color){92, 140, 150, 255}; + c = col_lerp(deep, shal, shallow * 0.85); + // 水面反光:加一点高频条纹,免得像一块塑料 + double ripple = sin(wx * 1.7 + wy * 0.9) * 0.5 + 0.5; + c = col_mul(c, 0.94 + 0.12 * ripple); + } + + // 冰 + if (ov->ice > 0.02f) { + struct Color ice = (struct Color){214, 234, 246, 255}; + c = col_lerp(c, ice, gclamp(0.35 + ov->ice * 0.5, 0.0, 0.95)); + } + // 积雪:按覆盖率刷白,薄雪保留地表 + if (ov->snow > 0.004f) { + struct Color snow = (struct Color){240, 243, 250, 255}; + c = col_lerp(c, snow, gclamp(0.15 + 0.85 * ov->snow, 0.0, 1.0)); + } + // 湿地面(正在下雨、且不是雪):压暗一点 + if (ov->precip > 0.05f && ov->temp > 1.0f) { + c = col_mul(c, 0.88); + } + + // 山体阴影 + c = col_mul(c, rt->shade); + // 昼夜:夜里压暗并往蓝里偏 + c = col_mul(c, ov->light); + if (ov->light < 0.75) { + double nb = NIGHT_BLUE * (1.0 - ov->light / 0.75); + c = (struct Color){ + (unsigned char)gclamp(c.r * (1.0 - nb * 0.8), 0, 255), + (unsigned char)gclamp(c.g * (1.0 - nb * 0.4), 0, 255), + (unsigned char)gclamp(c.b * (1.0 + nb * 0.5), 0, 255), 255}; + } + return c; +} + +// 往像素缓冲里填一块矩形(带裁剪) +static void blit_rect(struct Color *px, int w, int h, + int x0, int y0, int rw, int rh, struct Color c) { + int x1 = x0 + rw, y1 = y0 + rh; + if (x0 < 0) x0 = 0; + if (y0 < 0) y0 = 0; + if (x1 > w) x1 = w; + if (y1 > h) y1 = h; + for (int y = y0; y < y1; y++) { + struct Color *row = px + (size_t)y * w; + for (int x = x0; x < x1; x++) row[x] = c; + } +} + +static inline int g_round(double x) { return (int)floor(x + 0.5); } + +// 工程师:程序化的小人(约 0.7m x 1.8m)。用户给贴图后替换这里。 +static void draw_player(struct Game_State *g, struct Color *px, int w, int h) { + double tpx = g->tile_px; + // 玩家在视图里的**连续**像素坐标,原点必须和 game_render 用同一个 + // (view_origin)。相机跟随玩家时这恰好等于屏幕正中,所以缩放时 + // 人不会动。 + double ox, oy; + view_origin(g, w, h, &ox, &oy); + double cx = (g->player.wx - ox) * tpx; + double cy = (g->player.wy - oy) * tpx; + + int body_w = (int)(0.62 * tpx); + int body_h = (int)(1.10 * tpx); + int head_d = (int)(0.42 * tpx); + if (body_w < 2) body_w = 2; + if (body_h < 3) body_h = 3; + if (head_d < 2) head_d = 2; + + int bx = g_round(cx - body_w * 0.5); + int by = g_round(cy - body_h * 0.5); + + // 影子 + blit_rect(px, w, h, bx - 1, by + body_h - 1, body_w + 2, 2, + (struct Color){0, 0, 0, 255}); + // 腿 + blit_rect(px, w, h, bx, by + body_h / 2, body_w / 3, body_h / 2, + (struct Color){54, 58, 68, 255}); + blit_rect(px, w, h, bx + body_w - body_w / 3, by + body_h / 2, + body_w / 3, body_h / 2, (struct Color){54, 58, 68, 255}); + // 身体(工装橙) + blit_rect(px, w, h, bx, by + head_d, body_w, body_h / 2 - head_d + 1, + (struct Color){214, 126, 40, 255}); + // 头 + blit_rect(px, w, h, g_round(cx - head_d * 0.5), by, head_d, head_d, + (struct Color){226, 190, 150, 255}); + // 朝向指示:眼睛方向的一个小亮点 + int ex = g_round(cx + cos(g->player.facing) * head_d * 0.42); + int ey = g_round(cy - body_h * 0.5 + head_d * 0.5); + blit_rect(px, w, h, ex - 1, ey - 1, 2, 2, (struct Color){40, 40, 48, 255}); +} + +void game_render(struct Game_State *g, struct Color *pixels, int w, int h) { + if (g == NULL || pixels == NULL || w <= 0 || h <= 0) return; + g->buf_w = w; + g->buf_h = h; + g->frame_id++; + + int tpx = (int)g->tile_px; + int ntx = (w + tpx - 1) / tpx; + int nty = (h + tpx - 1) / tpx; + + // 视图左上角对应的世界坐标 + double origin_x, origin_y; + view_origin(g, w, h, &origin_x, &origin_y); + + // 分块缓存要能装下整屏:低缩放下可视范围是几百米 + int need_chunks = (ntx / GAME_CHUNK_TILES + 3) * + (nty / GAME_CHUNK_TILES + 3); + if (need_chunks < GAME_CHUNK_CACHE_MIN) need_chunks = GAME_CHUNK_CACHE_MIN; + if (need_chunks > g->chunk_count) { + struct Game_Render_Chunk *n = calloc((size_t)need_chunks, + sizeof(struct Game_Render_Chunk)); + if (n != NULL) { + free(g->chunks); + g->chunks = n; + g->chunk_count = need_chunks; + } + } + + if (overlay_needs_refresh(g, ntx, nty)) + overlay_sample(g, ntx, nty, origin_x, origin_y); + + // ---- 地形 ---- + // 每格的**屏幕边界**由连续的相机变换算出来,而不是画在 tx*tpx 上。 + // 原来那种画法的问题是:格号 = floor(相机坐标),而矩形永远对齐到 + // tx*tpx,于是相机连续移动时画面只能整格整格地跳(每格 4~32 像素), + // 看上去就是"坐标在动但人走走停停"。现在左右边界各自取整、 + // 相邻格共用边界,所以既平滑又不会留缝。 + double left_x = floor(origin_x + CHUNK_HALF + 0.5) - CHUNK_HALF; // 最左那格的西边界 + double top_y = floor(origin_y + CHUNK_HALF + 0.5) - CHUNK_HALF; + double sx0 = (left_x - origin_x) * (double)tpx; // 该边界在屏幕上的 x(-tpx/2 .. tpx/2] + double sy0 = (top_y - origin_y) * (double)tpx; + long base_gx = (long)(left_x + CHUNK_HALF); + long base_gy = (long)(top_y + CHUNK_HALF); + + int last_cx = 0x7fffffff, last_cy = 0x7fffffff; + struct Game_Render_Chunk *rc = NULL; + for (int j = -1; ; j++) { + int y0 = g_round(sy0 + (double)j * tpx); + int y1 = g_round(sy0 + (double)(j + 1) * tpx); + if (y0 >= h) break; + if (y1 <= 0) continue; + + double wy = g_clamp_y(top_y + (double)j + 0.5); + long gy = g_tile_index(wy); + int cy = (int)g_floor_div(gy, GAME_CHUNK_TILES); + last_cx = 0x7fffffff; + + for (int k = -1; ; k++) { + int x0 = g_round(sx0 + (double)k * tpx); + int x1 = g_round(sx0 + (double)(k + 1) * tpx); + if (x0 >= w) break; + if (x1 <= 0) continue; + + long gx = base_gx + k; + int cx = (int)g_floor_div(gx, GAME_CHUNK_TILES); + + if (cx != last_cx || cy != last_cy) { + bool gen = false; + rc = render_chunk_get(g, cx, cy, &gen); + if (rc != NULL && gen) { + render_chunk_fill(g, rc); + } + last_cx = cx; + last_cy = cy; + } + int lx = (int)(gx - (long)cx * GAME_CHUNK_TILES); + int ly = (int)(gy - (long)cy * GAME_CHUNK_TILES); + if (lx < 0) lx = 0; + if (lx >= GAME_CHUNK_TILES) lx = GAME_CHUNK_TILES - 1; + if (ly < 0) ly = 0; + if (ly >= GAME_CHUNK_TILES) ly = GAME_CHUNK_TILES - 1; + + struct Game_Render_Tile fallback; + const struct Game_Render_Tile *rt; + if (rc != NULL) { + rt = &rc->t[ly][lx]; + } else { + memset(&fallback, 0, sizeof(fallback)); + fallback.surface = SURFACE_WATER; // 极区之外/无效区域当海 + fallback.shade = 1.0f; + rt = &fallback; + } + + double wx = origin_x + ((double)(x0 + x1) * 0.5) / (double)tpx; + struct Game_Overlay ov; + overlay_at(g, (double)k, (double)j, &ov); + struct Color c = tile_color(g, rt, &ov, (int)gx, (int)gy, wx, wy); + blit_rect(pixels, w, h, x0, y0, x1 - x0, y1 - y0, c); + } + } + + // ---- 网格(8m)---- + // 网格线也要跟着分数偏移走,否则线会相对地面滑动。 + if (g->show_grid && tpx >= 8) { + struct Color thin = (struct Color){0, 0, 0, 255}; + long gx0 = (long)floor(left_x + CHUNK_HALF); + long gy0 = (long)floor(top_y + CHUNK_HALF); + long k0 = ((gx0 + 7) / 8) * 8 - gx0; // 第一条落在 8 的整数倍上的格 + for (long k = k0; ; k += 8) { + int x = g_round(sx0 + (double)k * tpx); + if (x >= w) break; + if (x < 0) continue; + for (int y = 0; y < h; y++) { + struct Color *p = &pixels[(size_t)y * w + x]; + *p = col_lerp(*p, thin, 0.25); + } + } + long j0 = ((gy0 + 7) / 8) * 8 - gy0; + for (long j = j0; ; j += 8) { + int y = g_round(sy0 + (double)j * tpx); + if (y >= h) break; + if (y < 0) continue; + struct Color *row = pixels + (size_t)y * w; + for (int x = 0; x < w; x++) row[x] = col_lerp(row[x], thin, 0.25); + } + } + + draw_player(g, pixels, w, h); +} + +// =============================================================== +// 窗口路径 +// =============================================================== + +#include +#ifndef _ +#define _(S) gettext(S) +#endif + +static void text_shadow(struct Font f, const char *s, float x, float y, + float size, float sp, struct Color c) { + DrawTextEx(f, s, (struct Vector2){x + 1.5f, y + 1.5f}, size, sp, + (struct Color){0, 0, 0, 170}); + DrawTextEx(f, s, (struct Vector2){x, y}, size, sp, c); +} + +static void panel(float x, float y, float w, float h) { + DrawRectangle((int)x, (int)y, (int)w, (int)h, (struct Color){8, 10, 14, 185}); + DrawRectangleLines((int)x, (int)y, (int)w, (int)h, + (struct Color){120, 130, 150, 120}); +} + +static void game_hud(struct Game_State *g, struct Font font, float fs, + float sp) { + struct World *w = g->world; + struct Player *p = &g->player; + char line[256]; + float small = fs * 0.78f; + + struct Climate_Sample cs; + climate_sample(&w->climate, w->seed, p->wx, p->wy, 0.0, &cs); + struct Tile pt0; + memset(&pt0, 0, sizeof(pt0)); + terrain_sample(&pt0, p->wx, p->wy, w); + struct Weather_Sample ws; + weather_sample(w, p->wx, p->wy, pt0.elevation, w->now.seconds, &ws); + + // ---- 左上:位置 ---- + double lat = climate_latitude(p->wy); + double lon = p->wx / (double)WORLD_W * 360.0 - 180.0; + panel(10, 10, 330, 96); + snprintf(line, sizeof(line), "X %.0f Y %.0f m", p->wx, p->wy); + text_shadow(font, line, 20, 16, fs, sp, RAYWHITE); + snprintf(line, sizeof(line), "%.3f%s %.3f%s", fabs(lat), + lat >= 0 ? "N" : "S", fabs(lon), lon >= 0 ? "E" : "W"); + text_shadow(font, line, 20, 16 + fs * 1.35f, small, sp, + (struct Color){190, 200, 215, 255}); + struct Tile pt = pt0; + snprintf(line, sizeof(line), "%s %.1f m slope %.2f sun %.0fdeg", + surface_label(pt.surface_type), pt.elevation, pt.slope, + ws.solar_elev); + text_shadow(font, line, 20, 16 + fs * 2.7f, small, sp, + (struct Color){190, 200, 215, 255}); + + // ---- 右上:时间 ---- + struct Planet_Params *pp = &w->planet; + double doy = astro_day_of_year(pp, &w->now); + double hour = astro_local_hour(pp, &w->now, lon); + int years = (int)(w->now.seconds / pp->year_seconds); + panel((float)GetScreenWidth() - 300, 10, 290, 72); + snprintf(line, sizeof(line), "Y%d day %.0f/%.0f %02d:%02d", + years, doy, pp->year_days, (int)hour, + (int)((hour - floor(hour)) * 60.0)); + text_shadow(font, line, (float)GetScreenWidth() - 290, 16, fs, sp, RAYWHITE); + snprintf(line, sizeof(line), "1x realtime (T: skip time)"); + text_shadow(font, line, (float)GetScreenWidth() - 290, 16 + fs * 1.4f, + small * 0.92f, sp, (struct Color){190, 200, 215, 255}); + + // ---- 左下:天气 + 本体 ---- + panel(10, (float)GetScreenHeight() - 132, 350, 122); + snprintf(line, sizeof(line), "air %.1fC wind %.1f m/s RH %.0f%%", + ws.temperature, ws.wind_speed, ws.humidity * 100.0); + text_shadow(font, line, 20, (float)GetScreenHeight() - 126, small, sp, + RAYWHITE); + snprintf(line, sizeof(line), "precip %.2f mm/h cloud %.0f%% snow %.0f%%", + ws.precipitation, ws.cloud * 100.0, ws.snow_cover * 100.0); + text_shadow(font, line, 20, (float)GetScreenHeight() - 126 + fs * 1.3f, + small, sp, (struct Color){200, 208, 220, 255}); + snprintf(line, sizeof(line), "feels like %.1fC storm %.2f tide %+.2f m", + wind_chill_c(ws.temperature, ws.wind_speed), ws.storm, ws.tide_m); + text_shadow(font, line, 20, (float)GetScreenHeight() - 126 + fs * 2.6f, + small, sp, RAYWHITE); + snprintf(line, sizeof(line), "stamina %.0f%% %s %s", + p->stamina * 100.0, + p->in_water ? "in water" : "on foot", + g->world->weather.storms.active_count ? "STORM ACTIVE" : ""); + text_shadow(font, line, 20, (float)GetScreenHeight() - 126 + fs * 3.9f, + small, sp, RAYWHITE); + + // ---- 右下:光标下的格子 ---- + double mx = (double)GetMouseX(), my = (double)GetMouseY(); + double cxw, cyw; + game_screen_to_world(g, mx, my, &cxw, &cyw); + struct Tile ct; + memset(&ct, 0, sizeof(ct)); + terrain_sample(&ct, cxw, cyw, w); + panel((float)GetScreenWidth() - 330, (float)GetScreenHeight() - 116, + 320, 106); + snprintf(line, sizeof(line), "cursor %.0f,%.0f elev %.1f m", + cxw, cyw, ct.elevation); + text_shadow(font, line, (float)GetScreenWidth() - 320, + (float)GetScreenHeight() - 110, small, sp, RAYWHITE); + snprintf(line, sizeof(line), "%s slope %.2f water %.2f m", + surface_label(ct.surface_type), ct.slope, ct.water_depth); + text_shadow(font, line, (float)GetScreenWidth() - 320, + (float)GetScreenHeight() - 110 + fs * 1.3f, small, sp, + (struct Color){200, 208, 220, 255}); + snprintf(line, sizeof(line), "T %.1fC veg %.0f%% river %.0f m3/s", + ct.temperature, ct.vegetation * 100.0, ct.river_depth); + text_shadow(font, line, (float)GetScreenWidth() - 320, + (float)GetScreenHeight() - 110 + fs * 2.6f, small, sp, + (struct Color){200, 208, 220, 255}); + + // ---- 时间跳转面板 ---- + if (g->skip_panel_open || g->skipping) { + float pw = 420, ph = 150; + float px_ = ((float)GetScreenWidth() - pw) * 0.5f; + float py_ = ((float)GetScreenHeight() - ph) * 0.5f; + panel(px_, py_, pw, ph); + if (g->skipping) { + double total = g->skip_target - g->skip_start; + double done = g->skip_done; + float frac = total > 1e-9 ? (float)(done / total) : 1.0f; + snprintf(line, sizeof(line), "simulating %.1f / %.1f game-hours", + done / 3600.0, total / 3600.0); + text_shadow(font, line, px_ + 20, py_ + 18, fs, sp, RAYWHITE); + DrawRectangle((int)(px_ + 20), (int)(py_ + 56), (int)(pw - 40), 22, + (struct Color){30, 34, 42, 255}); + DrawRectangle((int)(px_ + 20), (int)(py_ + 56), + (int)((pw - 40) * frac), 22, + (struct Color){90, 160, 220, 255}); + snprintf(line, sizeof(line), + "advancing world state at full step (%.1f s/tick)", + GAME_SIM_STEP); + text_shadow(font, line, px_ + 20, py_ + 92, small, sp, + (struct Color){200, 208, 220, 255}); + text_shadow(font, "Esc: abort", px_ + 20, py_ + 116, small, sp, + (struct Color){180, 150, 150, 255}); + } else { + snprintf(line, sizeof(line), "skip time: [1] 1h [2] 6h [3] 12h"); + text_shadow(font, line, px_ + 20, py_ + 18, fs * 0.9f, sp, RAYWHITE); + snprintf(line, sizeof(line), "[4] 24h [5] 72h Enter: confirm"); + text_shadow(font, line, px_ + 20, py_ + 52, fs * 0.9f, sp, RAYWHITE); + snprintf(line, sizeof(line), "selected: %d h", g->skip_hours_sel); + text_shadow(font, line, px_ + 20, py_ + 92, fs, sp, + (struct Color){255, 220, 120, 255}); + text_shadow(font, "Esc: cancel", px_ + 20, py_ + 120, small, sp, + (struct Color){180, 150, 150, 255}); + } + } + + if (g->toast_t > 0.0f) { + snprintf(line, sizeof(line), "%s", g->toast); + struct Vector2 sz = MeasureTextEx(font, line, fs, sp); + float x = ((float)GetScreenWidth() - sz.x) * 0.5f; + panel(x - 12, 70, sz.x + 24, fs + 16); + text_shadow(font, line, x, 78, fs, sp, + (struct Color){255, 230, 160, 255}); + } +} + +void game_draw(struct Game_State *g, struct Font font, float font_size, + float spacing) { + int w = GetScreenWidth(), h = GetScreenHeight(); + if (w <= 0 || h <= 0) return; + + static struct Color *buf = NULL; + static int buf_w = 0, buf_h = 0; + if (buf == NULL || buf_w != w || buf_h != h) { + free(buf); + buf = malloc(sizeof(struct Color) * (size_t)w * h); + buf_w = w; buf_h = h; + if (buf == NULL) return; + if (g->texture_valid) { UnloadTexture(g->texture); g->texture_valid = false; } + } + + double t0 = g_now(); + game_render(g, buf, w, h); + g->render_ms = (g_now() - t0) * 1000.0; + + if (!g->texture_valid) { + struct Image img = {0}; + img.data = buf; + img.width = w; + img.height = h; + img.mipmaps = 1; + img.format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8; + g->texture = LoadTextureFromImage(img); + g->texture_valid = true; + } else { + UpdateTexture(g->texture, buf); + } + DrawTexture(g->texture, 0, 0, WHITE); + + game_hud(g, font, font_size, spacing); + + if (g->show_grid) { + text_shadow(font, "grid on (G)", 12, (float)h * 0.5f, font_size * 0.7f, + spacing, (struct Color){200, 200, 200, 160}); + } +} + +// =============================================================== +// 屏幕 <-> 世界 +// =============================================================== + +void game_screen_to_world(const struct Game_State *g, double sx, double sy, + double *wx_out, double *wy_out) { + int w = g->buf_w > 0 ? g->buf_w : GetScreenWidth(); + int h = g->buf_h > 0 ? g->buf_h : GetScreenHeight(); + double ox, oy; + view_origin(g, w, h, &ox, &oy); + if (wx_out) *wx_out = ox + sx / g->tile_px; + if (wy_out) *wy_out = oy + sy / g->tile_px; +} + +bool game_screen_to_world_checked(const struct Game_State *g, double sx, double sy, + int screen_w, int screen_h, + double *wx_out, double *wy_out) { + int tpx = (int)g->tile_px; + int ntx = (screen_w + tpx - 1) / tpx; + int nty = (screen_h + tpx - 1) / tpx; + (void)nty; + (void)ntx; + game_screen_to_world(g, sx, sy, wx_out, wy_out); + return true; +} + +// =============================================================== +// 移动与碰撞 +// =============================================================== + +// 该点能不能站:水太深 / 太陡 都不行 +static bool can_stand(struct World *w, double wx, double wy, double *depth_out) { + struct Tile t; + memset(&t, 0, sizeof(t)); + terrain_sample(&t, wx, wy, w); + if (depth_out) *depth_out = t.water_depth; + if (t.water_depth > WADE_MAX_DEPTH) return false; + if (t.slope > CLIMB_MAX_SLOPE) return false; + return true; +} + +static void player_move(struct Game_State *g, double dt, double dx, double dy) { + struct Player *p = &g->player; + struct World *w = g->world; + + double len = sqrt(dx * dx + dy * dy); + if (len < 1e-9) { p->vx = p->vy = 0.0; return; } + dx /= len; dy /= len; + p->facing = atan2(dy, dx); + + bool running = IsKeyDown(KEY_LEFT_SHIFT) && p->stamina > 0.02; + double speed = PLAYER_WALK; + if (running) { + speed = PLAYER_RUN; + p->stamina -= STAMINA_DRAIN * dt; + if (p->stamina < 0.0) p->stamina = 0.0; + } else { + p->stamina += STAMINA_REGEN * dt; + if (p->stamina > 1.0) p->stamina = 1.0; + } + if (p->in_water) speed *= 0.45; + // 坡度惩罚:越陡越慢 + double depth = 0.0; + struct Tile t; + memset(&t, 0, sizeof(t)); + terrain_sample(&t, p->wx, p->wy, w); + speed *= gclamp(1.0 - t.slope * 1.1, 0.25, 1.0); + (void)depth; + + double step = speed * dt; + double nx = p->wx + dx * step; + double ny = p->wy + dy * step; + + // 分轴尝试:允许沿墙滑动 + bool okx = can_stand(w, nx, p->wy, &depth); + bool oky = can_stand(w, p->wx, ny, &depth); + if (okx) p->wx = nx; + if (oky) p->wy = ny; + if (!okx && !oky) { + // 试试小步(贴边走) + nx = p->wx + dx * step * 0.35; + ny = p->wy + dy * step * 0.35; + if (can_stand(w, nx, p->wy, &depth)) p->wx = nx; + if (can_stand(w, p->wx, ny, &depth)) p->wy = ny; + } + + // 世界边界:y 是两极,不能走出去 + if (p->wy < 1.0) p->wy = 1.0; + double hmax = (double)WORLD_H - 1.0; + if (p->wy > hmax) p->wy = hmax; + double wmax = (double)WORLD_W; + if (p->wx < 0.0) p->wx += wmax; + if (p->wx >= wmax) p->wx -= wmax; + + memset(&t, 0, sizeof(t)); + terrain_sample(&t, p->wx, p->wy, w); + p->water_depth = t.water_depth; + p->in_water = t.water_depth > 0.05; +} + +// =============================================================== +// 世界推进(实时和跳时间共用) +// =============================================================== + +// =============================================================== +// 有状态的世界推进 —— 时间跳转的**唯一**挂钩 +// =============================================================== +// 只有这里有状态的东西才会因为"跳过时间"而变。目前只有台风系统 +// (移动、增强、消散、生成)。 +// +// 以后要加"跳过时间有代价"的东西,全挂在这一行下面: +// 机器磨损/损坏(时间越长越可能坏) +// 作物生长/枯萎、食物腐坏 +// 电力网络的蓄电/放电、燃料消耗 +// 库存/物流的产出累积 +// 它们按 GAME_SIM_STEP(30 游戏秒)积分,所以实时和跳时间走的是 +// 同一套代码,跳时间不会用更粗的近似。 +static void game_state_step(struct Game_State *g, double dt) { + struct World *w = g->world; + weather_storms_update(&w->weather, w, w->now.seconds); + // TODO(state): 机器损坏 / 作物 / 电力 / 库存 ... + (void)dt; +} + +static void game_sim_step(struct Game_State *g) { + game_time_advance(&g->world->now, GAME_SIM_STEP); + game_state_step(g, GAME_SIM_STEP); +} + +bool game_simulate_to(struct Game_State *g, double target_seconds, + double real_budget) { + struct World *w = g->world; + double t0 = g_now(); + double remain = target_seconds - w->now.seconds; + if (remain <= 0.0) return true; + + // 按固定步长推进,但受现实时间预算限制(用来把跳时间切成多帧) + while (remain > 1e-6) { + double step = remain > GAME_SIM_STEP ? GAME_SIM_STEP : remain; + if (step >= GAME_SIM_STEP - 1e-9) { + game_sim_step(g); + } else { + game_time_advance(&w->now, step); + game_state_step(g, step); + } + g->skip_done += step; + remain = target_seconds - w->now.seconds; + if (real_budget > 0.0 && (g_now() - t0) > real_budget) return false; + } + return true; +} + +void game_skip_hours(struct Game_State *g, double hours) { + g->skipping = true; + g->skip_start = g->world->now.seconds; + g->skip_target = g->world->now.seconds + hours * 3600.0; + g->skip_done = 0.0; +} + +// =============================================================== +// 输入 +// =============================================================== + +void game_update(struct Game_State *g, double dt) { + if (g == NULL) return; + struct Player *p = &g->player; + struct World *w = g->world; + + if (g->toast_t > 0.0f) g->toast_t -= (float)dt; + + // ---- 跳时间 ---- + if (g->skipping) { + if (IsKeyPressed(KEY_ESCAPE)) { + g->skipping = false; + snprintf(g->toast, sizeof(g->toast), "time skip aborted"); + g->toast_t = 2.5f; + return; + } + double t0 = g_now(); + bool done = game_simulate_to(g, g->skip_target, 0.010); + g->sim_ms = (g_now() - t0) * 1000.0; + if (done) { + g->skipping = false; + snprintf(g->toast, sizeof(g->toast), + "skipped %.1f h (%d storms active)", + (g->skip_target - g->skip_start) / 3600.0, + g->world->weather.storms.active_count); + g->toast_t = 5.0f; + } + return; // 跳时间期间不接受移动输入 + } + + if (g->skip_panel_open) { + if (IsKeyPressed(KEY_ESCAPE)) g->skip_panel_open = false; + if (IsKeyPressed(KEY_ONE)) g->skip_hours_sel = 1; + if (IsKeyPressed(KEY_TWO)) g->skip_hours_sel = 6; + if (IsKeyPressed(KEY_THREE)) g->skip_hours_sel = 12; + if (IsKeyPressed(KEY_FOUR)) g->skip_hours_sel = 24; + if (IsKeyPressed(KEY_FIVE)) g->skip_hours_sel = 72; + if (IsKeyPressed(KEY_ENTER) || IsKeyPressed(KEY_KP_ENTER)) { + g->skip_panel_open = false; + game_skip_hours(g, (double)g->skip_hours_sel); + } + return; + } + if (IsKeyPressed(KEY_T)) { + g->skip_panel_open = true; + return; + } + if (IsKeyPressed(KEY_G)) g->show_grid = !g->show_grid; + if (IsKeyPressed(KEY_F)) g->follow = !g->follow; + + // ---- 缩放 ---- + // 只按**整个像素台阶**走。渲染分块那边按 (int)tile_px 铺像素,而玩家和 + // 光标换算用的是 double,两边不一致人就会相对地面滑动;滚轮送来的增量 + // 也不一定是整数(触摸板、高分辨率滚轮会给 0.1/0.5)。所以先攒起来, + // 够一格才动——不然小数增量会被抹掉,滚半天没反应。 + double wheel = GetMouseWheelMove(); + if (wheel != 0.0) { + g->zoom_accum += wheel * 2.0; + double stepz = floor(g->zoom_accum); + if (stepz != 0.0) { + g->zoom_accum -= stepz; + g->tile_px = gclamp(g->tile_px + stepz, GAME_TILE_PX_MIN, + GAME_TILE_PX_MAX); + if (g->tile_px <= GAME_TILE_PX_MIN || + g->tile_px >= GAME_TILE_PX_MAX) { + g->zoom_accum = 0.0; // 顶到边界就别再攒了 + } + } + } + if (IsKeyPressed(KEY_EQUAL)) g->tile_px = gclamp(g->tile_px + 2, GAME_TILE_PX_MIN, GAME_TILE_PX_MAX); + if (IsKeyPressed(KEY_MINUS)) g->tile_px = gclamp(g->tile_px - 2, GAME_TILE_PX_MIN, GAME_TILE_PX_MAX); + + // ---- 移动 ---- + double dx = 0.0, dy = 0.0; + if (IsKeyDown(KEY_W) || IsKeyDown(KEY_UP)) dy -= 1.0; + if (IsKeyDown(KEY_S) || IsKeyDown(KEY_DOWN)) dy += 1.0; + if (IsKeyDown(KEY_A) || IsKeyDown(KEY_LEFT)) dx -= 1.0; + if (IsKeyDown(KEY_D) || IsKeyDown(KEY_RIGHT)) dx += 1.0; + player_move(g, dt, dx, dy); + + // ---- 相机 ---- + if (g->follow) { + g->cam_wx = p->wx; + g->cam_wy = p->wy; + } else { + double pan = 40.0 * dt * (IsKeyDown(KEY_LEFT_SHIFT) ? 3.0 : 1.0); + if (IsKeyDown(KEY_W)) g->cam_wy -= pan; + if (IsKeyDown(KEY_S)) g->cam_wy += pan; + if (IsKeyDown(KEY_A)) g->cam_wx -= pan; + if (IsKeyDown(KEY_D)) g->cam_wx += pan; + } + + // ---- 实时推进世界 ---- + // 游戏内 1 秒 = 现实 1 秒。按固定步长走,和跳时间用同一个 sim_step。 + game_simulate_to(g, w->now.seconds + dt, 0.0); +} + +// =============================================================== +// 生命周期 +// =============================================================== + +struct Game_State *game_create(struct World *w, double wx, double wy) { + if (w == NULL) return NULL; + struct Game_State *g = calloc(1, sizeof(struct Game_State)); + if (g == NULL) return NULL; + g->world = w; + g->tile_px = GAME_TILE_PX_DEF; + g->follow = true; + g->show_grid = false; + g->skip_hours_sel = 6; + + g->chunk_count = GAME_CHUNK_CACHE_MIN; + g->chunks = calloc((size_t)g->chunk_count, sizeof(struct Game_Render_Chunk)); + if (g->chunks == NULL) { free(g); return NULL; } + + // 着陆点:不是陆地就往北/南找最近的海岸(最多找 2000 格) + struct Tile t; + memset(&t, 0, sizeof(t)); + terrain_sample(&t, wx, wy, w); + double px = wx, py = wy; + if (t.elevation < 0.0 || t.water_depth > WADE_MAX_DEPTH) { + bool found = false; + for (int r = 1; r <= 2000 && !found; r++) { + double d = (double)r; + const double off[4][2] = {{0,-1},{0,1},{-1,0},{1,0}}; + for (int k = 0; k < 4 && !found; k++) { + double cx = wx + off[k][0] * d; + double cy = wy + off[k][1] * d; + if (cy < 1.0 || cy > (double)WORLD_H - 1.0) continue; + if (cx < 0.0) cx += (double)WORLD_W; + if (cx >= (double)WORLD_W) cx -= (double)WORLD_W; + memset(&t, 0, sizeof(t)); + terrain_sample(&t, cx, cy, w); + if (t.elevation >= 0.0 && t.water_depth <= WADE_MAX_DEPTH && + t.slope <= CLIMB_MAX_SLOPE) { + px = cx; py = cy; found = true; + } + } + } + if (!found) { /* 全是海:就落在原地,玩家自己想办法 */ } + } + + g->player.wx = px; + g->player.wy = py; + g->player.walk_speed = PLAYER_WALK; + g->player.stamina = 1.0; + + // 着陆时间:把世界钟拨到着陆点的**当地上午**。世界时间从 0 起算, + // 而那可能正好是当地的深夜(day 0 落在春分前 60 天),一片漆黑。 + { + struct Planet_Params *pp = &w->planet; + double lon = px / (double)WORLD_W * 360.0 - 180.0; + // 先看这个季节在这个纬度"正午"能有多亮。高纬的深冬正午太阳高度 + // 不到 10°,进去就是一片黑——所以远征队默认等春天再降落。 + double lat = climate_latitude(py); + double doy = astro_day_of_year(pp, &w->now); + struct Game_Time noon = game_time_at( + (floor(w->now.seconds / pp->day_seconds) + 0.5) * pp->day_seconds); + double noon_dec = astro_solar_declination(pp, &noon); + double noon_elev = 90.0 - fabs(lat - noon_dec); + if (noon_elev < 25.0) { + // 推到下一个春分 + double cur = doy; + double eq = pp->equinox_day; + double adv = eq - cur; + if (adv <= 0.0) adv += pp->year_days; + game_time_advance(&w->now, adv * pp->day_seconds); + } + double hour = astro_local_hour(pp, &w->now, lon); + double target = 9.0; // 当地 9 点 + double hours_fwd = target - hour; + if (hours_fwd < 0.0) hours_fwd += 24.0; + game_time_advance(&w->now, hours_fwd * 3600.0); + } + + g->cam_wx = px; + g->cam_wy = py; + g->ov_w = g->ov_h = 0; + g->ov = NULL; + snprintf(g->toast, sizeof(g->toast), "landed at %.0f, %.0f", px, py); + g->toast_t = 4.0f; + return g; +} + +void game_free(struct Game_State *g) { + if (g == NULL) return; + if (g->texture_valid) UnloadTexture(g->texture); + free(g->ov); + free(g->chunks); + free(g); +} diff --git a/src/game.h b/src/game.h new file mode 100644 index 0000000..cc7a7fc --- /dev/null +++ b/src/game.h @@ -0,0 +1,147 @@ +#ifndef GAME_H +#define GAME_H + +#include +#include +#include +#include "world.h" + +// =============================================================== +// 局部游戏层(1 格 = 1 米) +// =============================================================== +// 世界层是行星尺度(40960km),地块层是米级(chunk.c 的 1m 格)。 +// 这一层把两者接起来:在世界地图上选一个着陆点,然后进入米级俯视视图, +// 玩家是一个能走动的工程师。 +// +// 渲染走的是"写像素缓冲"这条路,不依赖窗口——所以可以在没有 GL 的环境里 +// 出图验证(见 test/test_game.c)。窗口路径只是把同一张图贴成纹理再叠 HUD。 +// --------------------------------------------------------------- + +// 局部视图的缩放:一格(1m)多少像素。4px/m 看 240m 宽,32px/m 看 30m 宽。 +#define GAME_TILE_PX_MIN 4 +#define GAME_TILE_PX_MAX 32 +#define GAME_TILE_PX_DEF 12 + +// 渲染用的分块缓存:和 chunk.c 的 chunk 对齐(16x16 米) +#define GAME_CHUNK_TILES 16 +#define GAME_CHUNK_CACHE_MIN 256 // 实际会按屏幕尺寸自动放大 +#define GAME_OVERLAY_STEP 4 // 天气覆盖层最小间隔(格) +#define GAME_OVERLAY_MAX_X 48 // 覆盖层网格上限(越界就加大间隔) +#define GAME_OVERLAY_MAX_Y 32 +#define GAME_OVERLAY_REFRESH_S 60.0 // 游戏时间走过这么多秒就重采一次 + +// 世界推进的固定步长(游戏秒)。实时和"跳时间"用的是同一个步长, +// 所以跳时间不会用更粗的近似。1 秒 = 30 游戏刻,30 秒 = 900 刻。 +#define GAME_SIM_STEP 30.0 + +// =============================================================== +// 工程师 +// =============================================================== + +struct Player { + double wx, wy; // 世界坐标(米) + double vx, vy; // 速度 m/s + double facing; // 朝向(弧度,0 = +x) + double walk_speed; // 基础步行速度 m/s + double stamina; // 体力 0..1 + bool in_water; + double water_depth; // 所处水深 m + + // ---- 留空:这里以后放"会变、会害人"的本体状态 ---- + // 设计上这些量由 game_sim_step 按 GAME_SIM_STEP 积分,所以跳时间 + // 会真的让它们演化(体感温度、失温、饥饿、辐射、中毒……)。 + // 现在刻意不实现:等机器损坏/生存系统那套一起做,免得先写一套 + // 半成品的热平衡再推翻。 +}; + +// =============================================================== +// 时间跳转 +// =============================================================== +// 设计(用户指定):不是"加速",是**离散跳转**——玩家说跳 6 小时,引擎就 +// 以全精度把世界推进 6 游戏小时,期间所有状态量按 GAME_SIM_STEP 积分, +// 跳完之后回到 1x 实时。代价由玩家承担,所以必须真的跑模拟,不能插值跳过。 +// +// 现在的状态量只有台风系统和工程师本体;以后机器/作物/电力都挂到 +// game_sim_step 里就行。 + +struct Game_Render_Chunk; // 内部定义在 game.c +struct Game_Overlay; + +struct Game_State { + struct World *world; + + struct Player player; + + // 视角 + double tile_px; // 每格像素(**始终是整数**,见 game_update) + double zoom_accum; // 滚轮小数增量的累加器,够一格才动 + double cam_wx, cam_wy; // 视图中心的世界坐标 + bool follow; // 相机是否跟随玩家 + double free_cam_x, free_cam_y; // 自由视角时的偏移 + + // 渲染分块缓存 + struct Game_Render_Chunk *chunks; + int chunk_count; + uint32_t frame_id; + + // 天气覆盖层(粗网格,双线性插值到每个格)。 + // 采样很贵(weather_sample 里含 climate_sample + hydro_sample + + // river_sample),所以网格尺寸有上限,而且带缓存:相机没怎么动、 + // 时间没怎么走就不重采。 + int ov_w, ov_h, ov_step, ov_cap; + double ov_cam_x, ov_cam_y, ov_time; + bool ov_valid; + struct Game_Overlay *ov; + + // 像素缓冲 + struct Color *pixels; + int buf_w, buf_h; + struct Texture texture; + bool texture_valid; + bool show_grid; + + // 时间跳转 + bool skipping; + double skip_start, skip_target; // 游戏秒 + double skip_done; // 已模拟的游戏秒 + int skip_hours_sel; // UI 里选的小时数 + bool skip_panel_open; + + // HUD 临时提示 + char toast[160]; + float toast_t; + + // 帧率统计 + double render_ms, sim_ms, gen_ms; +}; + +// 从世界坐标创建(着陆点不合法的会自动挪到最近的陆地) +struct Game_State *game_create(struct World *w, double wx, double wy); +void game_free(struct Game_State *g); + +// 实时输入 + 移动 + 相机。dt 是现实秒(= 游戏秒)。 +void game_update(struct Game_State *g, double dt); + +// 把世界推进到 target_seconds。real_budget 是本次调用允许花的**现实秒** +// (用来把跳时间切成多帧,好画进度条)。返回 true = 已完成。 +bool game_simulate_to(struct Game_State *g, double target_seconds, + double real_budget); + +// 开始一次时间跳转(游戏小时) +void game_skip_hours(struct Game_State *g, double hours); + +// 纯渲染:把视图写进 pixels(w*h)。不碰窗口,可以 headless 调用。 +void game_render(struct Game_State *g, struct Color *pixels, int w, int h); + +// 窗口路径:渲染 + 贴纹理 + HUD +void game_draw(struct Game_State *g, struct Font font, float font_size, + float spacing); + +// 光标(屏幕像素)指向的世界坐标 +void game_screen_to_world(const struct Game_State *g, double sx, double sy, + double *wx_out, double *wy_out); +bool game_screen_to_world_checked(const struct Game_State *g, double sx, double sy, + int screen_w, int screen_h, + double *wx_out, double *wy_out); + +#endif diff --git a/src/hydro.c b/src/hydro.c new file mode 100644 index 0000000..fd67aeb --- /dev/null +++ b/src/hydro.c @@ -0,0 +1,968 @@ +#include "hydro.h" +#include "world.h" +#include "river.h" +#include "weather.h" +#include "climate.h" +#include "noise.h" +#include "random.h" + +#include +#include +#include +#include + +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + +#define SEC_PER_YEAR_H 31557600.0 + +// =============================================================== +// 参数 +// =============================================================== +// 这一层只做两件事:把年降水分配进 12 个月、算成流量,以及算水体温度。 +// 所有系数都对着真实河流/湖泊的量级标定,注释里给了参考值。 + +// ---- 月水量平衡 ---- +// 雨雪分界:实测 2℃ 以上基本全是雨、-2℃ 以下全是雪。 +#define SNOW_RAIN_T 2.0 +#define SNOW_SNOW_T (-2.0) +// 度日融雪因子。实测 2~8 mm/(℃·day),开阔地 4 左右。冰面反照率低、 +// 内部有液态水,化得比雪快,所以雪用 4、冰用 6。 +#define DDF_SNOW 4.0 +#define DDF_ICE 6.0 +// 土壤田间持水量。1m 根层的典型值 100~200mm。 +#define SOIL_CAP_MM 150.0 +#define WILT_FRAC 0.25 // 凋萎含水量(低于它植物吸不到水) +#define SWE_CAP_MM 3000.0 // 常年积雪的净积累上限(超出按冰流排出) +// 基流:降水中一部分先入渗补给地下水,再按退水曲线慢慢放出来。 +// 没有它的话,旱季的河流会干到 0——真实大河靠地下水撑着,退水段 +// 是指数衰减(基流指数 0.4~0.6,大河取高值),这正是"汛期过后水位 +// 缓慢回落"的来源。 +#define BETA_GW 0.45 // 入渗补给比例 +#define TAU_GW_DAYS 70.0 // 地下水退水时间常数 + +// ---- 水体温度 ---- +// 水的热容让季节振幅小于气温、相位落后于气温。河流浅、跟得紧; +// 湖泊深、滞后大;海洋混合层最深、滞后最大。 +#define WATER_AMP_RIVER 0.88 +#define WATER_AMP_LAKE 0.55 +#define WATER_AMP_OCEAN 0.28 +#define WATER_LAG_RIVER 16.0 +#define WATER_LAG_LAKE 45.0 +#define WATER_LAG_OCEAN 78.0 +#define WATER_LAG_AIR 28.0 +// 水面热交换的时间常数 τ = ρ·cp·H / k(秒),k 是水气界面的换热系数 +// (W·m^-2·K^-1)。k 用体块公式:感热 + 潜热 + 长波,随风速上升, +// k ≈ 8 + 12·U (U 为风速 m/s) +// 静风 8、8m/s 风 104,量级和实测(20~120)一致。 +// 于是 τ = 4.2e6·H/k。沿程每 40km 的松弛因子 exp(-Δt/τ) 让水温既带着 +// 上游的记忆、又逐渐回到当地平衡温度——尼罗河把赤道的水一路带到埃及, +// 沿途会慢慢变成埃及的冬季气温,而不是把维多利亚湖的 24℃ 原样搬过去。 +// (用固定的 25W·m^-2·K^-1 时,一条 50m 深的大河要一万多公里才回到 +// 平衡温度,50°N 的河会带着热带的水过冬,明显偏暖。) +#define WATER_THERM_NUM 4.2e6 // ρ·cp = 4.2e6 J·m^-3·K^-1 +#define WATER_K_BASE 8.0 // 静风换热系数 +#define WATER_K_WIND 12.0 // 每 m/s 风速增加 +// 有效混合深度上限。实测大江大河的水温基本跟着气温走(滞后 2~4 周、 +// 振幅略小于气温),用断面平均水深当热惯性厚度会把大江的热响应压得 +// 过慢——垂向湍流混合 + 河面辐射让它比这快得多。15m 是标定值。 +#define WATER_H_EFF_MAX 15.0 +#define LAKE_STRAT_SCALE 18.0 // 分层尺度:越深越接近年均温 + +// ---- 冰 ---- +// Stefan 定律:冰厚 = k·sqrt(冻结指数)。k=0.03 是湖冰实测值, +// 1000℃·day 对应约 0.95m 冰。 +#define STEFAN_K 0.030 +#define ICE_MIN_M 0.02 +#define SEA_ICE_MAX_M 3.0 +#define JAM_DT_REF 6.0 // 下游年均温低这么多 -> 凌汛纬度梯度拉满 +#define JAM_Q_REF 800.0 // 流量参考(大河冰坝更严重) +#define JAM_THAW_REF 0.030 // 开河速率参考 m/天 +#define LAKE_RES_MAX_D 180.0 // 湖泊换水时间的上限(作为相位用) +#define LAG_MAX_D 90.0 // 流域平均汇流时间的上限(天) +#define THERM_LAG_MAX_D 30.0 // 水温相位的上限(天) + +// ---- 潮汐 ---- +// 潮差主要是**地理**现象:开阔洋面只有 0.3~0.6m,宽浅陆架 2~4m, +// 喇叭口河口 8~16m(芬迪湾 16m)。用格林定律的量级(振幅 ∝ h^-1/4~-1/2) +// 加一个海盆尺度的随机因子来覆盖这个跨度。 +#define TIDE_BASE_M 1.80 +#define TIDE_DEPTH_REF 200.0 +#define TIDE_DEPTH_EXP 0.40 +#define TIDE_RANGE_MIN 0.20 +#define TIDE_RANGE_MAX 14.0 +#define TIDE_SHELF_R 4 // 取 ±4 格(±160km)的平均水深 + +// =============================================================== +// 小工具与编解码 +// =============================================================== + +static double hc(double x, double lo, double hi) { + return x < lo ? lo : (x > hi ? hi : x); +} +static double hs01(double t) { + t = hc(t, 0.0, 1.0); + return t * t * (3.0 - 2.0 * t); +} +static double hstep(double a, double b, double x) { + if (b == a) return x >= b ? 1.0 : 0.0; + return hs01((x - a) / (b - a)); +} +static inline int hwrap_x(int x, int n) { + x %= n; + return x < 0 ? x + n : x; +} + +// 流量比:1/32 一档,0 ~ 7.97(12 个月的径流/流量形状都用它) +static uint8_t enc_q(double r) { + if (!(r > 0.0)) return 0; + int v = (int)lround(r * 32.0); + return (uint8_t)(v > 255 ? 255 : v); +} +static double dec_q(uint8_t v) { return v / 32.0; } + +// 温度:0.5℃ 一档,-60 ~ +67.5℃ +static uint8_t enc_t(double t) { + if (!(t > -60.0)) t = -60.0; + int v = (int)lround((t + 60.0) * 2.0); + return (uint8_t)(v < 0 ? 0 : (v > 255 ? 255 : v)); +} +static double dec_t(uint8_t v) { return v * 0.5 - 60.0; } + +// 雪水当量:10mm 一档,0 ~ 2550mm +static uint8_t enc_swe(double mm) { + if (!(mm > 0.0)) return 0; + int v = (int)lround(mm / 10.0); + return (uint8_t)(v > 255 ? 255 : v); +} +static double dec_swe(uint8_t v) { return v * 10.0; } + +// 月降水:sqrt 刻度,0 ~ 1500mm(100mm 处约 3mm 一档) +static uint8_t enc_mm(double mm) { + if (!(mm > 0.0)) return 0; + double s = sqrt(mm / 1500.0); + int v = (int)lround(s * 255.0); + return (uint8_t)(v > 255 ? 255 : v); +} +static double dec_mm(uint8_t v) { + double s = v / 255.0; + return s * s * 1500.0; +} + +// 0..1 +static uint8_t enc_f(double f) { + return (uint8_t)lround(hc(f, 0.0, 1.0) * 255.0); +} +static double dec_f(uint8_t v) { return v / 255.0; } + +typedef double (*dec_fn)(uint8_t); + +// =============================================================== +// 每月的气候表 +// =============================================================== +// 每格都去调 weather_monsoon_index 是 1200 万次,太贵。季风只跟纬度和 +// 时间有关,所以按纬度带建表,格点上插值。 + +struct Month_Tab { + int bands; + double t_mid[HYDRO_MONTHS]; + double days; + double shift_y[HYDRO_MONTHS]; // 雨带随太阳赤纬的南北平移 + double *wt; // [12][bands+1] 降水权重 + double *sp_air; // [12][bands+1] 气温季节相位 + double *sp_riv; // [12][bands+1] 水体季节相位(三种滞后) + double *sp_lak; + double *sp_oce; +}; + +static double tab_band(const double *tab, int m, int bands, double wy) { + double by = wy / (double)WORLD_BLOCK_SIZE - 0.5; + int iy = (int)floor(by); + double fy = by - iy; + if (iy < 0) { iy = 0; fy = 0.0; } + if (iy > bands - 2) { iy = bands - 2; fy = 1.0; } + const double *p = tab + (size_t)m * (bands + 1); + return p[iy] * (1.0 - fy) + p[iy + 1] * fy; +} + +static void month_tab_build(struct Month_Tab *mt, struct World *w) { + struct Planet_Params *p = &w->planet; + struct Weather_Field *wf = &w->weather; + int bands = wf->bands > 1 ? wf->bands : 1; + mt->bands = bands; + size_t sz = (size_t)HYDRO_MONTHS * (size_t)(bands + 1); + + mt->wt = malloc(sizeof(double) * sz); + mt->sp_air = malloc(sizeof(double) * sz); + mt->sp_riv = malloc(sizeof(double) * sz); + mt->sp_lak = malloc(sizeof(double) * sz); + mt->sp_oce = malloc(sizeof(double) * sz); + if (mt->wt == NULL || mt->sp_air == NULL || mt->sp_riv == NULL || + mt->sp_lak == NULL || mt->sp_oce == NULL) return; + + mt->days = p->year_days / HYDRO_MONTHS; + for (int m = 0; m < HYDRO_MONTHS; m++) { + mt->t_mid[m] = ((double)m + 0.5) * mt->days * p->day_seconds; + struct Game_Time gt = game_time_at(mt->t_mid[m]); + double dec = astro_solar_declination(p, >); + mt->shift_y[m] = -dec / 180.0 * (double)WORLD_H; + } + for (int j = 0; j <= bands; j++) { + double wy = ((double)j + 0.5) * (double)WORLD_BLOCK_SIZE; + for (int m = 0; m < HYDRO_MONTHS; m++) { + size_t k = (size_t)m * (size_t)(bands + 1) + (size_t)j; + mt->wt[k] = weather_precip_weight(wf, p, wy, mt->t_mid[m]); + mt->sp_air[k] = weather_season_phase(wf, p, wy, + mt->t_mid[m] - WATER_LAG_AIR * p->day_seconds); + mt->sp_riv[k] = weather_season_phase(wf, p, wy, + mt->t_mid[m] - WATER_LAG_RIVER * p->day_seconds); + mt->sp_lak[k] = weather_season_phase(wf, p, wy, + mt->t_mid[m] - WATER_LAG_LAKE * p->day_seconds); + mt->sp_oce[k] = weather_season_phase(wf, p, wy, + mt->t_mid[m] - WATER_LAG_OCEAN * p->day_seconds); + } + } +} + +static void month_tab_free(struct Month_Tab *mt) { + free(mt->wt); free(mt->sp_air); free(mt->sp_riv); + free(mt->sp_lak); free(mt->sp_oce); + memset(mt, 0, sizeof(*mt)); +} + +// =============================================================== +// 内存 +// =============================================================== + +static void hf_alloc(struct Hydro_Field *hf, int n, double cell_m) { + const size_t nn = (size_t)n * n; + hf->n = n; + hf->cell_m = cell_m; + hf->cell_area = cell_m * cell_m; + hf->q_shape = calloc(nn * HYDRO_MONTHS, 1); + hf->wtemp = calloc(nn * HYDRO_MONTHS, 1); + hf->swe = calloc(nn * HYDRO_MONTHS, 1); + hf->precip = calloc(nn * HYDRO_MONTHS, 1); + hf->soil = calloc(nn * HYDRO_MONTHS, 1); + hf->is_water = calloc(nn, 1); + hf->freeze_m = malloc(nn); + hf->break_m = malloc(nn); + hf->tidal_range = calloc(nn, sizeof(float)); + hf->tidal_form = calloc(nn, 1); + hf->lag_days = calloc(nn, sizeof(float)); + if (hf->freeze_m) memset(hf->freeze_m, 255, nn); + if (hf->break_m) memset(hf->break_m, 255, nn); +} + +static bool hf_ok(const struct Hydro_Field *hf) { + return hf->q_shape && hf->wtemp && hf->swe && hf->precip && hf->soil && + hf->is_water && hf->freeze_m && hf->break_m && hf->tidal_range && + hf->tidal_form && hf->lag_days; +} + +void hydro_free(struct Hydro_Field *hf) { + if (hf == NULL) return; + free(hf->q_shape); free(hf->wtemp); free(hf->swe); + free(hf->precip); free(hf->soil); free(hf->is_water); + free(hf->freeze_m); free(hf->break_m); free(hf->tidal_range); + free(hf->tidal_form); free(hf->lag_days); + memset(hf, 0, sizeof(*hf)); +} + +// =============================================================== +// 月水量平衡 +// =============================================================== +// 这是积雪能"存水"的地方:冬天的降水以雪的形式攒着、春天化出来, +// 于是径流的峰值不在降水最多的月份,而在融雪最猛的月份。这就是春汛。 + +static void cell_balance(const double *P, const double *T, const double *pet, + double days, double *runoff_out, + double *swe_out, double *soil_out) { + double swe = 0.0; + double soil = SOIL_CAP_MM * 0.5; + double gw = 0.0; + double wp = WILT_FRAC * SOIL_CAP_MM; + + // 前两年只是让雪和土壤水走到周期态,第三年的状态才记下来。 + for (int cycle = 0; cycle < 3; cycle++) { + for (int m = 0; m < HYDRO_MONTHS; m++) { + double snow_frac = hstep(SNOW_RAIN_T, SNOW_SNOW_T, T[m]); + double acc = P[m] * snow_frac; + double rain = P[m] - acc; + + double melt = DDF_SNOW * (T[m] > 0.0 ? T[m] : 0.0) * days; + if (melt > swe + acc) melt = swe + acc; + if (melt < 0.0) melt = 0.0; + swe += acc - melt; + // 常年积雪:净积累超过上限的部分按冰流/消融排出,不让它无限攒 + double spill = 0.0; + if (swe > SWE_CAP_MM) { spill = swe - SWE_CAP_MM; swe = SWE_CAP_MM; } + + double liq = rain + melt + spill; + + // 蒸散:有雪盖时几乎只剩升华,低温下 PET 本身也很低 + double e = pet[m]; + if (swe > 1.0) { + double scf = hc(swe / (swe + 10.0), 0.0, 1.0); + e *= (1.0 - 0.85 * scf); + } + e *= hc((T[m] + 2.0) / 6.0, 0.0, 1.0); + e *= hc((soil - wp) / (SOIL_CAP_MM - wp), 0.0, 1.0); + + double d = soil + liq - e; + double excess = 0.0; + if (d > SOIL_CAP_MM) { excess = d - SOIL_CAP_MM; soil = SOIL_CAP_MM; } + else { soil = d < 0.0 ? 0.0 : d; } + + // 快排(地表径流)+ 慢排(地下水基流) + double rech = excess * BETA_GW; + gw += rech; + double release = gw * (1.0 - exp(-days / TAU_GW_DAYS)); + if (release > gw) release = gw; + gw -= release; + + runoff_out[m] = (excess - rech) + release; + if (cycle == 2) { swe_out[m] = swe; soil_out[m] = soil; } + } + } +} + +// =============================================================== +// 冰厚序列 +// =============================================================== +// Stefan 定律的增量形式:I_new = sqrt(I² + k²·(-T)·Δt),融化走度日。 +// 从全年最暖的那个月(那里必然无冰)开始循环积分一整年,得到周期性 +// 稳定的年内冰情。封冻日/开河日就是冰厚穿越阈值的时刻。 + +static void ice_series(const uint8_t *wt, double month_days, double *ice_out, + int *m_warm_out) { + int m_warm = 0; + for (int m = 1; m < HYDRO_MONTHS; m++) + if (wt[m] > wt[m_warm]) m_warm = m; + if (m_warm_out) *m_warm_out = m_warm; + + double cur = 0.0; + for (int k = 1; k <= HYDRO_MONTHS; k++) { + int m = (m_warm + k) % HYDRO_MONTHS; + double T = dec_t(wt[m]); + if (T < 0.0) { + cur = sqrt(cur * cur + STEFAN_K * STEFAN_K * (-T) * month_days); + if (cur > SEA_ICE_MAX_M) cur = SEA_ICE_MAX_M; + } else { + cur -= DDF_ICE * 0.001 * T * month_days; + if (cur < 0.0) cur = 0.0; + } + ice_out[m] = cur; + } +} + +// 把"月"插值到分数月:返回 m0/m1 与权重 +static void month_idx(double xm, int *m0, int *m1, double *tm) { + int a = (int)floor(xm); + double t = xm - a; + a = ((a % HYDRO_MONTHS) + HYDRO_MONTHS) % HYDRO_MONTHS; + *m0 = a; + *m1 = (a + 1) % HYDRO_MONTHS; + *tm = t; +} + +// =============================================================== +// 汇流时间 +// =============================================================== +// 洪峰不是全流域同时到达的。沿程每个 40km 格要花 L/v,湖泊还要加上 +// 换水时间;从河源到某格的累计行程时间就是那里洪峰落后的时间。 +// 亚马逊从安第斯到 Óbidos 的洪峰落后约 2 个月,就是这个量。 + +static void compute_travel(struct Hydro_Field *hf, struct River_Field *rf, + const float *vel) { + const int n = rf->n; + const size_t nn = (size_t)n * n; + + double *travel = calloc(nn, sizeof(double)); // 到入海口的行程时间(天) + double *maxtr = calloc(nn, sizeof(double)); // 流域内最远的行程时间 + if (travel == NULL || maxtr == NULL) { free(travel); free(maxtr); return; } + + for (size_t i = 0; i < nn; i++) { + double dt = 0.0; + if (rf->elev[i] >= 0.0) { + double v = vel[i]; + if (v < 0.02) v = 0.02; + dt = rf->cell_m / v / 86400.0; + // 湖泊换水时间只能在**出湖那一格**计入一次,否则一个跨 10 格 + // 的湖会被重复计 10 遍,滞后直接爆掉。 + int dn = rf->down[i]; + bool lake_outlet = (dn < 0) || (rf->lake_depth[dn] <= 0.0f); + if (rf->lake_depth[i] > 0.0f && lake_outlet && + rf->discharge[i] > 10.0) { + double vol = (double)rf->lake_depth[i] * rf->cell_area; + double res = vol / rf->discharge[i] / 86400.0; + if (res > LAKE_RES_MAX_D) res = LAKE_RES_MAX_D; + dt += res; + } + } + travel[i] = dt; + maxtr[i] = dt; + } + + // topo[0] 最靠下游。先算"到入海口"(下游先算)…… + for (int t = 0; t < rf->topo_count; t++) { + int c = rf->topo[t]; + int j = rf->down[c]; + if (j >= 0) travel[c] += travel[j]; + } + // …再算"流域内最远的行程时间"(上游先算) + for (int t = rf->topo_count - 1; t >= 0; t--) { + int c = rf->topo[t]; + int j = rf->down[c]; + if (j >= 0 && maxtr[j] < maxtr[c]) maxtr[j] = maxtr[c]; + } + + for (size_t i = 0; i < nn; i++) { + // 平均滞后 ≈ 流域内最长行程时间的一半(时间-面积图的形心)。 + // 上限 90 天:更大的"滞后"只是说明该格以下游水库的形式蓄水, + // 那属于流量衰减,不是相位移动。 + double lag = 0.5 * (maxtr[i] - travel[i]); + if (lag < 0.0) lag = 0.0; + if (lag > LAG_MAX_D) lag = LAG_MAX_D; + hf->lag_days[i] = (float)lag; + } + free(travel); + free(maxtr); +} + +// =============================================================== +// 主构建 +// =============================================================== + +void hydro_build(struct Hydro_Field *hf, struct World *w) { + if (hf == NULL || w == NULL || w->rivers == NULL) return; + struct River_Field *rf = w->rivers; + const int n = rf->n; + if (n <= 0) return; + const size_t nn = (size_t)n * n; + struct Planet_Params *p = &w->planet; + + hf_alloc(hf, n, rf->cell_m); + if (!hf_ok(hf)) { hydro_free(hf); return; } + hf->month_days = p->year_days / HYDRO_MONTHS; + + struct Month_Tab mt; + memset(&mt, 0, sizeof(mt)); + month_tab_build(&mt, w); + if (mt.wt == NULL) { month_tab_free(&mt); hydro_free(hf); return; } + const int bands = mt.bands; + + // 临时量:全部量化成 uint8/float,否则光是这些中间量就要 200MB + uint8_t *local_q = malloc(nn * HYDRO_MONTHS); // 本地径流形状 + uint8_t *teq = malloc(nn * HYDRO_MONTHS); // 水体平衡温度 + float *relax = malloc(sizeof(float) * nn); // 沿程热松弛因子 + float *vel = malloc(sizeof(float) * nn); // 流速(算汇流时间用) + float *t_ann = malloc(sizeof(float) * nn); // 年均气温(凌汛判据用) + float *mflow = malloc(sizeof(float) * nn); // 月均流量(m^3/s) + if (!local_q || !teq || !relax || !vel || !t_ann || !mflow) { + free(local_q); free(teq); free(relax); free(vel); free(t_ann); + free(mflow); + month_tab_free(&mt); hydro_free(hf); return; + } + + double swe_glob = 0.0, swe_max = 0.0; + double swe_cnt = 0.0; + double swem[HYDRO_MONTHS], soilm[HYDRO_MONTHS]; + double runoff[HYDRO_MONTHS]; + double P[HYDRO_MONTHS], T[HYDRO_MONTHS], pet[HYDRO_MONTHS]; + + // ---- 第一遍:逐格水量平衡 + 水体平衡温度 ---- + for (size_t i = 0; i < nn; i++) { + int cx = (int)(i % (size_t)n), cy = (int)(i / (size_t)n); + double wx = ((double)cx + 0.5) * rf->cell_m; + double wy = ((double)cy + 0.5) * rf->cell_m; + double elev = rf->elev[i]; + bool ocean = elev < 0.0; + bool lake = rf->lake_depth[i] > 0.0f; + bool chan = rf->width[i] > 0.0f; + hf->is_water[i] = (ocean || lake || chan) ? 1 : 0; + + struct Climate_Sample cs; + climate_sample(&w->climate, w->seed, wx, wy, elev, &cs); + t_ann[i] = (float)cs.temperature; + + // 月降水:年均降水按"雨带随太阳迁移 × 季风重分配"分配到 12 个月。 + // 归一化保证 12 个月加起来还是那个年均值——季风是**重新分配**水, + // 不是凭空造水(否则季风会往全球水量里加账,河流流量全部偏大)。 + double wsum = 0.0, pw[HYDRO_MONTHS]; + for (int m = 0; m < HYDRO_MONTHS; m++) { + double raw = climate_precip_at(&w->climate, wx, + wy + mt.shift_y[m]); + pw[m] = raw * tab_band(mt.wt, m, bands, wy); + if (pw[m] < 0.0) pw[m] = 0.0; + wsum += pw[m]; + } + for (int m = 0; m < HYDRO_MONTHS; m++) { + P[m] = (wsum > 1e-9) ? cs.precip_mm * pw[m] / wsum + : cs.precip_mm / HYDRO_MONTHS; + hf->precip[i * HYDRO_MONTHS + m] = enc_mm(P[m]); + double sp = tab_band(mt.sp_air, m, bands, wy); + T[m] = cs.temperature + cs.seasonal_amplitude * sp; + pet[m] = climate_pet_mm(T[m]) * mt.days / 365.2422; + } + + double r_ann = 0.0, r_sum = 0.0; + if (ocean) { + for (int m = 0; m < HYDRO_MONTHS; m++) { + hf->swe[i * HYDRO_MONTHS + m] = 0; + hf->soil[i * HYDRO_MONTHS + m] = enc_f(1.0); + runoff[m] = 0.0; + } + } else { + cell_balance(P, T, pet, mt.days, runoff, swem, soilm); + for (int m = 0; m < HYDRO_MONTHS; m++) { + hf->swe[i * HYDRO_MONTHS + m] = enc_swe(swem[m]); + hf->soil[i * HYDRO_MONTHS + m] = enc_f(soilm[m] / SOIL_CAP_MM); + swe_glob += swem[m]; + swe_cnt += 1.0; + if (swem[m] > swe_max) swe_max = swem[m]; + r_sum += runoff[m]; + } + r_ann = climate_runoff_mm(cs.precip_mm, cs.temperature); + } + + // 本地径流形状:月径流 / 月均径流。乘以月均流量就是该格的月流量。 + // 年总量锚在已标定的 Budyko 径流上,季节分配才是这一层新加的。 + // 形状按**本格的年径流总量**归一化,而不是按桶模型的年总量: + // 简单水桶的年径流比 Budyko 少一个量级(土壤把水都存住了), + // 那是年总量的偏差,不该污染季节分配。所以这里只取桶模型的 + // **形状**,年总量仍然锚在已标定的 Budyko 径流上。 + mflow[i] = (float)(r_ann * 0.001 * rf->cell_area / + SEC_PER_YEAR_H / HYDRO_MONTHS); + for (int m = 0; m < HYDRO_MONTHS; m++) { + double ratio = (r_sum > 1e-9) + ? runoff[m] * HYDRO_MONTHS / r_sum : 0.0; + local_q[i * HYDRO_MONTHS + m] = enc_q(ratio); + } + + double amp_w = ocean ? WATER_AMP_OCEAN : (lake ? WATER_AMP_LAKE + : WATER_AMP_RIVER); + const double *spt = ocean ? mt.sp_oce : (lake ? mt.sp_lak : mt.sp_riv); + for (int m = 0; m < HYDRO_MONTHS; m++) { + double sp = tab_band(spt, m, bands, wy); + teq[i * HYDRO_MONTHS + m] = enc_t( + cs.temperature + cs.seasonal_amplitude * amp_w * sp); + } + + // 热松弛因子 exp(-Δt/τ),τ = K·H。H 取混合层厚度: + // 河道 = 水深,湖泊/海洋 = 深水(完全混合),坡面流 = 几厘米 + double H; + if (ocean) H = 40.0; + else if (lake) H = rf->lake_depth[i] > 1.0f ? rf->lake_depth[i] : 1.0; + else if (chan && rf->depth[i] > 0.0f) + H = rf->depth[i] < WATER_H_EFF_MAX ? rf->depth[i] : WATER_H_EFF_MAX; + else H = 0.05; + double q = rf->discharge[i] > 0.0f ? rf->discharge[i] : 1.0; + double v = 0.0; + if (!ocean && chan && rf->depth[i] > 0.0f) + v = q / ((double)rf->width[i] * rf->depth[i]); + if (v < 0.02) v = 0.02; + vel[i] = ocean ? 0.02f : (float)v; + // 风速:行星风带的归一化矢量乘 6 m/s(和天气层一致) + double U = 6.0 * sqrt(cs.wind_x * cs.wind_x + cs.wind_y * cs.wind_y); + double k_ex = WATER_K_BASE + WATER_K_WIND * U; + double tau = WATER_THERM_NUM * H / k_ex; + double dt_sec = rf->cell_m / v; + double f = (ocean || lake) ? 0.0 : exp(-dt_sec / tau); + relax[i] = (float)hc(f, 0.0, 1.0); + } + + compute_travel(hf, rf, vel); + + // ---- 第二遍:按月沿水系汇流 ---- + // 每个月独立累加:上游产流按流量加权混合成下游的水温,再向当地 + // 平衡温度松弛。所以"上游来水"是真的被带下去的,不是按当地气温硬算。 + double *qacc = calloc(nn, sizeof(double)); + double *qtacc = calloc(nn, sizeof(double)); + if (qacc == NULL || qtacc == NULL) { + free(qacc); free(qtacc); + free(local_q); free(teq); free(relax); free(vel); free(t_ann); + free(mflow); + month_tab_free(&mt); hydro_free(hf); return; + } + + for (int m = 0; m < HYDRO_MONTHS; m++) { + for (size_t i = 0; i < nn; i++) { + double qc = dec_q(local_q[i * HYDRO_MONTHS + m]) * (double)mflow[i]; + double te = dec_t(teq[i * HYDRO_MONTHS + m]); + if (rf->elev[i] < 0.0) { + qacc[i] = 0.0; qtacc[i] = 0.0; + hf->wtemp[i * HYDRO_MONTHS + m] = enc_t(te); + continue; + } + qacc[i] = qc; + qtacc[i] = qc * te; + } + for (int t = rf->topo_count - 1; t >= 0; t--) { + int c = rf->topo[t]; + if (rf->elev[c] < 0.0) continue; + double qc = qacc[c]; + double te = dec_t(teq[(size_t)c * HYDRO_MONTHS + m]); + if (qc <= 0.0) { + hf->wtemp[(size_t)c * HYDRO_MONTHS + m] = enc_t(te); + continue; + } + double tout = te + (qtacc[c] / qc - te) * relax[c]; + hf->wtemp[(size_t)c * HYDRO_MONTHS + m] = enc_t(tout); + int j = rf->down[c]; + if (j >= 0 && rf->elev[j] >= 0.0) { + qacc[j] += qc; + qtacc[j] += qc * tout; + } + } + for (size_t i = 0; i < nn; i++) { + // qacc 是**单月**流量,q_shape 要的是"当月 / 年均", + // 所以除了 12(月均 = 年均/12)。 + double ann = rf->discharge[i]; + double r = (ann > 1e-6) ? qacc[i] * HYDRO_MONTHS / ann : 0.0; + hf->q_shape[i * HYDRO_MONTHS + m] = enc_q(r); + } + } + free(qacc); + free(qtacc); + + // ---- 洪峰滞后:整条流域的过程线按平均汇流时间后移 ---- + // 40km 的格子自己只有几小时,但一条大河的洪峰从源头走到河口要一两个月, + // 这个位移就是"下游汛期比上游晚"的来源。 + { + double mdays = hf->month_days; + for (size_t i = 0; i < nn; i++) { + double shift = hf->lag_days[i] / mdays; + if (shift < 0.02) continue; + uint8_t qs[HYDRO_MONTHS], ws[HYDRO_MONTHS]; + memcpy(qs, &hf->q_shape[i * HYDRO_MONTHS], HYDRO_MONTHS); + memcpy(ws, &hf->wtemp[i * HYDRO_MONTHS], HYDRO_MONTHS); + // 水温的滞后只取 30 天上限:热量不是被动示踪物,河水一边流 + // 一边和空气换热,热信号的记忆只有几百公里(约几周),跟 + // "洪峰走完全流域"的时间尺度不是一回事。 + double shift_wt = hf->lag_days[i] > THERM_LAG_MAX_D + ? THERM_LAG_MAX_D : hf->lag_days[i]; + shift_wt /= mdays; + for (int m = 0; m < HYDRO_MONTHS; m++) { + int a, b; double tm; + month_idx((double)m - shift, &a, &b, &tm); + hf->q_shape[i * HYDRO_MONTHS + m] = + enc_q(dec_q(qs[a]) * (1.0 - tm) + dec_q(qs[b]) * tm); + month_idx((double)m - shift_wt, &a, &b, &tm); + hf->wtemp[i * HYDRO_MONTHS + m] = + enc_t(dec_t(ws[a]) * (1.0 - tm) + dec_t(ws[b]) * tm); + } + } + } + + // ---- 冰情:从水温序列积分出冰厚,并回写给地貌层 ---- + { + double water_cnt = 0.0, ice_cnt = 0.0; + for (size_t i = 0; i < nn; i++) { + if (!hf->is_water[i]) { rf->ice_thick[i] = 0.0f; + rf->jam_risk[i] = 0.0f; continue; } + water_cnt += 1.0; + + double ice[HYDRO_MONTHS]; + int m_warm = 0; + ice_series(&hf->wtemp[i * HYDRO_MONTHS], hf->month_days, + ice, &m_warm); + + double imax = 0.0; + int m_max = 0; + for (int m = 0; m < HYDRO_MONTHS; m++) + if (ice[m] > imax) { imax = ice[m]; m_max = m; } + rf->ice_thick[i] = (float)imax; + + if (imax < ICE_MIN_M) { + hf->freeze_m[i] = -1; + hf->break_m[i] = -1; + rf->jam_risk[i] = 0.0f; + continue; + } + ice_cnt += 1.0; + + // 封冻:冰最厚的月份往前找,冰厚第一次越过阈值的那一月 + int mf = m_max; + for (int k = 1; k <= HYDRO_MONTHS; k++) { + int m = (m_max - k + HYDRO_MONTHS * 2) % HYDRO_MONTHS; + if (ice[m] >= ICE_MIN_M) mf = m; + else break; + } + // 开河:冰最厚之后第一次掉回阈值以下 + int mb = m_max; + for (int k = 1; k <= HYDRO_MONTHS; k++) { + int m = (m_max + k) % HYDRO_MONTHS; + if (ice[m] < ICE_MIN_M) { mb = m; break; } + mb = m; + } + hf->freeze_m[i] = (int8_t)mf; + hf->break_m[i] = (int8_t)mb; + + // 凌汛的静态部分:下游年均温更低(河流从暖纬度流向冷纬度) + // 而且流量够大,才可能壅冰成坝。黄河内蒙古段、松花江、勒拿河 + // 都是这个成因。开河的"时机"部分在采样时按冰厚变化现算。 + double dT = 0.0; + int j = (int)i; + for (int k = 0; k < 10 && j >= 0; k++) j = rf->down[j]; + if (j >= 0) dT = (double)t_ann[i] - (double)t_ann[j]; + double qf = hc(rf->discharge[i] / JAM_Q_REF, 0.0, 1.0); + rf->jam_risk[i] = (float)(hc(dT / JAM_DT_REF, 0.0, 1.0) * qf); + } + hf->ice_area_frac = water_cnt > 0.0 ? ice_cnt / water_cnt : 0.0; + } + + // ---- 结冰期水温封顶 ---- + // 冰盖一旦形成,冰下的水就不可能继续降温——水的密度极大值在 4℃、 + // 冰点是 0℃。水温序列是"辐射平衡温度",它可以是 -9℃;但真实水体 + // 的温度会被冰盖钉在冰点附近,多出来的冷量全部用在长冰上(就是 + // Stefan 定律里那个冻结指数)。所以这里把结冰月份的水温封顶。 + for (size_t i = 0; i < nn; i++) { + if (!hf->is_water[i]) continue; + double ice[HYDRO_MONTHS]; + ice_series(&hf->wtemp[i * HYDRO_MONTHS], hf->month_days, ice, NULL); + bool ocean = rf->elev[i] < 0.0; + double t_freeze = ocean ? -1.8 : 0.1; + for (int m = 0; m < HYDRO_MONTHS; m++) { + if (ice[m] < ICE_MIN_M) continue; + // 有冰时水温**不能低于冰点**:多出来的冷量全用在长冰上了, + // 所以是向上夹紧(max),不是向下夹紧。 + double t = dec_t(hf->wtemp[i * HYDRO_MONTHS + m]); + if (t < t_freeze) hf->wtemp[i * HYDRO_MONTHS + m] = enc_t(t_freeze); + } + } + + // ---- 水温年均值回写给地貌层 ---- + for (size_t i = 0; i < nn; i++) { + double s = 0.0; + for (int m = 0; m < HYDRO_MONTHS; m++) + s += dec_t(hf->wtemp[i * HYDRO_MONTHS + m]); + rf->water_temp[i] = (float)(s / HYDRO_MONTHS); + } + + // ---- 潮汐:水深放大 + 海盆随机 ---- + { + float *depth = malloc(sizeof(float) * nn); + float *tmp = malloc(sizeof(float) * nn); + if (depth && tmp) { + for (size_t i = 0; i < nn; i++) + depth[i] = rf->elev[i] < 0.0 ? (float)(-rf->elev[i]) : 0.0f; + const int R = TIDE_SHELF_R; + for (int y = 0; y < n; y++) { + for (int x = 0; x < n; x++) { + double s = 0.0; int c = 0; + for (int d = -R; d <= R; d++) { + float v = depth[y * n + hwrap_x(x + d, n)]; + if (v > 0.0f) { s += v; c++; } + } + tmp[y * n + x] = c ? (float)(s / c) : 0.0f; + } + } + for (int x = 0; x < n; x++) { + for (int y = 0; y < n; y++) { + double s = 0.0; int c = 0; + for (int d = -R; d <= R; d++) { + int yy = y + d; + if (yy < 0 || yy >= n) continue; + float v = tmp[yy * n + x]; + if (v > 0.0f) { s += v; c++; } + } + size_t i = (size_t)y * n + x; + if (c == 0) { hf->tidal_range[i] = 0.0f; continue; } + double shelf = s / c; + double wx = ((double)x + 0.5) * rf->cell_m; + double wy = ((double)y + 0.5) * rf->cell_m; + double basin = 0.45 + 1.95 * fractal_noise( + w->seed, HYDRO_NOISE_TIDE, wx, wy, 3.0e6, 3, 0.5); + double amp = TIDE_BASE_M * basin * + pow(TIDE_DEPTH_REF / shelf, TIDE_DEPTH_EXP); + hf->tidal_range[i] = + (float)hc(amp, TIDE_RANGE_MIN, TIDE_RANGE_MAX); + // 潮型因子 (K1+O1)/(M2+S2):真实海洋里半日潮占多数, + // 但有些海盆是全日潮(墨西哥湾、南海)。给一个海盆 + // 尺度的随机场,平方一下让半日潮占多数。 + double n2 = fractal_noise(w->seed, HYDRO_NOISE_TIDE + 1, + wx, wy, 6.0e6, 2, 0.6); + double form = 0.04 + 5.0 * pow(n2, 5.0); + hf->tidal_form[i] = (uint8_t)hc(form * 64.0, 0.0, 255.0); + } + } + } + free(depth); + free(tmp); + } + + hf->mean_swe_mm = swe_cnt > 0.0 ? swe_glob / swe_cnt : 0.0; + hf->max_swe_mm = swe_max; + + free(local_q); + free(teq); + free(relax); + free(vel); + free(t_ann); + free(mflow); + month_tab_free(&mt); +} + +// =============================================================== +// 采样 +// =============================================================== + +double hydro_snow_cover(double swe_mm) { + if (!(swe_mm > 0.0)) return 0.0; + return hc(swe_mm / (swe_mm + 10.0), 0.0, 1.0); +} + +static double hf_at(const struct Hydro_Field *hf, const uint8_t *f, + double wx, double wy, double xm, dec_fn dec) { + const int n = hf->n; + double fx = wx / hf->cell_m - 0.5; + double fy = wy / hf->cell_m - 0.5; + int ix = (int)floor(fx), iy = (int)floor(fy); + double tx = fx - ix, ty = fy - iy; + int y0 = iy < 0 ? 0 : (iy >= n ? n - 1 : iy); + int y1 = iy + 1 < 0 ? 0 : (iy + 1 >= n ? n - 1 : iy + 1); + int x0 = hwrap_x(ix, n), x1 = hwrap_x(ix + 1, n); + + int m0, m1; double tm; + month_idx(xm, &m0, &m1, &tm); + + double a0 = dec(f[((size_t)y0 * n + x0) * HYDRO_MONTHS + m0]) * (1.0 - tx) + + dec(f[((size_t)y0 * n + x1) * HYDRO_MONTHS + m0]) * tx; + double a1 = dec(f[((size_t)y1 * n + x0) * HYDRO_MONTHS + m0]) * (1.0 - tx) + + dec(f[((size_t)y1 * n + x1) * HYDRO_MONTHS + m0]) * tx; + double a = a0 * (1.0 - ty) + a1 * ty; + + double b0 = dec(f[((size_t)y0 * n + x0) * HYDRO_MONTHS + m1]) * (1.0 - tx) + + dec(f[((size_t)y0 * n + x1) * HYDRO_MONTHS + m1]) * tx; + double b1 = dec(f[((size_t)y1 * n + x0) * HYDRO_MONTHS + m1]) * (1.0 - tx) + + dec(f[((size_t)y1 * n + x1) * HYDRO_MONTHS + m1]) * tx; + double b = b0 * (1.0 - ty) + b1 * ty; + + return a * (1.0 - tm) + b * tm; +} + +static size_t hf_cell(const struct Hydro_Field *hf, double wx, double wy) { + int cx = (int)floor(wx / hf->cell_m); + int cy = (int)floor(wy / hf->cell_m); + if (cy < 0) cy = 0; + if (cy >= hf->n) cy = hf->n - 1; + return (size_t)cy * hf->n + hwrap_x(cx, hf->n); +} + +void hydro_sample(struct World *w, double wx, double wy, double elevation, + double t_seconds, struct Hydro_Sample *out) { + memset(out, 0, sizeof(*out)); + out->freeze_month = -1; + out->break_month = -1; + if (w == NULL || w->hydro == NULL) return; + struct Hydro_Field *hf = w->hydro; + struct River_Field *rf = w->rivers; + if (hf->n == 0) return; + struct Planet_Params *p = &w->planet; + + bool annual = (t_seconds < 0.0); + double xm = 0.0; + if (!annual) { + struct Game_Time gt = game_time_at(t_seconds); + double doy = astro_day_of_year(p, >); + xm = doy / p->year_days * HYDRO_MONTHS - 0.5; + } + + if (annual) { + double s[5] = {0, 0, 0, 0, 0}; + for (int m = 0; m < HYDRO_MONTHS; m++) { + s[0] += hf_at(hf, hf->precip, wx, wy, m, dec_mm); + s[1] += hf_at(hf, hf->swe, wx, wy, m, dec_swe); + s[2] += hf_at(hf, hf->soil, wx, wy, m, dec_f); + s[3] += hf_at(hf, hf->wtemp, wx, wy, m, dec_t); + s[4] += hf_at(hf, hf->q_shape,wx, wy, m, dec_q); + } + out->precip_mm = s[0] / HYDRO_MONTHS; + out->swe_mm = s[1] / HYDRO_MONTHS; + out->soil_moist = s[2] / HYDRO_MONTHS; + out->water_temp = s[3] / HYDRO_MONTHS; + out->q_ratio = s[4] / HYDRO_MONTHS; + } else { + out->precip_mm = hf_at(hf, hf->precip, wx, wy, xm, dec_mm); + out->swe_mm = hf_at(hf, hf->swe, wx, wy, xm, dec_swe); + out->soil_moist = hf_at(hf, hf->soil, wx, wy, xm, dec_f); + out->water_temp = hf_at(hf, hf->wtemp, wx, wy, xm, dec_t); + out->q_ratio = hf_at(hf, hf->q_shape,wx, wy, xm, dec_q); + } + out->snow_cover = hydro_snow_cover(out->swe_mm); + + struct Climate_Sample cs; + climate_sample(&w->climate, w->seed, wx, wy, elevation, &cs); + if (annual) { + out->air_temp = cs.temperature; + out->pet_mm = climate_pet_mm(cs.temperature) / HYDRO_MONTHS; + } else { + struct Weather_Field *wf = &w->weather; + double sp = weather_season_phase(wf, p, wy, + t_seconds - WATER_LAG_AIR * p->day_seconds); + out->air_temp = cs.temperature + cs.seasonal_amplitude * sp; + out->pet_mm = climate_pet_mm(out->air_temp) * hf->month_days / 365.2422; + } + + size_t ci = hf_cell(hf, wx, wy); + out->tidal_range = hf->tidal_range[ci]; + out->tidal_form = hf->tidal_form[ci] / 64.0; + out->lag_days = hf->lag_days[ci]; + out->freeze_month = hf->freeze_m[ci] < 0 ? -1 : hf->freeze_m[ci]; + out->break_month = hf->break_m[ci] < 0 ? -1 : hf->break_m[ci]; + + double lake_depth = rf ? rf->lake_depth[ci] : 0.0; + bool is_water = hf->is_water[ci] != 0; + if (rf) out->discharge = rf->discharge[ci] * out->q_ratio; + + // 深层水温:越深越接近年均温(湖下层、海洋次表层都是这个道理) + double depth_for_strat = lake_depth > 0.0 ? lake_depth + : (elevation < 0.0 ? 50.0 : 0.0); + out->water_temp_deep = cs.temperature + + (out->water_temp - cs.temperature) * exp(-depth_for_strat / + LAKE_STRAT_SCALE); + out->stratified = (out->water_temp - out->water_temp_deep) > 1.0 || + (out->water_temp_deep - out->water_temp) > 1.0; + + // 冰情:只有水面才结冰。干地面上"水温低于 0"不是冰,是冻土。 + if (!annual && is_water) { + // 注意:水温在结冰期被冰点封过顶,直接用它会算不出冻结指数。 + // 冰厚序列在建表时就已经存好了封冻/开河月,这里用它们重建 + // "当前的冰厚"——封冻期按 Stefan 曲线在 0 和年最大值之间插值。 + out->freeze_month = hf->freeze_m[ci] < 0 ? -1 : hf->freeze_m[ci]; + out->break_month = hf->break_m[ci] < 0 ? -1 : hf->break_m[ci]; + if (out->freeze_month >= 0 && out->break_month >= 0) { + int fm = out->freeze_month, bm = out->break_month; + double span = bm - fm; if (span < 0) span += HYDRO_MONTHS; + double x = xm - fm; if (x < 0) x += HYDRO_MONTHS; + double imax = rf ? rf->ice_thick[ci] : 0.0; + if (x < span) { + // 增长快、消融更快(冰面反照率低于雪面) + double u = x / (span > 1e-6 ? span : 1.0); + double shape = (u < 0.65) ? sqrt(u / 0.65) + : sqrt((1.0 - u) / 0.35); + out->ice_thick = imax * hc(shape, 0.0, 1.0); + double span_m = span > 1e-6 ? span : 1.0; + // m/月:增长段慢、消融段快 + out->ice_trend = (u < 0.65) ? imax / (0.65 * span_m) + : -imax / (0.35 * span_m); + out->ice_days = span * hf->month_days; + } else { + out->ice_thick = 0.0; + out->ice_trend = 0.0; + out->ice_days = span * hf->month_days; + } + } + } + + // 凌汛:只有开河期才拉高。判据是"冰还厚 + 正在快速变薄 + 下游可能 + // 还封着"——冰坝洪水就是这么来的。 + if (out->ice_thick > 0.0 && out->ice_trend < 0.0) { + double jam_geom = rf ? (double)rf->jam_risk[ci] : 0.0; + double thaw = hc(-out->ice_trend / (JAM_THAW_REF * hf->month_days), + 0.0, 1.0); + out->jam_risk = jam_geom * thaw; + } +} diff --git a/src/hydro.h b/src/hydro.h new file mode 100644 index 0000000..fa9b4ea --- /dev/null +++ b/src/hydro.h @@ -0,0 +1,106 @@ +#ifndef HYDRO_H +#define HYDRO_H + +#include +#include +#include "terrain.h" + +struct World; + +// =============================================================== +// 季节水文 / 水体热力层 +// =============================================================== +// 气候层给的是**年均值**,天气层把它们展开成 t 的函数。但有两类量 +// 不能只靠"当前时刻的环境"算出来,它们有**记忆**: +// +// 积雪 —— 冬天存下来的水,要等春天才化出来 +// 土壤水 —— 下过雨之后还能撑多久不干 +// 水温 —— 水的热惯量,以及上游把冷水/暖水带下来 +// 河冰 —— 一个冬天积起来的冰,开河要看它化得多快 +// +// 这些量的正确做法是随时间积分。所以这一层在 40km 水文网格上做一次 +// 月步长的演算(12 个月循环到周期性稳定),得到每一格**全年 12 个月** +// 的序列,采样时按月插值。 +// +// 这一层同时解决"水从哪来、什么时候来"的问题: +// 月降水(雨带随太阳南北迁移 + 季风重分配) +// -> 积雪/融雪 + 土壤水桶 -> 月径流 +// -> 沿水系汇流(带行程时间滞后)-> 12 个月的水文过程线 +// +// 于是"汛期/枯水期"不是写死的常数,而是从降水季节性和流域汇流时间 +// 里自然出来的:融雪河春汛、季风河夏汛、大河洪峰比源头晚一两个月。 +// --------------------------------------------------------------- + +#define HYDRO_MONTHS 12 + +// 一次采样得到的当月水文/热力状态 +struct Hydro_Sample { + // ---- 水量平衡 ---- + double precip_mm; // 当月降水 mm + double pet_mm; // 当月潜在蒸散 mm + double swe_mm; // 雪水当量 mm + double snow_cover; // 积雪覆盖率 0..1 + double soil_moist; // 土壤含水 0..1(占田间持水量) + double air_temp; // 当月平均气温 ℃ + + // ---- 水温与冰 ---- + double water_temp; // 当月表层水温 ℃ + double water_temp_deep;// 深层水温(湖泊下层 / 海洋次表层)℃ + bool stratified; // 是否分层(湖泊夏/冬分层) + double ice_thick; // 当月冰厚 m + double ice_trend; // 冰厚变化 m/月,>0 结冰、<0 开河 + double ice_days; // 年封冻天数 + int freeze_month; // 开始封冻的月份 0..11,-1 = 全年不冻 + int break_month; // 开河月份 0..11,-1 = 全年不冻 + double jam_risk; // 凌汛(冰坝)风险 0..1,只在开河期拉高 + + // ---- 流量 ---- + double q_ratio; // 当月流量 / 年均流量 + double discharge; // 当月流量 m^3/s + double lag_days; // 流域平均汇流时间(天) + + // ---- 潮汐 ---- + double tidal_range; // 该点平均潮差 m(地理放大后) + double tidal_form; // 潮型因子 (K1+O1)/(M2+S2):<0.25 半日潮,>1.5 全日潮 +}; + +struct Hydro_Field { + int n; + double cell_m; + double cell_area; + double month_days; // 一个月的天数 = 年长/12 + + // 12 个月的序列,每格 12 字节。编码见 hydro.c 顶部的 enc_*/dec_*。 + // 这五张表就是"各种数据随时间变化"在空间上的完整答案: + // 采样时按月插值,任何时刻任何地点都能取到。 + uint8_t *q_shape; // 流量 / 年均流量,1/32 + uint8_t *wtemp; // 水温 ℃,(T+60)*2 + uint8_t *swe; // 雪水当量,10mm + uint8_t *precip; // 月降水,sqrt 刻度到 1500mm + uint8_t *soil; // 土壤含水 0..1 + uint8_t *is_water; // 该格是不是水面(海/湖/河道) + int8_t *freeze_m; // 封冻起始月,-1 = 不冻 + int8_t *break_m; // 开河月,-1 = 不冻 + + float *tidal_range; // 平均潮差 m + uint8_t *tidal_form; // 潮型因子 ×64 + float *lag_days; // 汇流时间(天) + + // 诊断 + double mean_swe_mm; // 陆地平均雪水当量(mm) + double max_swe_mm; + double ice_area_frac; // 有冰水面占比 +}; + +void hydro_build(struct Hydro_Field *hf, struct World *w); +void hydro_free(struct Hydro_Field *hf); + +// 采样某点当月的水文/热力状态。t_seconds < 0 表示取年均值。 +// elevation 传该点地形高程(海洋为负)。需要 w->rivers(流量、河宽水深、湖深)。 +void hydro_sample(struct World *w, double wx, double wy, double elevation, + double t_seconds, struct Hydro_Sample *out); + +// 积雪覆盖率:从雪水当量推(消融期的斑块状衰减) +double hydro_snow_cover(double swe_mm); + +#endif diff --git a/src/landing.c b/src/landing.c new file mode 100644 index 0000000..e18db32 --- /dev/null +++ b/src/landing.c @@ -0,0 +1,857 @@ +#include "landing.h" +#include "chunk.h" +#include "compound.h" +#include "climate.h" +#include "river.h" +#include "weather.h" +#include "astro.h" +#include "map.h" + +#include +#include +#include +#include +#include + +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + +// =============================================================== +// 资源判据 +// =============================================================== +// 铁/铜/煤各自包含哪些化合物。判定用**归一化后的占比之和**: +// 占比是"这块石头里有多大比例是这种矿",和"地壳整体含铁多少"这种背景 +// 无关,正好是"这里算不算一处矿"。 +// +// 黄铁矿 (FeS2) 和磁黄铁矿**不算**铁矿:它们是硫矿,炼铁不用。 +// 赤铁矿/磁铁矿/针铁矿/菱铁矿才是真正的铁矿石。 + +static const enum Compound_Id IRON_IDS[] = { + CP_HEMATITE, CP_MAGNETITE, CP_GOETHITE, CP_SIDERITE +}; +static const enum Compound_Id COPPER_IDS[] = { + CP_CHALCOPYRITE, CP_BORNITE, CP_CHALCOCITE, CP_COVELLITE, CP_CUPRITE, + CP_TENORITE, CP_MALACHITE, CP_AZURITE, CP_CHRYSOCOLLA +}; +static const enum Compound_Id COAL_IDS[] = { CP_COAL }; + +#define N_IRON ((int)(sizeof(IRON_IDS) / sizeof(IRON_IDS[0]))) +#define N_COPPER ((int)(sizeof(COPPER_IDS) / sizeof(COPPER_IDS[0]))) +#define N_COAL ((int)(sizeof(COAL_IDS) / sizeof(COAL_IDS[0]))) + +static double group_sum(const struct Tile *t, const enum Compound_Id *ids, int n) { + double s = 0.0; + for (int i = 0; i < n; i++) s += t->compound[ids[i]]; + return s; +} + +static double ld_clamp(double x, double lo, double hi) { + return x < lo ? lo : (x > hi ? hi : x); +} + +static double ld_wrap_x(double wx) { + double w = (double)WORLD_W; + wx = fmod(wx, w); + if (wx < 0.0) wx += w; + return wx; +} + +// 从 a 到 b 的最短位移(x 方向环绕) +static double ld_wrap_dx(double ax, double bx) { + double d = bx - ax; + double w = (double)WORLD_W; + if (d > w * 0.5) d -= w; + if (d < -w * 0.5) d += w; + return d; +} + +static int cmp_double(const void *a, const void *b) { + double x = *(const double *)a, y = *(const double *)b; + return (x < y) ? -1 : (x > y) ? 1 : 0; +} + +// 一个点的三种品位。tile_sample 会算全部 104 种化合物(约 18us), +// 细查预算里这是唯一的大头,所以调用次数要克制。 +struct Grades { double iron, copper, coal; }; + +static struct Grades grades_of(const struct Tile *t) { + struct Grades g; + g.iron = group_sum(t, IRON_IDS, N_IRON); + g.copper = group_sum(t, COPPER_IDS, N_COPPER); + g.coal = group_sum(t, COAL_IDS, N_COAL); + return g; +} + +// =============================================================== +// 品位阈值标定 +// =============================================================== +// "什么算一处矿"不能拍死:创建世界时的 ore_abundance / difficulty / +// realism 会把整个品位分布平移又缩放。所以直接在这个世界里撒点,取 p88 +// —— "排进前 12% 的富集区"就是这个世界的矿点。 +// +// 只在陆地、非冰盖上撒:海洋的"品位"没有意义,混进来会把阈值压低。 + +static void calibrate(struct World *w, int samples, + double *thr_iron, double *thr_copper, double *thr_coal) { + if (samples < 32) samples = 32; + double *fe = malloc(sizeof(double) * (size_t)samples); + double *cu = malloc(sizeof(double) * (size_t)samples); + double *co = malloc(sizeof(double) * (size_t)samples); + if (fe == NULL || cu == NULL || co == NULL) { + free(fe); free(cu); free(co); + *thr_iron = 0.12; *thr_copper = 0.036; *thr_coal = 0.012; + return; + } + + int n = 0, tries = 0; + const int max_tries = samples * 16; + while (n < samples && tries < max_tries) { + tries++; + // 完全确定的撒点(同一个种子结果一样):两个无理数比例避免成行成列 + double x = ld_wrap_x((double)tries * 0.6180339887498949 * (double)WORLD_W); + double y = fmod((double)tries * 0.7548776662466927, 1.0) * (double)WORLD_H; + if (fabs(climate_latitude(y)) > 78.0) continue; + struct Tile t; + memset(&t, 0, sizeof(t)); + tile_sample(&t, x, y, w); + if (t.elevation < 0.0) continue; + struct Grades g = grades_of(&t); + fe[n] = g.iron; cu[n] = g.copper; co[n] = g.coal; + n++; + } + if (n < 32) { + free(fe); free(cu); free(co); + *thr_iron = 0.12; *thr_copper = 0.036; *thr_coal = 0.012; + return; + } + + qsort(fe, (size_t)n, sizeof(double), cmp_double); + qsort(cu, (size_t)n, sizeof(double), cmp_double); + qsort(co, (size_t)n, sizeof(double), cmp_double); + int k = n * 88 / 100; + // 夹一下:矿少的世界别把阈值压到"处处都算矿",矿多的世界也别要求 + // 离谱的品位(否则选点会失败)。 + *thr_iron = ld_clamp(fe[k], 0.030, 0.30); + *thr_copper = ld_clamp(cu[k], 0.008, 0.12); + *thr_coal = ld_clamp(co[k], 0.002, 0.10); + free(fe); free(cu); free(co); +} + +// =============================================================== +// 季风带 +// =============================================================== +// 这个模型里季风由"海陆热力差的**季节异常**"驱动,而海陆比只随纬度变, +// 于是季风带是纬向均匀的(现实里还跟经度有关——印度季风和同纬度的 +// 撒哈拉完全不同——这里简化了)。所以按纬度带预计算一次就够。 + +static double monsoon_strength(struct World *w, double wy) { + struct Weather_Field *wf = &w->weather; + struct Planet_Params *p = &w->planet; + if (wf->bands <= 0) return 0.0; + double best = 0.0; + // 一年采 36 个点找峰值:季风有窗口(onset~retreat),采太稀会错过 + for (int k = 0; k < 36; k++) { + double t = (double)k / 36.0 * p->year_seconds; + double v = weather_monsoon_rain(wf, p, wy, t); + if (v > best) best = v; + } + return best; +} + +static void build_monsoon_bands(struct Landing_State *st, struct World *w) { + for (int b = 0; b < (int)WORLD_BLOCK_COUNT_Y; b++) { + double wy = ((double)b + 0.5) * (double)WORLD_BLOCK_SIZE; + if (wy > (double)WORLD_H) wy = (double)WORLD_H; + st->mons_band[b] = monsoon_strength(w, wy); + } +} + +static double monsoon_at(const struct Landing_State *st, double wy) { + double by = wy / (double)WORLD_BLOCK_SIZE - 0.5; + int iy = (int)floor(by); + double fy = by - iy; + if (iy < 0) { iy = 0; fy = 0.0; } + if (iy > (int)WORLD_BLOCK_COUNT_Y - 2) { + iy = (int)WORLD_BLOCK_COUNT_Y - 2; fy = 1.0; + } + return st->mons_band[iy] * (1.0 - fy) + st->mons_band[iy + 1] * fy; +} + +// =============================================================== +// 粗筛:40km 水文网格上找"在河边、河够大、季风、平坦"的格子 +// =============================================================== + +struct Cand { double wx, wy, score, q; }; + +// 对数正态打分:x 在 peak 附近给 1,偏离一个数量级就接近 0。 +// 河流量、年降水都跨好几个数量级,而且都是"适中最好",用它正合适。 +static double lognormal_score(double x, double peak, double sigma_decades) { + if (x <= 1e-9) return 0.0; + double d = (log10(x) - log10(peak)) / sigma_decades; + return exp(-0.5 * d * d); +} + +static int cmp_cand(const void *a, const void *b) { + const struct Cand *x = a, *y = b; + return (x->score < y->score) ? 1 : (x->score > y->score) ? -1 : 0; +} + +static int coarse_scan(struct Landing_State *st, struct World *w, + const struct Landing_Options *opt, + struct Cand *out, int out_cap) { + struct River_Field *rf = w->rivers; + if (rf == NULL || rf->n == 0) return 0; + + const int n = rf->n; + const double cm = rf->cell_m; + const double min_area = river_channel_min_area(rf); + int count = 0; + + for (int cy = 1; cy < n - 1; cy++) { + for (int cx = 0; cx < n; cx++) { + int i = cy * n + cx; + if (rf->elev[i] < 2.0) continue; // 河道要在陆地上 + if (rf->area[i] < (float)min_area) continue; // 要是真河道 + double q = rf->discharge[i]; + if (q < opt->min_river_q) continue; + + double wy = ((double)cy + 0.5) * cm; + double wx = ((double)cx + 0.5) * cm; + double mons = monsoon_at(st, wy); + if (mons < opt->min_monsoon) continue; + + // 雨季强度是**按纬度**算的,沙漠和高雨区一样高(见文件头的说明)。 + // 所以还要看年降水,否则会把基地选在撒哈拉。 + double precip = climate_precip_at(&w->climate, wx, wy); + if (precip < opt->min_precip_mm) continue; + + // 崎岖度:和周围 3x3 的平均高差。平坦才建得起基地。 + double e = rf->elev[i]; + double rough = 0.0; + for (int dy = -1; dy <= 1; dy++) { + for (int dx = -1; dx <= 1; dx++) { + int j = (cy + dy) * n + (((cx + dx) % n + n) % n); + rough += fabs(rf->elev[j] - e); + } + } + rough /= 9.0; + + // 河不是越大越好:这条世界的大河能到 5e5 m3/s(亚马逊的 5 倍), + // 站在那种河边没法建基地。300 m3/s 上下最舒服——能通航、能架桥、 + // 有像样的河谷平地。对数正态打分。 + double s_q = lognormal_score(q, 300.0, 0.75); + // 雨也不是越多越好:这个模型里年降水超过约 2000mm 生物群系就 + // 塌进 SWAMP(雨林/泥炭沼泽),既不缺林子也不适合开局。 + double s_p = lognormal_score(precip, 1200.0, 0.45); + + double score = 2.0 * mons + + 1.4 * s_q + + 1.6 * s_p + - 0.010 * rough + - 0.0004 * ld_clamp(e, 0.0, 3000.0); + + if (count < out_cap) { + out[count].wx = wx; out[count].wy = wy; + out[count].score = score; out[count].q = q; + count++; + } else { + int worst = 0; + for (int k = 1; k < out_cap; k++) + if (out[k].score < out[worst].score) worst = k; + if (score > out[worst].score) { + out[worst].wx = wx; out[worst].wy = wy; + out[worst].score = score; out[worst].q = q; + } + } + } + } + qsort(out, (size_t)count, sizeof(struct Cand), cmp_cand); + return count; +} + +// =============================================================== +// 细查 +// =============================================================== + +// 倒角距离变换:命中点距离 0,向八邻域传播,得到每格到最近命中点的 +// 近似欧氏距离。两遍扫描(前向 + 后向),误差 <2%。 +static void chamfer(const uint8_t *hit, double *dist, int nx, int ny, double step) { + const double d1 = step, d2 = step * 1.41421356; + const double INF = 1e18; + const int total = nx * ny; + for (int i = 0; i < total; i++) dist[i] = hit[i] ? 0.0 : INF; + + for (int y = 0; y < ny; y++) { + for (int x = 0; x < nx; x++) { + int i = y * nx + x; + double d = dist[i]; + if (x > 0) { double v = dist[i - 1] + d1; if (v < d) d = v; } + if (y > 0) { double v = dist[i - nx] + d1; if (v < d) d = v; } + if (x > 0 && y > 0) { double v = dist[i - nx - 1] + d2; if (v < d) d = v; } + if (x < nx - 1 && y > 0) { double v = dist[i - nx + 1] + d2; if (v < d) d = v; } + dist[i] = d; + } + } + for (int y = ny - 1; y >= 0; y--) { + for (int x = nx - 1; x >= 0; x--) { + int i = y * nx + x; + double d = dist[i]; + if (x < nx - 1) { double v = dist[i + 1] + d1; if (v < d) d = v; } + if (y < ny - 1) { double v = dist[i + nx] + d1; if (v < d) d = v; } + if (x < nx - 1 && y < ny - 1) { double v = dist[i + nx + 1] + d2; if (v < d) d = v; } + if (x > 0 && y < ny - 1) { double v = dist[i + nx - 1] + d2; if (v < d) d = v; } + dist[i] = d; + } + } +} + +struct Fine { + int nx, ny; + double *grade; // [LANDING_RES_COUNT][total] + double *dist; // [LANDING_RES_COUNT][total],到最近命中点 + uint8_t *hit; // [LANDING_RES_COUNT][total] + float *elev, *slope; + uint8_t *surface, *dry; +}; + +static void fine_alloc(struct Fine *f, int nx, int ny) { + size_t total = (size_t)nx * (size_t)ny; + memset(f, 0, sizeof(*f)); + f->nx = nx; f->ny = ny; + f->grade = malloc(sizeof(double) * total * LANDING_RES_COUNT); + f->dist = malloc(sizeof(double) * total * LANDING_RES_COUNT); + f->hit = malloc(total * LANDING_RES_COUNT); + f->elev = malloc(sizeof(float) * total); + f->slope = malloc(sizeof(float) * total); + f->surface = malloc(total); + f->dry = malloc(total); +} + +static bool fine_ok(const struct Fine *f) { + return f->grade && f->dist && f->hit && f->elev && f->slope && + f->surface && f->dry; +} + +static void fine_free(struct Fine *f) { + free(f->grade); free(f->dist); free(f->hit); + free(f->elev); free(f->slope); free(f->surface); free(f->dry); + memset(f, 0, sizeof(*f)); +} + +// 在一块 12km 见方的区域里找一个"五样都在 radius 内"的着陆点。 +// need = 必须满足的位掩码(LANDING_OK_*)。成功返回 true。 +static bool fine_search(struct Landing_State *st, struct World *w, + const struct Landing_Options *opt, + double cx, double cy, double q, + uint32_t need, struct Landing_Site *out) { + const int nx = opt->box_cells, ny = opt->box_cells; + const size_t total = (size_t)nx * (size_t)ny; + const double step = opt->box_step_m; + const double ox = cx - (double)(nx / 2) * step; + const double oy = cy - (double)(ny / 2) * step; + const double h = (double)WORLD_H; + + struct Fine f; + fine_alloc(&f, nx, ny); + if (!fine_ok(&f)) { fine_free(&f); return false; } + + double *g_fe = f.grade, *g_cu = f.grade + total, *g_co = f.grade + 2 * total; + uint8_t *h_fe = f.hit, *h_cu = f.hit + total, *h_co = f.hit + 2 * total; + uint8_t *h_forest = f.hit + 3 * total, *h_river = f.hit + 4 * total; + + for (int j = 0; j < ny; j++) { + double wy = oy + ((double)j + 0.5) * step; + if (wy < 1.0) wy = 1.0; + if (wy > h - 1.0) wy = h - 1.0; + for (int i = 0; i < nx; i++) { + double wx = ld_wrap_x(ox + ((double)i + 0.5) * step); + size_t k = (size_t)j * nx + i; + struct Tile t; + memset(&t, 0, sizeof(t)); + tile_sample(&t, wx, wy, w); + struct Grades g = grades_of(&t); + + g_fe[k] = g.iron; g_cu[k] = g.copper; g_co[k] = g.coal; + h_fe[k] = g.iron > st->thr_iron; + h_cu[k] = g.copper > st->thr_copper; + h_co[k] = g.coal > st->thr_coal; + // "有林子"= 森林 / 针叶林 / 沼泽林地。这个模型的生物群系里 + // 最湿的那一档(热带雨林、泥炭沼泽)落在 SWAMP 上,但那里 + // 照样有木材——所以不能只认 FOREST,否则雨林反而"没有森林"。 + h_forest[k] = (t.surface_type == SURFACE_FOREST || + t.surface_type == SURFACE_TAIGA || + t.surface_type == SURFACE_SWAMP); + h_river[k] = (t.river_depth > 0.0f); + + f.elev[k] = (float)t.elevation; + f.slope[k] = (float)t.slope; + f.surface[k] = t.surface_type; + // 能站人的干地:出水、不是湖、不在河道里(河面没有 water_depth, + // 只有 river_depth,所以必须单独排掉,否则会把人放在河中间)、 + // 坡度爬得上去 + f.dry[k] = (t.elevation > 0.0 && t.water_depth <= 0.20f && + t.river_depth <= 0.0f && t.slope <= 0.40) ? 1 : 0; + } + } + + const uint8_t *hits[LANDING_RES_COUNT]; + hits[LANDING_RES_IRON] = h_fe; + hits[LANDING_RES_COPPER] = h_cu; + hits[LANDING_RES_COAL] = h_co; + hits[LANDING_RES_FOREST] = h_forest; + hits[LANDING_RES_RIVER] = h_river; + for (int r = 0; r < LANDING_RES_COUNT; r++) + chamfer(hits[r], f.dist + (size_t)r * total, nx, ny, step); + + // 半径内各矿的最高品位(着陆点"能拿到"的矿) + double best_grade[LANDING_RES_COUNT] = {0, 0, 0, 0, 0}; + for (int r = 0; r < LANDING_RES_COUNT; r++) { + const double *g = f.grade + (size_t)r * total; + const double *d = f.dist + (size_t)r * total; + for (size_t k = 0; k < total; k++) + if (hits[r][k] && d[k] <= opt->radius_m && g[k] > best_grade[r]) + best_grade[r] = g[k]; + } + + const double mons = monsoon_at(st, cy); + const double out_q = q; + const double precip_site = climate_precip_at(&w->climate, cx, cy); + double best_score = -1e30; + long best_k = -1; + + for (size_t k = 0; k < total; k++) { + if (!f.dry[k]) continue; + bool ok = true; + for (int r = 0; r < LANDING_RES_COUNT; r++) { + if (!(need & (1u << r))) continue; // 这一轮不要求的就不筛 + if (f.dist[(size_t)r * total + k] > opt->radius_m) { ok = false; break; } + } + if (!ok) continue; + + // 综合分:靠水最重要(水是命脉),其次平坦、有林子、矿好、季风强 + double s_water = ld_clamp(1.0 - f.dist[(size_t)LANDING_RES_RIVER * total + k] / opt->radius_m, 0.0, 1.0); + double s_forest = ld_clamp(1.0 - f.dist[(size_t)LANDING_RES_FOREST * total + k] / opt->radius_m, 0.0, 1.0); + double s_flat = 1.0 - ld_clamp(f.slope[k] / 0.40, 0.0, 1.0); + double s_fe = ld_clamp(best_grade[0] / (st->thr_iron > 0 ? st->thr_iron : 1.0), 0.0, 4.0); + double s_cu = ld_clamp(best_grade[1] / (st->thr_copper > 0 ? st->thr_copper : 1.0), 0.0, 4.0); + double s_co = ld_clamp(best_grade[2] / (st->thr_coal > 0 ? st->thr_coal : 1.0), 0.0, 4.0); + + double score = 2.6 * s_water + 1.6 * s_flat + 1.0 * s_forest + + 0.55 * s_fe + 0.40 * s_cu + 0.35 * s_co + + 1.0 * mons + + 1.4 * lognormal_score(out_q, 300.0, 0.75) + + 1.6 * lognormal_score(precip_site, 1200.0, 0.45) + - 0.40 * ld_clamp((f.elev[k] - 500.0) / 1500.0, 0.0, 2.0); + if (score > best_score) { best_score = score; best_k = (long)k; } + } + + if (best_k < 0) { fine_free(&f); return false; } + + double lx = ld_wrap_x(ox + ((double)(best_k % nx) + 0.5) * step); + double ly = oy + ((double)(best_k / nx) + 0.5) * step; + if (ly < 1.0 || ly > h - 1.0) { fine_free(&f); return false; } + + memset(out, 0, sizeof(*out)); + out->wx = lx; out->wy = ly; + out->score = best_score; + out->elevation = f.elev[best_k]; + out->slope = f.slope[best_k]; + out->surface_type = f.surface[best_k]; + out->monsoon = mons; + out->river_discharge = q; + { + struct Tile t; + memset(&t, 0, sizeof(t)); + terrain_sample(&t, lx, ly, w); + out->temperature = t.temperature; + out->precip_mm = t.precip_mm; + } + + // 每样资源最近的那一处(地图上要画出来) + for (int r = 0; r < LANDING_RES_COUNT; r++) { + double bd = 1e18; + size_t bk = 0; + bool found = false; + for (size_t k = 0; k < total; k++) { + if (!hits[r][k]) continue; + double dx = ld_wrap_dx(lx, ld_wrap_x(ox + ((double)(k % nx) + 0.5) * step)); + double dy = (oy + ((double)(k / nx) + 0.5) * step) - ly; + double d = sqrt(dx * dx + dy * dy); + if (d < bd) { bd = d; bk = k; found = true; } + } + if (!found) { out->res_d[r] = 1e9; continue; } + out->res_d[r] = bd; + out->res_x[r] = ld_wrap_x(ox + ((double)(bk % nx) + 0.5) * step); + out->res_y[r] = oy + ((double)(bk / nx) + 0.5) * step; + out->res_grade[r] = f.grade[(size_t)r * total + bk]; + if (bd <= opt->radius_m) out->flags |= (1u << r); + } + if (out->river_discharge < opt->min_river_q) + out->flags &= ~(uint32_t)LANDING_OK_RIVER; + if (mons >= opt->min_monsoon && out->precip_mm >= opt->min_precip_mm) + out->flags |= LANDING_OK_MONSOON; + else + out->flags &= ~(uint32_t)LANDING_OK_MONSOON; + + fine_free(&f); + return true; +} + +// =============================================================== +// 对外 +// =============================================================== + +void landing_options_default(struct Landing_Options *opt) { + memset(opt, 0, sizeof(*opt)); + opt->radius_m = 5000.0; + opt->min_river_q = 20.0; + opt->min_monsoon = 0.25; + opt->min_precip_mm = 350.0; + opt->box_step_m = 250.0; + opt->box_cells = 49; // ±6km + opt->max_candidates = 64; + opt->max_sites = LANDING_MAX_SITES; + opt->min_sep_m = 1200000.0; // 前 3 个点之间的最小间距 + opt->min_sep_near_m = 200000.0; // 凑数用的最小间距 + opt->calib_samples = 1200; +} + +void landing_search(struct Landing_State *st, struct World *w, + const struct Landing_Options *opt_in) { + struct Landing_Options opt; + if (opt_in) opt = *opt_in; else landing_options_default(&opt); + if (opt.max_candidates < 1) opt.max_candidates = 1; + if (opt.max_candidates > 512) opt.max_candidates = 512; + if (opt.max_sites < 1) opt.max_sites = 1; + if (opt.max_sites > LANDING_MAX_SITES) opt.max_sites = LANDING_MAX_SITES; + if (opt.box_cells < 9) opt.box_cells = 9; + if (opt.box_cells > 129) opt.box_cells = 129; + if (opt.box_cells % 2 == 0) opt.box_cells++; + if (opt.box_step_m < 20.0) opt.box_step_m = 20.0; + + double t0 = (double)clock() / CLOCKS_PER_SEC; + memset(st->sites, 0, sizeof(st->sites)); + st->count = 0; + st->sel = 0; + st->relaxed = LANDING_OK_ALL; + st->ready = false; + st->boxes_tried = 0; + + build_monsoon_bands(st, w); + calibrate(w, opt.calib_samples, &st->thr_iron, &st->thr_copper, &st->thr_coal); + + struct Cand *cands = malloc(sizeof(struct Cand) * (size_t)opt.max_candidates); + if (cands == NULL) return; + int nc = coarse_scan(st, w, &opt, cands, opt.max_candidates); + if (nc > opt.max_candidates) nc = opt.max_candidates; + + // 凑不够就从最不关键的往下砍:煤矿 -> 铜矿 -> 森林 -> 铁矿。 + // 河流和季风不让步——没有河、没有雨季,前期活不下去。 + static const uint32_t relax_order[] = { + LANDING_OK_ALL, + LANDING_OK_ALL & ~(uint32_t)LANDING_OK_COAL, + LANDING_OK_ALL & ~(uint32_t)(LANDING_OK_COAL | LANDING_OK_COPPER), + LANDING_OK_ALL & ~(uint32_t)(LANDING_OK_COAL | LANDING_OK_COPPER | LANDING_OK_FOREST), + LANDING_OK_ALL & ~(uint32_t)(LANDING_OK_COAL | LANDING_OK_COPPER | LANDING_OK_FOREST | LANDING_OK_IRON), + }; + const int relax_n = (int)(sizeof(relax_order) / sizeof(relax_order[0])); + + // 间距分两级:第一遍要求候选点两两隔开 1200km(把玩家推到不同气候带), + // 拿不满再放宽到 200km 补。不能做成"前 3 个必须远、其余就近"——候选点 + // 本来就集中的世界里会卡在 2 个再也加不进去。 + const double seps[2] = { opt.min_sep_m, opt.min_sep_near_m }; + for (int tier = 0; tier < 2 && st->count < opt.max_sites; tier++) { + double sep = seps[tier]; + for (int r = 0; r < relax_n; r++) { + uint32_t need = relax_order[r]; + for (int i = 0; i < nc && st->count < opt.max_sites; i++) { + // 和已经选中的点离太近就跳过(否则几个点全挤在一条河上) + bool too_close = false; + for (int s = 0; s < st->count; s++) { + double dx = ld_wrap_dx(cands[i].wx, st->sites[s].wx); + double dy = cands[i].wy - st->sites[s].wy; + if (dx * dx + dy * dy < sep * sep) { + too_close = true; break; + } + } + if (too_close) continue; + + struct Landing_Site site; + st->boxes_tried++; + if (fine_search(st, w, &opt, cands[i].wx, cands[i].wy, + cands[i].q, need, &site)) { + st->sites[st->count++] = site; + st->relaxed = need; + } + } + if (st->count >= opt.max_sites) break; + if (tier == 0 && st->count >= 3) break; // 已经有 3 个远的了 + } + } + + // 最后的保险:一轮都没成功就退到"只要有一块能站的干地", + // 再不行就直接落在粗筛第一名的格子中心。宁可给一个条件很差的点, + // 也不能让玩家卡在选址界面出不去。 + if (st->count == 0 && nc > 0) { + struct Landing_Site site; + static const uint32_t fallback[] = { LANDING_OK_RIVER, 0u }; + for (size_t k = 0; k < sizeof(fallback) / sizeof(fallback[0]); k++) { + for (int i = 0; i < nc; i++) { + st->boxes_tried++; + if (fine_search(st, w, &opt, cands[i].wx, cands[i].wy, + cands[i].q, fallback[k], &site)) { + st->sites[st->count++] = site; + st->relaxed = fallback[k]; + break; + } + } + if (st->count > 0) break; + } + if (st->count == 0) { + memset(&site, 0, sizeof(site)); + site.wx = cands[0].wx; site.wy = cands[0].wy; + site.river_discharge = cands[0].q; + for (int r = 0; r < LANDING_RES_COUNT; r++) site.res_d[r] = 1e9; + st->sites[st->count++] = site; + st->relaxed = 0; + } + } + + // 按分数降序 + for (int i = 0; i < st->count; i++) { + for (int j = i + 1; j < st->count; j++) { + if (st->sites[j].score > st->sites[i].score) { + struct Landing_Site tmp = st->sites[i]; + st->sites[i] = st->sites[j]; + st->sites[j] = tmp; + } + } + } + + st->search_ms = ((double)clock() / CLOCKS_PER_SEC - t0) * 1000.0; + st->ready = (st->count > 0); + st->follow_sel = true; + free(cands); +} + +// =============================================================== +// 选址界面 +// =============================================================== +// 分成 pre / post 两半:pre 在第一帧的地图渲染**之前**跑(换点、把地图挪 +// 过去),post 在 map_draw 之后跑(把标记和面板叠在地图上)。合成一个函数 +// 的话,换点那一帧的标记会画在旧地图上,看起来像跳了一下。 + +#include +#ifndef _ +#define _(S) gettext(S) +#endif + +static const char *RES_LABEL[LANDING_RES_COUNT] = { + "landing.iron", "landing.copper", "landing.coal", + "landing.forest", "landing.river" +}; + +static void ld_text(struct Font f, const char *s, float x, float y, + float size, float sp, struct Color c) { + DrawTextEx(f, s, (struct Vector2){x + 1.5f, y + 1.5f}, size, sp, + (struct Color){0, 0, 0, 190}); + DrawTextEx(f, s, (struct Vector2){x, y}, size, sp, c); +} + +static void ld_panel(float x, float y, float w, float h) { + DrawRectangle((int)x, (int)y, (int)w, (int)h, + (struct Color){8, 10, 14, 200}); + DrawRectangleLines((int)x, (int)y, (int)w, (int)h, + (struct Color){120, 130, 150, 130}); +} + +void landing_ui_pre(struct Landing_State *st, struct World *w, + struct Map_View *mv) { + if (st->count <= 0) return; + if (st->sel < 0) st->sel = 0; + if (st->sel >= st->count) st->sel = st->count - 1; + + int prev = st->sel; + if (IsKeyPressed(KEY_Q) || IsKeyPressed(KEY_LEFT_BRACKET)) + st->sel = (st->sel + st->count - 1) % st->count; + if (IsKeyPressed(KEY_E) || IsKeyPressed(KEY_RIGHT_BRACKET)) + st->sel = (st->sel + 1) % st->count; + // 直接跳到第 N 个点用 **Shift+数字**:光秃秃的数字键是全局的地图配色 + // 快捷键(map.c),直接抢会变成"按 3 既选第 3 个点又切成岩石图"。 + if (map_ui_shift_down()) { + for (int k = 0; k < st->count && k < 9; k++) + if (IsKeyPressed(KEY_ONE + k)) st->sel = k; + } + + // 鼠标点标记也能选 + if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT)) { + double mx = (double)GetMouseX(), my = (double)GetMouseY(); + for (int k = 0; k < st->count; k++) { + double sx, sy; + map_world_to_screen(mv, st->sites[k].wx, st->sites[k].wy, &sx, &sy); + double dx = sx - mx, dy = sy - my; + if (dx * dx + dy * dy < 22.0 * 22.0) { st->sel = k; break; } + } + } + if (st->sel != prev) st->follow_sel = true; + + if (st->follow_sel) { + struct Landing_Site *s = &st->sites[st->sel]; + mv->center.x = s->wx; + mv->center.y = s->wy; + // 默认给一个"看得见 5km 圈,也看得见周边地形"的缩放 + if (mv->mpp > 900.0 || mv->mpp < 60.0) mv->mpp = 300.0; + st->follow_sel = false; + } +} + +void landing_ui_post(struct Landing_State *st, struct World *w, + struct Map_View *mv, struct Font font, + float font_size, float spacing) { + int sw = GetScreenWidth(), sh = GetScreenHeight(); + float small = font_size * 0.72f; + char line[256]; + + if (st->count <= 0 || !st->ready) { + const char *tip = _("landing.none"); + struct Vector2 sz = MeasureTextEx(font, tip, font_size, spacing); + ld_panel(((float)sw - sz.x) * 0.5f - 16.0f, (float)sh * 0.5f - 20.0f, + sz.x + 32.0f, font_size + 26.0f); + ld_text(font, tip, ((float)sw - sz.x) * 0.5f, (float)sh * 0.5f - 8.0f, + font_size, spacing, (struct Color){255, 210, 120, 255}); + return; + } + + struct Landing_Site *s = &st->sites[st->sel]; + + // ---- 标记 ---- + for (int i = 0; i < st->count; i++) { + struct Landing_Site *t = &st->sites[i]; + double sx, sy; + map_world_to_screen(mv, t->wx, t->wy, &sx, &sy); + if (sx < -60 || sx > sw + 60 || sy < -60 || sy > sh + 60) continue; + + if (i == st->sel) { + // 5km 资源半径 + double rx, ry; + map_world_to_screen(mv, t->wx + 5000.0, t->wy, &rx, &ry); + float r = (float)fabs(rx - sx); + if (r > 4.0f && r < 4000.0f) { + DrawCircleLines((int)sx, (int)sy, r, + (struct Color){255, 255, 255, 150}); + } + // 五样资源的位置 + static const struct Color rc[LANDING_RES_COUNT] = { + {232, 90, 70, 255}, // 铁 + { 80, 210, 215, 255}, // 铜 + { 40, 40, 46, 255}, // 煤 + { 90, 225, 110, 255}, // 森林 + { 90, 155, 255, 255}, // 河流 + }; + for (int r2 = 0; r2 < LANDING_RES_COUNT; r2++) { + if (t->res_d[r2] > 1e8) continue; + double px, py; + map_world_to_screen(mv, t->res_x[r2], t->res_y[r2], &px, &py); + DrawCircle((int)px, (int)py, 5.0f, (struct Color){0, 0, 0, 170}); + DrawCircle((int)px, (int)py, 3.5f, rc[r2]); + } + } + DrawCircle((int)sx, (int)sy, i == st->sel ? 9.0f : 7.0f, + (struct Color){0, 0, 0, 190}); + DrawCircle((int)sx, (int)sy, i == st->sel ? 7.0f : 5.0f, + i == st->sel ? (struct Color){255, 90, 70, 255} + : (struct Color){255, 225, 130, 255}); + snprintf(line, sizeof(line), "%d", i + 1); + ld_text(font, line, (float)sx + 10.0f, (float)sy - 26.0f, small, + spacing, RAYWHITE); + if (i == st->sel) { + DrawLineEx((struct Vector2){(float)sx - 14, (float)sy}, + (struct Vector2){(float)sx + 14, (float)sy}, 1.5f, + (struct Color){255, 255, 255, 170}); + DrawLineEx((struct Vector2){(float)sx, (float)sy - 14}, + (struct Vector2){(float)sx, (float)sy + 14}, 1.5f, + (struct Color){255, 255, 255, 170}); + } + } + + // ---- 右侧体检表 ---- + float pw = 372.0f; + float ph = 44.0f + 6.0f * (font_size * 1.5f) + 3.0f * (font_size * 1.35f) + 22.0f; + float px0 = (float)sw - pw - 12.0f; + float py0 = 62.0f; + ld_panel(px0, py0, pw, ph); + + snprintf(line, sizeof(line), "%s %d / %d", _("landing.title"), + st->sel + 1, st->count); + ld_text(font, line, px0 + 14.0f, py0 + 10.0f, font_size, spacing, + (struct Color){255, 232, 160, 255}); + + float y = py0 + 12.0f + font_size * 1.6f; + float lh = font_size * 1.5f; + for (int r = 0; r < LANDING_RES_COUNT; r++) { + bool ok = (s->flags & (1u << r)) != 0; + ld_text(font, _(RES_LABEL[r]), px0 + 14.0f, y, small, spacing, + (struct Color){205, 212, 224, 255}); + ld_text(font, ok ? "OK" : "--", px0 + 118.0f, y, small, spacing, + ok ? (struct Color){120, 225, 140, 255} + : (struct Color){235, 110, 100, 255}); + if (s->res_d[r] < 1000.0) { + snprintf(line, sizeof(line), "%.0f m", s->res_d[r]); + } else if (s->res_d[r] < 1e8) { + snprintf(line, sizeof(line), "%.2f km", s->res_d[r] / 1000.0); + } else { + snprintf(line, sizeof(line), "-"); + } + ld_text(font, line, px0 + 162.0f, y, small, spacing, + (struct Color){205, 212, 224, 255}); + if (r < 3) { + snprintf(line, sizeof(line), "%.3f (%.3f)", s->res_grade[r], + r == 0 ? st->thr_iron : r == 1 ? st->thr_copper + : st->thr_coal); + ld_text(font, line, px0 + 236.0f, y, small * 0.9f, spacing, + (struct Color){170, 180, 196, 255}); + } else if (r == LANDING_RES_RIVER) { + snprintf(line, sizeof(line), "%.0f m3/s", s->river_discharge); + ld_text(font, line, px0 + 236.0f, y, small * 0.9f, spacing, + (struct Color){170, 180, 196, 255}); + } + y += lh; + } + { + bool ok = (s->flags & LANDING_OK_MONSOON) != 0; + ld_text(font, _("landing.monsoon"), px0 + 14.0f, y, small, spacing, + (struct Color){205, 212, 224, 255}); + ld_text(font, ok ? "OK" : "--", px0 + 118.0f, y, small, spacing, + ok ? (struct Color){120, 225, 140, 255} + : (struct Color){235, 110, 100, 255}); + snprintf(line, sizeof(line), _("landing.monsoon_val"), s->monsoon, + s->precip_mm); + ld_text(font, line, px0 + 162.0f, y, small, spacing, + (struct Color){205, 212, 224, 255}); + y += lh; + } + y += font_size * 0.35f; + snprintf(line, sizeof(line), _("landing.site_stats"), s->elevation, + s->slope, s->temperature, s->precip_mm); + ld_text(font, line, px0 + 14.0f, y, small, spacing, + (struct Color){190, 200, 215, 255}); + y += font_size * 1.15f; + snprintf(line, sizeof(line), _("landing.thresholds"), st->thr_iron, + st->thr_copper, st->thr_coal); + ld_text(font, line, px0 + 14.0f, y, small * 0.92f, spacing, + (struct Color){150, 158, 172, 255}); + + // ---- 底部提示 ---- + { + const char *tip = _("landing.hint"); + float fs = font_size * 0.8f; + struct Vector2 sz = MeasureTextEx(font, tip, fs, 1.3f * spacing); + float tx = ((float)sw - sz.x) * 0.5f; + float ty = (float)sh - 62.0f; + DrawRectangle((int)tx - 14, (int)ty - 10, (int)sz.x + 28, (int)sz.y + 18, + (struct Color){8, 10, 14, 190}); + ld_text(font, tip, tx, ty, fs, 1.3f * spacing, + (struct Color){255, 230, 160, 255}); + } +} diff --git a/src/landing.h b/src/landing.h new file mode 100644 index 0000000..515c023 --- /dev/null +++ b/src/landing.h @@ -0,0 +1,121 @@ +#ifndef LANDING_H +#define LANDING_H + +#include +#include +#include +#include "world.h" + +// =============================================================== +// 着陆点选址 +// =============================================================== +// 玩家**不自由选点**:远征队自己挑地方。硬性条件是着陆点半径 5km 内 +// 同时能找到 +// 铁矿、铜矿、煤矿、森林、河流 +// 而且当地是季风气候(有雨季,前期才有水)。缺一样,前期就卡死。 +// +// 全球 40960km 见方(1.7e9 km²,约 4.5 个地球陆地),不可能做细网格扫描。 +// 所以分两级: +// 粗筛 在 40km 的水文网格上按"在河道上 + 河够大 + 季风 + 不崎岖"打分, +// 取前若干个(互相比开 300km 以上); +// 细查 只在候选点周围 12km 见方、250m 步长上算三种矿的品位,再用 +// 倒角距离变换求出"到最近铁矿/铜矿/煤矿/森林/河道的距离", +// 最后挑一个五样都在 5km 内、而且平坦靠水的点当着陆点。 +// +// 矿的判据("什么算一处矿")用**这个世界的实际参数标定**:随机撒点取 +// 品位的 p88。这样把 ore_abundance / difficulty / realism 三个创建选项 +// 接进来了——"矿少"的世界里矿点就是更稀,而不是判据失灵。 +// +// 已知简化:季风带在这个模型里只随纬度变(见 landing.c 的说明), +// 所以"季风气候"实际上是"在这一条纬度带里"。 +// --------------------------------------------------------------- + +#define LANDING_MAX_SITES 6 + +// 半径内的五样资源 +enum { + LANDING_RES_IRON = 0, + LANDING_RES_COPPER, + LANDING_RES_COAL, + LANDING_RES_FOREST, + LANDING_RES_RIVER, + LANDING_RES_COUNT +}; + +// 硬条件位掩码(与 LANDING_RES_* 一一对应,另加季风) +enum { + LANDING_OK_IRON = 1u << LANDING_RES_IRON, + LANDING_OK_COPPER = 1u << LANDING_RES_COPPER, + LANDING_OK_COAL = 1u << LANDING_RES_COAL, + LANDING_OK_FOREST = 1u << LANDING_RES_FOREST, + LANDING_OK_RIVER = 1u << LANDING_RES_RIVER, + LANDING_OK_MONSOON= 1u << 5, + LANDING_OK_ALL = 0x3fu +}; + +struct Landing_Site { + double wx, wy; + double score; // 综合分,越大越好 + uint32_t flags; // LANDING_OK_*,缺哪样一目了然 + + // 半径内每样资源最近的那一处 + double res_d[LANDING_RES_COUNT]; // 距离 m + double res_x[LANDING_RES_COUNT]; // 位置(画在地图上) + double res_y[LANDING_RES_COUNT]; + double res_grade[LANDING_RES_COUNT]; // 最高品位(归一化占比;森林/河流为 0) + + double river_discharge; // 那条河的流量 m³/s + + // 场地条件 + double elevation, slope, temperature, precip_mm, monsoon; + uint8_t surface_type; +}; + +struct Landing_Options { + double radius_m; // 资源半径(默认 5000) + double min_river_q; // 河的最小流量 m³/s(默认 20) + double min_monsoon; // 季风强度下限(默认 0.25) + double min_precip_mm; // 年降水下限 mm(默认 350) + double box_step_m; // 细查步长(默认 250) + int box_cells; // 细查边长格数(默认 49 → ±6km) + int max_candidates; // 最多细查几个候选格子(默认 24) + int max_sites; // 最多返回几个点(默认 LANDING_MAX_SITES) + double min_sep_m; // 前 3 个候选点之间的最小距离(默认 1200km) + double min_sep_near_m; // 之后凑数时的最小距离(默认 200km) + int calib_samples; // 标定品位阈值用的撒点数(默认 1200) +}; + +struct Landing_State { + struct Landing_Site sites[LANDING_MAX_SITES]; + int count; + int sel; // 当前选中的那个 + uint32_t relaxed; // 实际用到哪一档要求(= 必须满足的位掩码) + double thr_iron, thr_copper, thr_coal; // 标定出来的品位阈值 + double mons_band[WORLD_BLOCK_COUNT_Y]; // 每个纬度带的季风强度 + double search_ms; + int boxes_tried; + bool ready; + + // UI 状态 + bool confirmed; + bool follow_sel; // 换点后把地图挪过去 +}; + +struct Map_View; + +void landing_options_default(struct Landing_Options *opt); + +// 跑一次选址。结果写进 st->sites / st->count(按分数降序)。 +void landing_search(struct Landing_State *st, struct World *w, + const struct Landing_Options *opt); + +// 选址界面分两半:pre 在 map_update/draw **之前**(换点、把地图挪过去), +// post 在 map_draw **之后**(把标记和体检表叠在地图上)。 +// Enter 的判定放在调用方(main.c),因为着陆要回收上一局。 +void landing_ui_pre(struct Landing_State *st, struct World *w, + struct Map_View *mv); +void landing_ui_post(struct Landing_State *st, struct World *w, + struct Map_View *mv, struct Font font, + float font_size, float spacing); + +#endif diff --git a/src/main.c b/src/main.c index 9bbd448..406d439 100644 --- a/src/main.c +++ b/src/main.c @@ -219,6 +219,18 @@ int main(){ struct text_list text_list={NULL,0}; + struct World *world = NULL; + struct Map_View map_view; + bool map_view_ready = false; + bool pending_world_create = false; + + // 着陆点选址:世界一建好就算一遍,之后只在世界地图上挑 + struct Landing_State landing; + memset(&landing, 0, sizeof(landing)); + + struct Game_State *game = NULL; // 局部游戏层(1 格 = 1 米) + bool game_ready = false; + struct Input_Box *focus = NULL; struct Input_Box **focus_p = NULL; @@ -866,8 +878,8 @@ int main(){ focus = NULL; focus_p = NULL; - // 接入点:world_create(&world_config); screen = GAME_SCREEN; - screen = START_SCREEN; + // 世界生成(板块 + 高程)要几百毫秒,放到本帧渲染结束之后再做 + pending_world_create = true; break; } @@ -952,6 +964,77 @@ int main(){ break; + case GAME_SCREEN://世界地图 —— 选着陆点 + if(world==NULL||!map_view_ready){ + ClearBackground(background_color); + screen = START_SCREEN; + break; + } + + // 世界时间在这里**不**推进:选点的时候世界是暂停的, + // 进入局部视图之后才按 1 秒 = 1 游戏秒走。 + // + // 玩家不自由选点:远征队自己挑好了几个"五样俱全"的地点 + // (见 landing.c),玩家只在这些点之间挑,能平移缩放看周边。 + landing_ui_pre(&landing,world,&map_view); + map_update(&map_view); + map_draw(&map_view,font_25px,25*screen_scale,2*screen_scale); + landing_ui_post(&landing,world,&map_view,font_25px, + 25*screen_scale,2*screen_scale); + + if((IsKeyPressed(KEY_ENTER)||IsKeyPressed(KEY_KP_ENTER)) + &&landing.count>0){ + // 重新着陆:先把上一次的回收掉,否则会漏 + if(game_ready&&game!=NULL){ + game_free(game); + game=NULL; + game_ready=false; + } + struct Landing_Site *site = &landing.sites[landing.sel]; + game = game_create(world,site->wx,site->wy); + if(game!=NULL){ + game_ready = true; + screen = PLAY_SCREEN; + } + } + + if(IsKeyPressed(KEY_ESCAPE)){ + map_free(&map_view); + map_view_ready = false; + world_destroy(world); + world = NULL; + screen = START_SCREEN; + } + break; + + case PLAY_SCREEN://局部游戏(1 格 = 1 米) + if(world==NULL||!game_ready||game==NULL){ + ClearBackground(background_color); + screen = START_SCREEN; + break; + } + + game_update(game,GetFrameTime()); + game_draw(game,font_25px,25*screen_scale,2*screen_scale); + + // M / Tab:回世界地图看一眼(世界在局部视图里才走时间) + if(IsKeyPressed(KEY_M)||IsKeyPressed(KEY_TAB)){ + screen = GAME_SCREEN; + break; + } + // 空格:把玩家挪到地图准星处(方便调试/以后做传送) + if(IsKeyPressed(KEY_ESCAPE)){ + game_free(game); + game = NULL; + game_ready = false; + map_free(&map_view); + map_view_ready = false; + world_destroy(world); + world = NULL; + screen = START_SCREEN; + } + break; + } if (IsWindowResized()&&background_type==IMAGE){ @@ -965,10 +1048,74 @@ int main(){ EndDrawing(); + if(pending_world_create){ + pending_world_create = false; + + // 先画一帧提示:世界生成期间窗口会卡住几百毫秒 + BeginDrawing(); + ClearBackground(background_color); + { + const char *tip = _("world.generating"); + struct Vector2 tip_size = MeasureTextEx(font_25px,tip,25*screen_scale,2*screen_scale); + DrawTextEx(font_25px,tip, + (struct Vector2){(GetScreenWidth()-tip_size.x)*0.5f, + (GetScreenHeight()-tip_size.y)*0.5f}, + 25*screen_scale,2*screen_scale,text_color); + } + EndDrawing(); + + world = world_create(&world_config); + if(world!=NULL){ + // 选址也要算一会儿(粗筛 1e6 个水文格 + 若干候选格的细查), + // 所以照样先画一帧提示 + BeginDrawing(); + ClearBackground(background_color); + { + const char *tip = _("world.survey"); + struct Vector2 tip_size = MeasureTextEx(font_25px,tip,25*screen_scale,2*screen_scale); + DrawTextEx(font_25px,tip, + (struct Vector2){(GetScreenWidth()-tip_size.x)*0.5f, + (GetScreenHeight()-tip_size.y)*0.5f}, + 25*screen_scale,2*screen_scale,text_color); + } + EndDrawing(); + + memset(&landing,0,sizeof(landing)); + landing_search(&landing,world,NULL); + + map_init(&map_view,world); + // 开局就把镜头对准首选的着陆点 + if(landing.count>0){ + map_view.center.x = landing.sites[0].wx; + map_view.center.y = landing.sites[0].wy; + map_view.mpp = 300.0; + landing.follow_sel = false; + } + map_view_ready = true; + screen = GAME_SCREEN; // 先在世界地图上选着陆点 + }else{ + screen = START_SCREEN; + } + } + } jump_break: + if(game_ready){ + game_free(game); + game = NULL; + game_ready = false; + } + if(map_view_ready){ + map_free(&map_view); + map_view_ready = false; + } + if(world!=NULL){ + world_destroy(world); + world = NULL; + } + if(background_type==IMAGE){ UnloadTexture(background_image); }//图片背景模式的纹理单独收回 diff --git a/src/main.h b/src/main.h index 59ff6bc..953b3df 100644 --- a/src/main.h +++ b/src/main.h @@ -11,18 +11,51 @@ #include "texture.h" #include "timer.h" #include "tools.h" + // 时间与天文 + #include "astro.h" + #include "weather.h" + #include "hydro.h" + // 世界生成 + #include "terrain.h" + #include "noise.h" + #include "chunk.h" + #include "compound.h" + #include "climate.h" + #include "river.h" + #include "world.h" + #include "map.h" + #include "landing.h" + #include "game.h" #else #include "json.c" #include "ui.c" #include "texture.c" #include "timer.c" #include "tools.c" + // 时间与天文 + #include "astro.c" + #include "weather.c" + #include "hydro.c" + // 世界生成 + #include "terrain.c" + #include "noise.c" + #include "chunk.c" + #include "compound.c" + #include "random.c" + #include "climate.c" + #include "river.c" + #include "world.c" + #include "map.c" + #include "landing.c" + #include "game.c" #endif #ifndef MAIN_H #define MAIN_H +#ifndef _ #define _(STRING) gettext(STRING) +#endif struct { struct json_object *root; @@ -51,7 +84,9 @@ enum{ SETTING_SCREEN, SETTING_BACKGROUND_SCREEN, EXIT_SCREEN, - CREATE_WORLD_SCREEN + CREATE_WORLD_SCREEN, + GAME_SCREEN, // 世界地图:选着陆点 + PLAY_SCREEN // 局部游戏:1 格 = 1 米,可走动 }screen=START_SCREEN; extern const char *texture_path_list[]; @@ -68,38 +103,7 @@ enum { CENTER_INPUT_BOX }; -enum { - DIFFICULTY_EASY, - DIFFICULTY_NORMAL, - DIFFICULTY_HARD, - DIFFICULTY_BRUTAL, - DIFFICULTY_COUNT -}; - -enum { - ORE_SCARCE, - ORE_NORMAL, - ORE_ABUNDANT, - ORE_PARADISE, - ORE_COUNT -}; - -enum { - REALISM_CASUAL, - REALISM_STANDARD, - REALISM_HARDCORE, - REALISM_COUNT -}; - -#define WORLD_NAME_MAX 64 - -struct World_Config { - char name[WORLD_NAME_MAX]; - uint64_t seed; - int difficulty; - int ore_abundance; - int realism; -}; +// DIFFICULTY_* / ORE_* / REALISM_* 与 struct World_Config 已移到 world.h enum { ENGLISH, diff --git a/src/map.c b/src/map.c new file mode 100644 index 0000000..6fef673 --- /dev/null +++ b/src/map.c @@ -0,0 +1,1099 @@ +#include "map.h" +// 地图上只显示汇水面积超过这个格数的河流(纯粹是显示层的取舍,不影响 +// 物理模型里的河道阈值) +#define MAP_RIVER_MIN_CELLS 90.0 + + +#include "chunk.h" +#include "hydro.h" +#include "astro.h" +#include "ui.h" + +#include +#include +#include +#include +#include +#include + +// =============================================================== +// 世界坐标工具 +// =============================================================== + +// x 方向是环形的(和 wrap_block_x 一致),y 方向夹紧到两极 +static double wrap_world_x(double wx) { + double w = (double)WORLD_W; + wx = fmod(wx, w); + if (wx < 0.0) wx += w; + return wx; +} + +static double clamp_world_y(double wy) { + double h = (double)WORLD_H; + if (wy < 0.0) wy = 0.0; + if (wy > h) wy = h; + return wy; +} + +// 左右 Shift 都算。map.c 的数字键配色和选址界面的 Shift+数字直选共用 +// 同一批键,靠这个区分。 +bool map_ui_shift_down(void) { + return IsKeyDown(KEY_LEFT_SHIFT) || IsKeyDown(KEY_RIGHT_SHIFT); +} + +static int default_threads(int requested) { + if (requested > 0) return requested; + long n = sysconf(_SC_NPROCESSORS_ONLN); + return (n > 0) ? (int)n : 1; +} + +// =============================================================== +// 按行并行的通用小工具 +// =============================================================== + +typedef void (*Row_Fn)(void *ctx, int y0, int y1); + +struct Row_Job { + Row_Fn fn; + void *ctx; + int y0, y1; +}; + +static void *row_worker(void *arg) { + struct Row_Job *j = (struct Row_Job *)arg; + j->fn(j->ctx, j->y0, j->y1); + return NULL; +} + +static void run_rows(int threads, int rows, Row_Fn fn, void *ctx) { + if (threads <= 1 || rows <= 1) { fn(ctx, 0, rows); return; } + if (threads > rows) threads = rows; + + pthread_t *tids = malloc(sizeof(pthread_t) * (size_t)threads); + struct Row_Job *jobs = malloc(sizeof(struct Row_Job) * (size_t)threads); + if (tids == NULL || jobs == NULL) { + free(tids); free(jobs); + fn(ctx, 0, rows); + return; + } + + int per = rows / threads; + int rem = rows % threads; + int y = 0; + for (int i = 0; i < threads; i++) { + int cnt = per + (i < rem ? 1 : 0); + jobs[i].fn = fn; + jobs[i].ctx = ctx; + jobs[i].y0 = y; + jobs[i].y1 = y + cnt; + y += cnt; + pthread_create(&tids[i], NULL, row_worker, &jobs[i]); + } + for (int i = 0; i < threads; i++) pthread_join(tids[i], NULL); + + free(tids); + free(jobs); +} + +// =============================================================== +// 采样 +// =============================================================== +// +// 这是一个"每像素都要跑一遍"的内循环,所以每一层都要按需调用。 +// 实测(800x450,12 线程,见 test/dbg_perf.c): +// terrain_sample 2.7 us ← 其中 20m 基线坡度差分占 1.9 us +// hydro_sample 0.3 us ← 只有积雪/水温/潮差三种配色用得到 +// river_sample_filtered ~1 us ← 只有水系配色的"是不是河道"用得到 +// 全算一遍是 4.8 us/px(约 7 fps),按需 + LOD + 移动时降分辨率之后 +// 是 0.2 us/px 量级。 +// +// 每种配色真正需要的"贵"字段: +// 积雪 -> 冰厚、积雪覆盖率 (水文层) +// 水温 -> 水温、冰厚、是否水体 (水文层) +// 潮差 -> 平均潮差、是否水体 (水文层) +// 水系 -> 流量、是否落在河道内 (河流层,带最小汇水面积过滤) +// 其余配色只要 terrain_sample 这一层。 + +static bool mode_needs_hydro(enum Map_Mode m) { + return m == MAP_MODE_SNOW || m == MAP_MODE_WATER_TEMP || m == MAP_MODE_TIDE; +} + +static bool mode_needs_river(enum Map_Mode m) { + return m == MAP_MODE_RIVER; +} + +// 地图采样精度分三档(见 chunk.h 的 terrain_sample_lod): +// mpp <= 64 m 完整精度(米级细节 + 20m 基线坡度) +// mpp <= 4 km 丢掉 60/15/4m 三层细节(亚像素) +// mpp > 4 km 连 8km / 400m 两个倍频也丢掉(同样是亚像素, +// 留着只会变成椒盐噪声) +#define MAP_LOD_MPP 64.0 +#define MAP_LOD2_MPP 4000.0 + +static int map_lod_for(double mpp) { + if (mpp > MAP_LOD2_MPP) return 2; + if (mpp > MAP_LOD_MPP) return 1; + return 0; +} + +struct Sample_Ctx { + struct World *world; + struct Map_Sample *buf; + int img_w; + double origin_x, origin_y, mpp; + bool need_hydro; + bool need_river; + int lod; // >=0 强制精度档位,<0 = 按 mpp 自动 +}; + +static void sample_one(struct World *w, double wx, double wy, double mpp, + bool need_hydro, bool need_river, int lod, + struct Map_Sample *out) { + struct Tile t; + memset(&t, 0, sizeof(t)); // slope / aspect = 0:地图尺度上坡度无意义 + terrain_sample_lod(&t, wx, wy, w, lod >= 0 ? lod : map_lod_for(mpp)); + + out->elevation = (float)t.elevation; + out->temperature = (float)t.temperature; + out->moisture = (float)t.moisture; + out->vegetation = (float)t.vegetation; + out->seasonality = t.seasonal_amplitude; + out->precipitation = t.precipitation; + out->water_depth = t.water_depth; + out->surface_type = t.surface_type; + out->soil_type = t.soil_type; + out->rock_type = t.rock_type; + out->is_water = (t.elevation < 0.0 || t.water_depth > 0.0f) ? 1 : 0; + + if (need_hydro) { + // 时间相关的量:按**当前世界时间**采样,所以地图上能看到 + // 积雪带随季节南北移动、河湖封冻开河、水温的年循环。 + struct Hydro_Sample hs; + hydro_sample(w, wx, wy, t.elevation, w->now.seconds, &hs); + out->swe_mm = (float)hs.swe_mm; + out->snow_cover = (float)hs.snow_cover; + out->water_temp = (float)hs.water_temp; + out->ice_thick = (float)hs.ice_thick; + out->tidal_range = (float)hs.tidal_range; + out->tidal_form = (float)hs.tidal_form; + } else { + out->swe_mm = 0.0f; out->snow_cover = 0.0f; + out->water_temp = 0.0f; out->ice_thick = 0.0f; + out->tidal_range = 0.0f; out->tidal_form = 0.0f; + } + + if (need_river) { + // 全球视图下一条河只有零点几个像素宽,点采样必然断续。所以: + // 1) 只画汇水面积够大的河,让河网间距远大于线宽(否则一片椒盐); + // 2) 线宽取 max(真实河宽, 半个屏幕像素),保证线是连着的。 + const double min_area = MAP_RIVER_MIN_CELLS * RIVER_CELL_M * RIVER_CELL_M; + struct River_Sample rs; + river_sample_filtered(w->rivers, wx, wy, min_area, &rs); + out->discharge = (float)rs.discharge; + + double radius = rs.width * 0.5; + if (radius < mpp * 0.5) radius = mpp * 0.5; + out->is_channel = (rs.is_channel && rs.dist <= radius) ? 1 : 0; + } else { + out->discharge = 0.0f; + out->is_channel = 0; + } +} + +static void sample_rows(void *ctx, int y0, int y1) { + struct Sample_Ctx *c = (struct Sample_Ctx *)ctx; + for (int py = y0; py < y1; py++) { + double wy = clamp_world_y(c->origin_y + (py + 0.5) * c->mpp); + struct Map_Sample *row = c->buf + (size_t)py * c->img_w; + for (int px = 0; px < c->img_w; px++) { + double wx = wrap_world_x(c->origin_x + (px + 0.5) * c->mpp); + sample_one(c->world, wx, wy, c->mpp, c->need_hydro, c->need_river, + c->lod, row + px); + } + } +} + +static void sample_buffer(struct World *w, struct Map_Sample *buf, + int img_w, int img_h, + double origin_x, double origin_y, double mpp, + enum Map_Mode mode, int lod, int threads) { + struct Sample_Ctx ctx; + ctx.world = w; + ctx.buf = buf; + ctx.img_w = img_w; + ctx.origin_x = origin_x; + ctx.origin_y = origin_y; + ctx.mpp = mpp; + ctx.need_hydro = mode_needs_hydro(mode); + ctx.need_river = mode_needs_river(mode); + ctx.lod = lod; + run_rows(threads, img_h, sample_rows, &ctx); +} + +// =============================================================== +// 配色 +// =============================================================== + +static struct Color lerp_color(struct Color a, struct Color b, double t) { + if (t < 0.0) t = 0.0; + if (t > 1.0) t = 1.0; + struct Color c; + c.r = (unsigned char)(a.r + (b.r - a.r) * t); + c.g = (unsigned char)(a.g + (b.g - a.g) * t); + c.b = (unsigned char)(a.b + (b.b - a.b) * t); + c.a = 255; + return c; +} + +// 沿一组"色标"做分层设色 +struct Color_Stop { double v; struct Color c; }; + +static struct Color ramp_color(const struct Color_Stop *stops, int n, double v) { + if (v <= stops[0].v) return stops[0].c; + for (int i = 1; i < n; i++) { + if (v <= stops[i].v) { + double span = stops[i].v - stops[i - 1].v; + double t = (span > 0.0) ? (v - stops[i - 1].v) / span : 0.0; + return lerp_color(stops[i - 1].c, stops[i].c, t); + } + } + return stops[n - 1].c; +} + +static struct Color elevation_color(double e) { + static const struct Color_Stop stops[] = { + { -8000.0, { 8, 20, 60, 255 } }, + { -4000.0, { 12, 40, 100, 255 } }, + { -500.0, { 30, 90, 150, 255 } }, + { -50.0, { 60, 130, 180, 255 } }, + { 0.0, { 90, 140, 170, 255 } }, + { 100.0, { 96, 145, 92, 255 } }, + { 500.0, {110, 155, 85, 255 } }, + { 1200.0, {155, 160, 95, 255 } }, + { 2200.0, {160, 125, 82, 255 } }, + { 3200.0, {130, 108, 95, 255 } }, + { 4200.0, {165, 165, 165, 255 } }, + { 5200.0, {235, 238, 242, 255 } }, + { 7000.0, {255, 255, 255, 255 } }, + }; + return ramp_color(stops, (int)(sizeof(stops) / sizeof(stops[0])), e); +} + +static struct Color surface_color(uint8_t s); // 下面三个配色要用 + +// ---- 随时间变化的三种配色 ---- + +// 积雪:薄的保留地表底色,厚的刷白;结冰的水面用冰白 +static struct Color snow_color(const struct Map_Sample *s) { + if (s->ice_thick > 0.02f) return (struct Color){215, 236, 250, 255}; + struct Color base = surface_color(s->surface_type); + if (s->elevation < 0.0f) base = (struct Color){40, 80, 130, 255}; + if (s->snow_cover <= 0.004f) return base; + double t = 0.20 + 0.80 * s->snow_cover; + return lerp_color(base, (struct Color){250, 250, 255, 255}, t); +} + +// 水温:陆地压暗当背景,水面按水温分层设色,结冰的盖一层冰白 +static struct Color water_temp_color(const struct Map_Sample *s) { + if (s->is_water) { + if (s->ice_thick > 0.02f) return (struct Color){222, 240, 252, 255}; + static const struct Color_Stop stops[] = { + { -6.0, { 30, 40, 95, 255 } }, + { 0.0, { 55, 110, 190, 255 } }, + { 6.0, { 60, 175, 205, 255 } }, + { 14.0, { 95, 200, 125, 255 } }, + { 22.0, { 235, 200, 70, 255 } }, + { 31.0, { 215, 75, 45, 255 } }, + }; + return ramp_color(stops, 6, s->water_temp); + } + struct Color c = surface_color(s->surface_type); + return (struct Color){(unsigned char)(c.r * 0.40), + (unsigned char)(c.g * 0.40), + (unsigned char)(c.b * 0.45), 255}; +} + +// 潮差:开阔洋面 <1m 是深蓝,宽浅陆架 2~4m,喇叭口河口能到十几米 +static struct Color tide_color(const struct Map_Sample *s) { + if (s->tidal_range <= 0.0f) { + return (s->is_water) ? (struct Color){16, 28, 48, 255} + : (struct Color){38, 38, 42, 255}; + } + static const struct Color_Stop stops[] = { + { 0.20, { 28, 55, 105, 255 } }, + { 1.00, { 40, 115, 180, 255 } }, + { 2.00, { 60, 185, 185, 255 } }, + { 4.00, { 150, 210, 95, 255 } }, + { 8.00, { 240, 190, 60, 255 } }, + { 14.00, { 230, 70, 55, 255 } }, + }; + return ramp_color(stops, 6, s->tidal_range); +} + +static struct Color surface_color(uint8_t s) { + switch (s) { + case SURFACE_BARE_ROCK: return (struct Color){130, 125, 120, 255}; + case SURFACE_SOIL: return (struct Color){140, 115, 80, 255}; + case SURFACE_SAND: return (struct Color){225, 205, 140, 255}; + case SURFACE_GRASS: return (struct Color){150, 175, 95, 255}; + case SURFACE_FOREST: return (struct Color){ 60, 110, 60, 255}; + case SURFACE_WATER: return (struct Color){ 40, 90, 150, 255}; + case SURFACE_SNOW: return (struct Color){245, 245, 250, 255}; + case SURFACE_ICE: return (struct Color){215, 235, 245, 255}; + case SURFACE_TUNDRA: return (struct Color){160, 158, 145, 255}; + case SURFACE_TAIGA: return (struct Color){ 45, 85, 70, 255}; + case SURFACE_SAVANNA: return (struct Color){190, 180, 100, 255}; + case SURFACE_SHRUB: return (struct Color){150, 150, 105, 255}; + case SURFACE_SWAMP: return (struct Color){ 70, 100, 80, 255}; + default: return (struct Color){255, 0, 255, 255}; + } +} + +static const char *surface_name(uint8_t s) { + switch (s) { + case SURFACE_BARE_ROCK: return _("map.surface.bare_rock"); + case SURFACE_SOIL: return _("map.surface.soil"); + case SURFACE_SAND: return _("map.surface.sand"); + case SURFACE_GRASS: return _("map.surface.grass"); + case SURFACE_FOREST: return _("map.surface.forest"); + case SURFACE_WATER: return _("map.surface.water"); + case SURFACE_SNOW: return _("map.surface.snow"); + case SURFACE_ICE: return _("map.surface.ice"); + case SURFACE_TUNDRA: return _("map.surface.tundra"); + case SURFACE_TAIGA: return _("map.surface.taiga"); + case SURFACE_SAVANNA: return _("map.surface.savanna"); + case SURFACE_SHRUB: return _("map.surface.shrub"); + case SURFACE_SWAMP: return _("map.surface.swamp"); + default: return "?"; + } +} + +static const char *rock_name(uint8_t r) { + switch (r) { + case ROCK_GRANITE: return _("map.rock.granite"); + case ROCK_BASALT: return _("map.rock.basalt"); + case ROCK_LIMESTONE: return _("map.rock.limestone"); + case ROCK_SANDSTONE: return _("map.rock.sandstone"); + case ROCK_SHALE: return _("map.rock.shale"); + case ROCK_SCHIST: return _("map.rock.schist"); + case ROCK_GNEISS: return _("map.rock.gneiss"); + default: return "?"; + } +} + +static struct Color rock_color(uint8_t r) { + switch (r) { + case ROCK_GRANITE: return (struct Color){205, 165, 155, 255}; + case ROCK_BASALT: return (struct Color){ 70, 70, 85, 255}; + case ROCK_LIMESTONE: return (struct Color){215, 222, 228, 255}; + case ROCK_SANDSTONE: return (struct Color){215, 180, 120, 255}; + case ROCK_SHALE: return (struct Color){110, 110, 100, 255}; + case ROCK_SCHIST: return (struct Color){110, 145, 125, 255}; + case ROCK_GNEISS: return (struct Color){170, 150, 175, 255}; + default: return (struct Color){255, 0, 255, 255}; + } +} + +static struct Color temperature_color(double T) { + static const struct Color_Stop stops[] = { + {-40.0, { 30, 30, 120, 255 } }, + {-20.0, { 60, 90, 190, 255 } }, + { 0.0, { 90, 180, 210, 255 } }, + { 10.0, {120, 200, 130, 255 } }, + { 20.0, {225, 210, 100, 255 } }, + { 30.0, {215, 120, 60, 255 } }, + { 45.0, {170, 30, 30, 255 } }, + }; + return ramp_color(stops, (int)(sizeof(stops) / sizeof(stops[0])), T); +} + +static struct Color moisture_color(double m) { + static const struct Color_Stop stops[] = { + {0.0, {205, 180, 120, 255 } }, + {0.3, {170, 190, 110, 255 } }, + {0.6, { 80, 150, 90, 255 } }, + {0.8, { 50, 110, 150, 255 } }, + {1.0, { 25, 60, 140, 255 } }, + }; + return ramp_color(stops, (int)(sizeof(stops) / sizeof(stops[0])), m); +} + +// 年降水量(0..1,按全球 98 分位归一化):干黄 -> 绿 -> 蓝 +static struct Color precipitation_color(double p) { + static const struct Color_Stop stops[] = { + {0.00, {180, 150, 95, 255 } }, + {0.12, {210, 200, 130, 255 } }, + {0.30, {130, 190, 120, 255 } }, + {0.55, { 55, 140, 140, 255 } }, + {0.80, { 40, 95, 175, 255 } }, + {1.00, { 90, 60, 190, 255 } }, + }; + return ramp_color(stops, (int)(sizeof(stops) / sizeof(stops[0])), p); +} + +// 年温差半幅:越小越海洋性(蓝),越大越大陆性(红) +static struct Color seasonality_color(double a) { + static const struct Color_Stop stops[] = { + { 0.0, { 40, 80, 160, 255 } }, + { 5.0, { 80, 160, 170, 255 } }, + {10.0, {150, 195, 120, 255 } }, + {16.0, {230, 190, 90, 255 } }, + {24.0, {210, 110, 60, 255 } }, + {35.0, {150, 30, 40, 255 } }, + }; + return ramp_color(stops, (int)(sizeof(stops) / sizeof(stops[0])), a); +} + +// 水系:水面按流量深浅上色,陆地退成灰绿底图。 +// 流量跨四个数量级,用对数映射。 +static struct Color river_color(double q, uint8_t is_channel, + double water_depth, uint8_t surface) { + if (water_depth > 0.0) { + // 湖泊:越深越暗 + double t = water_depth / 400.0; + if (t > 1.0) t = 1.0; + return (struct Color){ (unsigned char)(70 - 50 * t), + (unsigned char)(130 - 80 * t), + (unsigned char)(200 - 60 * t), 255 }; + } + if (surface == SURFACE_WATER || surface == SURFACE_ICE) { + return (struct Color){ 60, 105, 165, 255 }; + } + if (is_channel) { + double t = (log10(q) - log10(0.5)) / (log10(200000.0) - log10(0.5)); + if (t < 0.0) t = 0.0; + if (t > 1.0) t = 1.0; + // 小溪浅青 -> 大河深蓝紫 + return (struct Color){ (unsigned char)(150 - 110 * t), + (unsigned char)(215 - 130 * t), + (unsigned char)(235 - 55 * t), 255 }; + } + return (struct Color){ 96, 108, 92, 255 }; +} + +// 山体阴影。地形起伏随缩放变化极大,所以垂直夸张跟着 mpp 自适应: +// 整颗星球视图需要放大几十倍才看得出山脉,局部视图 1 倍就够。 +// +// mpp 是**采样网格**的间距,exag_mpp 是**屏幕像素**的间距。移动时采样 +// 网格会变粗(div=4),把两者分开,阴影强度才不会随分辨率变化。 +static double shade_at(const struct Map_Sample *buf, int stride, int w, int h, + int px, int py, double mpp, double exag_mpp) { + int x0 = (px > 0) ? px - 1 : px; + int x1 = (px < w - 1) ? px + 1 : px; + int y0 = (py > 0) ? py - 1 : py; + int y1 = (py < h - 1) ? py + 1 : py; + + double exag = exag_mpp / 200.0; + if (exag < 1.0) exag = 1.0; + if (exag > 40.0) exag = 40.0; + + double dzdx = (buf[(size_t)py * stride + x1].elevation - + buf[(size_t)py * stride + x0].elevation) / + ((x1 - x0) * mpp) * exag; + double dzdy = (buf[(size_t)y1 * stride + px].elevation - + buf[(size_t)y0 * stride + px].elevation) / + ((y1 - y0) * mpp) * exag; + + // 法线 N = (-dz/dx, -dz/dy, 1);光源来自西北上方,已归一化 + double nx = -dzdx, ny = -dzdy, nz = 1.0; + double len = sqrt(nx * nx + ny * ny + nz * nz); + double d = (nx * -0.6 + ny * -0.6 + nz * 0.53) / len; + if (d < 0.0) d = 0.0; + + return 0.45 + 0.55 * d; +} + +static struct Color apply_shade(struct Color c, double shade) { + double r = c.r * shade, g = c.g * shade, b = c.b * shade; + if (r > 255.0) r = 255.0; + if (g > 255.0) g = 255.0; + if (b > 255.0) b = 255.0; + c.r = (unsigned char)r; + c.g = (unsigned char)g; + c.b = (unsigned char)b; + return c; +} + +struct Colorize_Ctx { + const struct Map_Sample *buf; + struct Color *pixels; + int img_w, img_h; // 输出图像尺寸 + int samp_w, samp_h; // 采样网格尺寸(可能是图像的 1/div) + int div; // 每个采样点覆盖多少像素 + double samp_mpp; // 采样网格间距 + double exag_mpp; // 屏幕像素间距(只影响阴影的垂直夸张) + enum Map_Mode mode; +}; + +// 逐**采样点**上色,再把它覆盖的 div x div 个像素一起填掉。 +// 移动时 div>1,这样连上色的开销也按 div^2 一起降下来——不然输出端 +// 还是 36 万次循环,采样白省了。 +static void colorize_rows(void *ctx, int y0, int y1) { + struct Colorize_Ctx *c = (struct Colorize_Ctx *)ctx; + int div = c->div > 0 ? c->div : 1; + for (int sy = y0; sy < y1; sy++) { + int py0 = sy * div; + int py1 = py0 + div; + if (py1 > c->img_h) py1 = c->img_h; + if (py0 >= c->img_h) break; + + for (int sx = 0; sx < c->samp_w; sx++) { + int px0 = sx * div; + int px1 = px0 + div; + if (px1 > c->img_w) px1 = c->img_w; + if (px0 >= c->img_w) break; + + const struct Map_Sample *s = c->buf + (size_t)sy * c->samp_w + sx; + struct Color col; + bool shaded = true; + + switch (c->mode) { + case MAP_MODE_SURFACE: + col = surface_color(s->surface_type); + break; + case MAP_MODE_ROCK: + col = rock_color(s->rock_type); + break; + case MAP_MODE_TEMPERATURE: + col = temperature_color(s->temperature); + shaded = false; + break; + case MAP_MODE_PRECIPITATION: + col = precipitation_color(s->precipitation); + shaded = false; + break; + case MAP_MODE_MOISTURE: + col = moisture_color(s->moisture); + shaded = false; + break; + case MAP_MODE_SEASONALITY: + col = seasonality_color(s->seasonality); + shaded = false; + break; + case MAP_MODE_RIVER: + col = river_color(s->discharge, s->is_channel, + s->water_depth, s->surface_type); + shaded = (s->is_channel == 0 && s->water_depth <= 0.0f); + break; + case MAP_MODE_SNOW: + col = snow_color(s); + shaded = (s->snow_cover < 0.05f && s->ice_thick <= 0.0f); + break; + case MAP_MODE_WATER_TEMP: + col = water_temp_color(s); + shaded = false; + break; + case MAP_MODE_TIDE: + col = tide_color(s); + shaded = false; + break; + case MAP_MODE_ELEVATION: + default: + col = elevation_color(s->elevation); + break; + } + + if (shaded) { + col = apply_shade(col, shade_at(c->buf, c->samp_w, + c->samp_w, c->samp_h, + sx, sy, c->samp_mpp, + c->exag_mpp)); + } + + for (int py = py0; py < py1; py++) { + struct Color *row = c->pixels + (size_t)py * c->img_w; + for (int px = px0; px < px1; px++) row[px] = col; + } + } + } +} + +static void colorize_buffer(const struct Map_Sample *buf, struct Color *pixels, + int img_w, int img_h, + int samp_w, int samp_h, int div, + double samp_mpp, double exag_mpp, + enum Map_Mode mode, int threads) { + struct Colorize_Ctx ctx; + ctx.buf = buf; + ctx.pixels = pixels; + ctx.img_w = img_w; + ctx.img_h = img_h; + ctx.samp_w = samp_w; + ctx.samp_h = samp_h; + ctx.div = div; + ctx.samp_mpp = samp_mpp; + ctx.exag_mpp = exag_mpp; + ctx.mode = mode; + run_rows(threads, samp_h, colorize_rows, &ctx); +} + +// =============================================================== +// 对外:纯渲染 +// =============================================================== + +struct Image map_render_image(struct World *w, enum Map_Mode mode, + double origin_x, double origin_y, double mpp, + int img_w, int img_h, int threads) { + return map_render_image_lod(w, mode, origin_x, origin_y, mpp, + img_w, img_h, threads, -1); +} + +struct Image map_render_image_lod(struct World *w, enum Map_Mode mode, + double origin_x, double origin_y, double mpp, + int img_w, int img_h, int threads, int lod) { + if (img_w < 1) img_w = 1; + if (img_h < 1) img_h = 1; + threads = default_threads(threads); + + size_t n = (size_t)img_w * (size_t)img_h; + struct Map_Sample *buf = malloc(sizeof(struct Map_Sample) * n); + struct Color *pixels = malloc(sizeof(struct Color) * n); + + struct Image img = {0}; + if (buf == NULL || pixels == NULL) { + free(buf); + free(pixels); + return img; + } + + sample_buffer(w, buf, img_w, img_h, origin_x, origin_y, mpp, mode, lod, threads); + colorize_buffer(buf, pixels, img_w, img_h, img_w, img_h, 1, + mpp, mpp, mode, threads); + + free(buf); + + img.data = pixels; + img.width = img_w; + img.height = img_h; + img.mipmaps = 1; + img.format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8; + return img; +} + +const char *map_mode_name(enum Map_Mode mode) { + switch (mode) { + case MAP_MODE_SURFACE: return _("map.mode.surface"); + case MAP_MODE_ROCK: return _("map.mode.rock"); + case MAP_MODE_TEMPERATURE: return _("map.mode.temperature"); + case MAP_MODE_PRECIPITATION: return _("map.mode.precipitation"); + case MAP_MODE_MOISTURE: return _("map.mode.moisture"); + case MAP_MODE_SEASONALITY: return _("map.mode.seasonality"); + case MAP_MODE_RIVER: return _("map.mode.river"); + case MAP_MODE_SNOW: return _("map.mode.snow"); + case MAP_MODE_WATER_TEMP: return _("map.mode.water_temp"); + case MAP_MODE_TIDE: return _("map.mode.tide"); + case MAP_MODE_ELEVATION: + default: return _("map.mode.elevation"); + } +} + +// =============================================================== +// 交互视图 +// =============================================================== + +#define MAP_MIN_MPP 4.0 // 最近:1 像素 4 米 +#define MAP_MAX_MPP_FRACTION 0.5 // 最远:整个世界占屏幕宽度的一半 + +void map_init(struct Map_View *v, struct World *w) { + memset(v, 0, sizeof(*v)); + v->world = w; + v->mode = MAP_MODE_ELEVATION; + v->render_scale = 2.0f; + v->threads = default_threads(0); + v->move_div = MAP_MOVE_DIV; + v->samp_div = 1; + v->last_ox = v->last_oy = 1e30; // 保证第一帧算成"动过" + + // 初始视角:看整颗星球,中心放在 (0,0) 附近的赤道 + v->center.x = 0.0; + v->center.y = (double)WORLD_H * 0.5; + v->mpp = (double)WORLD_W / 700.0; +} + +void map_free(struct Map_View *v) { + if (v->texture_valid) { + UnloadTexture(v->texture); + UnloadImage(v->image); + v->texture_valid = false; + } + free(v->samples); + v->samples = NULL; +} + +// 重建纹理/缓冲(窗口尺寸或 render_scale 变化时) +static bool map_ensure_targets(struct Map_View *v) { + int sw = GetScreenWidth(); + int sh = GetScreenHeight(); + int tw = (int)((float)sw / v->render_scale) + 1; + int th = (int)((float)sh / v->render_scale) + 1; + if (tw < 1) tw = 1; + if (th < 1) th = 1; + + if (v->texture_valid && tw == v->tex_w && th == v->tex_h) return true; + + if (v->texture_valid) { + UnloadTexture(v->texture); + UnloadImage(v->image); + v->texture_valid = false; + } + free(v->samples); + v->samples = NULL; + + v->tex_w = tw; + v->tex_h = th; + + v->image = GenImageColor(tw, th, BLACK); + if (v->image.data == NULL) return false; + + // 采样缓冲按**最大**尺寸分配(逐像素 + 一圈余量)。移动时会用更粗的 + // 采样网格(div=2/4),只是在同一块缓冲里换一个 stride 用, + // 不必每帧 realloc。 + v->samp_cap = (size_t)(tw + 2) * (size_t)(th + 2); + v->samples = malloc(sizeof(struct Map_Sample) * v->samp_cap); + if (v->samples == NULL) { + UnloadImage(v->image); + return false; + } + + v->texture = LoadTextureFromImage(v->image); + SetTextureFilter(v->texture, TEXTURE_FILTER_BILINEAR); + v->texture_valid = true; + v->has_rendered = false; + return true; +} + +// 当前视角对应的图像原点(左上角像素中心的世界坐标) +static void map_origin(const struct Map_View *v, double *ox, double *oy) { + *ox = v->center.x - (double)v->tex_w * 0.5 * v->mpp; + *oy = v->center.y - (double)v->tex_h * 0.5 * v->mpp; +} + +// div = 每个采样点覆盖多少像素。1 = 逐像素(静止时的最终画面), +// 2/4 = 平移过程中的粗略画面:采样点数按 div^2 减少, +// 纹理本来就是双线性放大的,所以粗一点几乎看不出来。 +static void map_resample(struct Map_View *v, int div) { + double ox, oy; + map_origin(v, &ox, &oy); + if (div < 1) div = 1; + + int sw = (v->tex_w + div - 1) / div + 2; + int sh = (v->tex_h + div - 1) / div + 2; + if ((size_t)sw * (size_t)sh > v->samp_cap) { sw = v->tex_w + 2; sh = v->tex_h + 2; div = 1; } + + v->samp_w = sw; + v->samp_h = sh; + v->samp_div = div; + + sample_buffer(v->world, v->samples, sw, sh, + ox, oy, v->mpp * (double)div, v->mode, -1, v->threads); + + v->sampled_hydro = mode_needs_hydro(v->mode); + v->sampled_river = mode_needs_river(v->mode); + + v->rendered_origin_x = ox; + v->rendered_origin_y = oy; + v->rendered_mpp = v->mpp; +} + +static void map_recolorize(struct Map_View *v) { + colorize_buffer(v->samples, (struct Color *)v->image.data, + v->tex_w, v->tex_h, v->samp_w, v->samp_h, v->samp_div, + v->mpp * (double)v->samp_div, v->mpp, v->mode, v->threads); + UpdateTexture(v->texture, v->image.data); + + v->rendered_mode = v->mode; + v->has_rendered = true; +} + +void map_update(struct Map_View *v) { + if (!map_ensure_targets(v)) return; + + // ---- 输入:平移 ---- + double dt = GetFrameTime(); + double pan = 700.0 * v->mpp * dt; + + if (IsKeyDown(KEY_W) || IsKeyDown(KEY_UP)) v->center.y -= pan; + if (IsKeyDown(KEY_S) || IsKeyDown(KEY_DOWN)) v->center.y += pan; + if (IsKeyDown(KEY_A) || IsKeyDown(KEY_LEFT)) v->center.x -= pan; + if (IsKeyDown(KEY_D) || IsKeyDown(KEY_RIGHT)) v->center.x += pan; + + if (IsMouseButtonDown(MOUSE_BUTTON_MIDDLE) || + IsMouseButtonDown(MOUSE_BUTTON_RIGHT)) { + struct Vector2 d = GetMouseDelta(); + v->center.x -= (double)d.x / v->render_scale * v->mpp; + v->center.y -= (double)d.y / v->render_scale * v->mpp; + } + + // ---- 输入:缩放(以光标下的世界点为锚) ---- + float wheel = GetMouseWheelMove(); + if (wheel != 0.0f) { + double ox, oy; + map_origin(v, &ox, &oy); + + struct Vector2 m = GetMousePosition(); + double sx = (double)m.x / v->render_scale; + double sy = (double)m.y / v->render_scale; + + double anchor_x = ox + sx * v->mpp; + double anchor_y = oy + sy * v->mpp; + + v->mpp *= pow(0.85, (double)wheel); + + double max_mpp = (double)WORLD_W / ((double)v->tex_w * MAP_MAX_MPP_FRACTION); + if (v->mpp < MAP_MIN_MPP) v->mpp = MAP_MIN_MPP; + if (v->mpp > max_mpp) v->mpp = max_mpp; + + // 让锚点仍然落回同一个屏幕位置 + double new_ox = anchor_x - sx * v->mpp; + double new_oy = anchor_y - sy * v->mpp; + v->center.x = new_ox + (double)v->tex_w * 0.5 * v->mpp; + v->center.y = new_oy + (double)v->tex_h * 0.5 * v->mpp; + } + + v->center.x = wrap_world_x(v->center.x); + v->center.y = clamp_world_y(v->center.y); + + // ---- 输入:切换配色 ---- + if (IsKeyPressed(KEY_M)) { + v->mode = (enum Map_Mode)((v->mode + 1) % MAP_MODE_COUNT); + } + // 数字键是**全局**的配色快捷键,所有用到世界地图的界面都一样。 + // 所以按住 Shift 时不响应——选址界面用 Shift+数字 直选候选点 + // (不然按 3 会同时"选第 3 个点"和"切成岩石图")。 + if (!map_ui_shift_down()) { + if (IsKeyPressed(KEY_ONE)) v->mode = MAP_MODE_ELEVATION; + if (IsKeyPressed(KEY_TWO)) v->mode = MAP_MODE_SURFACE; + if (IsKeyPressed(KEY_THREE)) v->mode = MAP_MODE_ROCK; + if (IsKeyPressed(KEY_FOUR)) v->mode = MAP_MODE_TEMPERATURE; + if (IsKeyPressed(KEY_FIVE)) v->mode = MAP_MODE_PRECIPITATION; + if (IsKeyPressed(KEY_SIX)) v->mode = MAP_MODE_MOISTURE; + if (IsKeyPressed(KEY_SEVEN)) v->mode = MAP_MODE_SEASONALITY; + if (IsKeyPressed(KEY_EIGHT)) v->mode = MAP_MODE_RIVER; + if (IsKeyPressed(KEY_NINE)) v->mode = MAP_MODE_SNOW; + if (IsKeyPressed(KEY_ZERO)) v->mode = MAP_MODE_WATER_TEMP; + if (IsKeyPressed(KEY_MINUS)) v->mode = MAP_MODE_TIDE; + } + + // ---- 只在必要时重算 ---- + double ox, oy; + map_origin(v, &ox, &oy); + + // 这一帧视角动了没有?动了就先用粗分辨率顶住,停下来再精修。 + bool moved = (ox != v->last_ox) || (oy != v->last_oy) || + (v->mpp != v->last_mpp); + v->last_ox = ox; v->last_oy = oy; v->last_mpp = v->mpp; + + bool need_hydro = mode_needs_hydro(v->mode); + bool need_river = mode_needs_river(v->mode); + + bool need_sample = !v->has_rendered || + v->mpp != v->rendered_mpp || + ox != v->rendered_origin_x || + oy != v->rendered_origin_y || + (need_hydro && !v->sampled_hydro) || + (need_river && !v->sampled_river); + + if (need_sample) { + map_resample(v, moved ? v->move_div : 1); + map_recolorize(v); + } else if (v->samp_div > 1 && !moved) { + map_resample(v, 1); // 停下来了:补一帧全分辨率 + map_recolorize(v); + } else if (v->mode != v->rendered_mode) { + map_recolorize(v); // 换配色不用重采样 + } +} + +// --------------------------------------------------------------- +// HUD +// --------------------------------------------------------------- + +static void draw_panel(struct Vector2 pos, float w, float h) { + DrawRectangle((int)pos.x, (int)pos.y, (int)w, (int)h, + (struct Color){0, 0, 0, 150}); +} + +static void draw_text_shadow(struct Font font, const char *text, + struct Vector2 pos, float size, float spacing) { + DrawTextEx(font, text, (struct Vector2){pos.x + 1.0f, pos.y + 1.0f}, + size, spacing, (struct Color){0, 0, 0, 200}); + DrawTextEx(font, text, pos, size, spacing, text_color); +} + +// 把米数格式化成好读的字符串 +static void format_distance(double meters, char *out, size_t n) { + if (meters >= 1000000.0) snprintf(out, n, "%.0f km", meters / 1000.0); + else if (meters >= 1000.0) snprintf(out, n, "%.1f km", meters / 1000.0); + else snprintf(out, n, "%.0f m", meters); +} + +// 比例尺:取一个不超过屏宽 1/4 的"整数"距离 +static void draw_scale_bar(struct Map_View *v, struct Font font, + float size, float spacing) { + static const double nice[] = {1, 2, 5, 10, 20, 50, + 100, 200, 500, 1000, 2000, 5000, + 10000, 20000, 50000, 100000, 200000, + 500000, 1000000, 2000000, 5000000}; + int n = (int)(sizeof(nice) / sizeof(nice[0])); + + double max_meters = v->mpp * (double)GetScreenWidth() * 0.25; + double chosen = nice[0]; + for (int i = 0; i < n; i++) { + if (nice[i] <= max_meters) chosen = nice[i]; + } + + double px = chosen / v->mpp; + float x = (float)GetScreenWidth() - 30.0f - (float)px; + float y = (float)GetScreenHeight() - 46.0f; + + DrawRectangle((int)(x - 10.0f), (int)(y - 22.0f), + (int)(px + 20.0f), 40, (struct Color){0, 0, 0, 150}); + DrawLineEx((struct Vector2){x, y}, (struct Vector2){x + (float)px, y}, + 2.0f, text_color); + DrawLineEx((struct Vector2){x, y - 5.0f}, (struct Vector2){x, y + 5.0f}, + 2.0f, text_color); + DrawLineEx((struct Vector2){x + (float)px, y - 5.0f}, + (struct Vector2){x + (float)px, y + 5.0f}, 2.0f, text_color); + + char buf[64]; + format_distance(chosen, buf, sizeof(buf)); + struct Vector2 sz = MeasureTextEx(font, buf, size, spacing); + draw_text_shadow(font, buf, + (struct Vector2){x + (float)px * 0.5f - sz.x * 0.5f, + y - 8.0f - sz.y}, + size, spacing); +} + +static void draw_legend(struct Map_View *v, struct Font font, + float size, float spacing) { + struct Color colors[SURFACE_COUNT]; + const char *names[SURFACE_COUNT]; + int n = 0; + + if (v->mode == MAP_MODE_SURFACE) { + for (int i = 0; i < SURFACE_COUNT; i++) { + colors[i] = surface_color((uint8_t)i); + names[i] = surface_name((uint8_t)i); + } + n = SURFACE_COUNT; + } else if (v->mode == MAP_MODE_ROCK) { + for (int i = 0; i < ROCK_COUNT; i++) { + colors[i] = rock_color((uint8_t)i); + names[i] = rock_name((uint8_t)i); + } + n = ROCK_COUNT; + } else { + return; // 连续量模式交给比例尺和读数,不画离散图例 + } + + float x = 20.0f; + float y = 92.0f; + float box = 16.0f; + // 条目数会变(地表 13 种),高度不够就压缩间距,别溢出屏幕 + float avail = (float)GetScreenHeight() - y - 70.0f; + float step = avail / (float)n; + if (step > 22.0f) step = 22.0f; + + for (int i = 0; i < n; i++) { + float by = y + (float)i * step; + DrawRectangle((int)x, (int)by, (int)box, (int)box, + (struct Color){0, 0, 0, 150}); + DrawRectangle((int)x + 2, (int)by + 2, + (int)box - 4, (int)box - 4, colors[i]); + draw_text_shadow(font, names[i], + (struct Vector2){x + box + 8.0f, by - 1.0f}, + size * 0.75f, spacing); + } +} + +void map_world_to_screen(const struct Map_View *v, double wx, double wy, + double *sx, double *sy) { + double ox, oy; + map_origin(v, &ox, &oy); + double dx = wrap_world_x(wx - v->center.x + (double)WORLD_W * 0.5) - + (double)WORLD_W * 0.5; + double px = (v->center.x + dx - ox) / v->mpp; + double py = (wy - oy) / v->mpp; + if (sx) *sx = px * (double)v->render_scale; + if (sy) *sy = py * (double)v->render_scale; +} + +void map_draw(struct Map_View *v, struct Font font, float font_size, + float spacing) { + if (v->texture_valid) { + DrawTextureEx(v->texture, (struct Vector2){0.0f, 0.0f}, 0.0f, + v->render_scale, WHITE); + } + + // ---- 中心准星 ---- + float cx = (float)GetScreenWidth() * 0.5f; + float cy = (float)GetScreenHeight() * 0.5f; + DrawLine((int)cx - 8, (int)cy, (int)cx + 8, (int)cy, + (struct Color){255, 255, 255, 120}); + DrawLine((int)cx, (int)cy - 8, (int)cx, (int)cy + 8, + (struct Color){255, 255, 255, 120}); + + // ---- 左上:世界信息 ---- + char line[256]; + float small = font_size * 0.8f; + + draw_panel((struct Vector2){10.0f, 10.0f}, 400.0f, 72.0f); + draw_text_shadow(font, v->world->config.name, + (struct Vector2){20.0f, 16.0f}, font_size, spacing); + { + // 当前世界时间。随时间变化的配色(积雪/水温/冰情)就是按它采的, + // 所以必须显示出来,否则看不懂图上为什么是这个季节。 + struct Planet_Params *pp = &v->world->planet; + double doy = astro_day_of_year(pp, &v->world->now); + double years = v->world->now.seconds / pp->year_seconds; + snprintf(line, sizeof(line), "%s: %llu %s: %d %s: %.0f / %.0f", + _("map.hud.seed"), (unsigned long long)v->world->seed, + _("map.hud.year"), (int)years, + _("map.hud.day"), doy, pp->year_days); + } + draw_text_shadow(font, line, (struct Vector2){20.0f, 46.0f}, small, spacing); + + // ---- 右上:当前配色 ---- + struct Vector2 mode_sz = MeasureTextEx(font, map_mode_name(v->mode), + font_size, spacing); + float mw = mode_sz.x + 40.0f; + draw_panel((struct Vector2){(float)GetScreenWidth() - mw - 10.0f, 10.0f}, + mw, 40.0f); + draw_text_shadow(font, map_mode_name(v->mode), + (struct Vector2){(float)GetScreenWidth() - mw + 10.0f, + 20.0f}, + font_size, spacing); + + draw_legend(v, font, font_size, spacing); + + // ---- 底部:坐标 / 缩放 / 操作提示 ---- + double lat = climate_latitude(v->center.y); // 与气候层用同一个换算 + double lon = (v->center.x / (double)WORLD_W) * 360.0 - 180.0; + + char dist[32]; + format_distance(v->mpp, dist, sizeof(dist)); + + snprintf(line, sizeof(line), + "%s: X %.0f m Y %.0f m | %.2f%s %.2f%s | %s: %s/px", + _("map.hud.center"), + v->center.x, v->center.y, + fabs(lat), (lat >= 0.0) ? _("map.hud.north") : _("map.hud.south"), + fabs(lon), (lon >= 0.0) ? _("map.hud.east") : _("map.hud.west"), + _("map.hud.scale"), dist); + + struct Vector2 info_sz = MeasureTextEx(font, line, small, spacing); + draw_panel((struct Vector2){10.0f, + (float)GetScreenHeight() - 40.0f}, + info_sz.x + 20.0f, 30.0f); + draw_text_shadow(font, line, (struct Vector2){20.0f, + (float)GetScreenHeight() - 35.0f}, small, spacing); + + draw_scale_bar(v, font, small, spacing); + + if (v->mpp <= MAP_MIN_MPP * 1.001) { + draw_text_shadow(font, _("map.hud.max_zoom"), + (struct Vector2){20.0f, + (float)GetScreenHeight() - 70.0f}, + small, spacing); + } +} diff --git a/src/map.h b/src/map.h new file mode 100644 index 0000000..4b512d1 --- /dev/null +++ b/src/map.h @@ -0,0 +1,130 @@ +#ifndef MAP_H +#define MAP_H + +#include +#include +#include +#include +#include "world.h" + +#ifndef _ +#define _(STRING) gettext(STRING) +#endif + +// --------------------------------------------------------------- +// 地图配色模式 —— 都是"便宜"的:一次 terrain_sample 就够, +// 不含 104 种化合物的逐点计算(那需要一个单独的线程化模式)。 +// --------------------------------------------------------------- +enum Map_Mode { + MAP_MODE_ELEVATION = 0, // 高程分层设色 + 山体阴影 + MAP_MODE_SURFACE, // 地表/生物群系 + MAP_MODE_ROCK, // 主导岩石类型 + MAP_MODE_TEMPERATURE, // 年均温 + MAP_MODE_PRECIPITATION, // 年降水量 + MAP_MODE_MOISTURE, // 干旱指数(P/PET)——生物群系真正用的量 + MAP_MODE_SEASONALITY, // 年温差半幅(大陆性) + MAP_MODE_RIVER, // 水系:流量定宽,湖泊另标 + // 下面三个是**随时间变化**的量,按当前世界时间采样: + MAP_MODE_SNOW, // 积雪:雪水当量 + 覆盖率(冬积春消) + MAP_MODE_WATER_TEMP, // 水温与冰情(结冰期水温被冰点夹住) + MAP_MODE_TIDE, // 潮差(地理放大后的平均潮差) + MAP_MODE_COUNT +}; + +// 每个采样点需要的字段(不含 104 维化合物,那太贵) +struct Map_Sample { + float elevation; + float temperature; + float moisture; + float vegetation; + float seasonality; + float precipitation; + float discharge; // 河流流量 m^3/s(地图模式下不参与化合物计算) + float water_depth; // 湖泊水深 + uint8_t is_channel; // 该像素是否落在河道水面内 + uint8_t surface_type; + uint8_t soil_type; + uint8_t rock_type; + uint8_t is_water; // 海/湖/河道 + float swe_mm; // 当月雪水当量 mm + float snow_cover; // 当月积雪覆盖率 0..1 + float water_temp; // 当月水温 ℃ + float ice_thick; // 当月冰厚 m + float tidal_range; // 平均潮差 m + float tidal_form; // 潮型因子 (K1+O1)/(M2+S2) +}; + +// --------------------------------------------------------------- +// 纯渲染:不碰窗口、不碰 GL,可以直接 ExportImage 出来看。 +// origin 是图像左上角第一个像素中心对应的世界坐标(米): +// pixel (px,py) 中心 = (origin_x + px*mpp, origin_y + py*mpp) +// 返回的 Image 需要用 UnloadImage 释放。 +// --------------------------------------------------------------- +struct Image map_render_image(struct World *w, enum Map_Mode mode, + double origin_x, double origin_y, double mpp, + int img_w, int img_h, int threads); + +// 同上,但强制指定采样精度档位(lod,见 chunk.h 的 terrain_sample_lod)。 +// lod < 0 = 按 mpp 自动。诊断/对比用。 +struct Image map_render_image_lod(struct World *w, enum Map_Mode mode, + double origin_x, double origin_y, double mpp, + int img_w, int img_h, int threads, int lod); + +const char *map_mode_name(enum Map_Mode mode); + +// 左右 Shift 是否按住。数字键在这个界面是配色快捷键(全局统一), +// 选址界面用 Shift+数字 直选候选点,靠这个区分。 +bool map_ui_shift_down(void); + +// --------------------------------------------------------------- +// 交互视图 +// --------------------------------------------------------------- +// 平移过程中每个采样点覆盖多少像素。地图是"每像素跑一遍地形+气候"的, +// 800x450 全精度要 60 ms 以上,按住 WASD 就没法看了;移动时用 1/16 的 +// 采样点顶住,松手后再补一帧全分辨率。 +#define MAP_MOVE_DIV 4 + +struct Map_View { + struct World *world; + + enum Map_Mode mode; + double mpp; // 每个像素多少米 + struct Vector2_double center; // 屏幕中心对应的世界坐标 + float render_scale; // 1=逐像素, 2=半分辨率再放大 + int move_div; // 平移时的降采样步长(1 = 不降) + + int tex_w, tex_h; + struct Texture texture; + struct Image image; // 复用的像素缓冲 + struct Map_Sample *samples; // 复用的采样缓冲(切换配色时免重采样) + size_t samp_cap; // samples 的容量(按最大网格分配) + int samp_w, samp_h, samp_div; // 本次采样网格的尺寸与步长 + bool sampled_hydro, sampled_river; // 当前缓冲里有没有水文层/河流层字段 + bool texture_valid; + + // 上一次真正采样时用的参数,用来判断是否需要重算 + double rendered_origin_x, rendered_origin_y, rendered_mpp; + enum Map_Mode rendered_mode; + bool has_rendered; + + // 上一帧的视角(用来判断"是不是正在移动") + double last_ox, last_oy, last_mpp; + + int threads; +}; + +void map_init(struct Map_View *v, struct World *w); +void map_free(struct Map_View *v); + +// 处理输入(平移/缩放/切换配色)并只在必要时重采样/重着色 +void map_update(struct Map_View *v); + +// 画出地图 + HUD +void map_draw(struct Map_View *v, struct Font font, float font_size, float spacing); + +// 世界坐标 -> 屏幕像素(窗口像素,含 render_scale)。x 方向取环绕后离 +// 视野中心最近的那一份。落点/资源标记要画在地图上就靠它。 +void map_world_to_screen(const struct Map_View *v, double wx, double wy, + double *sx, double *sy); + +#endif diff --git a/src/random.h b/src/random.h index 51d1ee6..75c9369 100644 --- a/src/random.h +++ b/src/random.h @@ -24,7 +24,14 @@ enum { CHUNK_NOISE_ORE_CO, CHUNK_NOISE_ORE_AU, CHUNK_NOISE_ROCK, - CHUNK_NOISE_MINERAL_BASE // 每个矿物占一个通道,共 MINERAL_COUNT 个 + CHUNK_NOISE_MINERAL_BASE, // 每个矿物占一个通道,共 MINERAL_COUNT 个 + // 水文/天气层的新通道。刻意避开矿物通道的区间,免得改动矿物分布。 + HYDRO_NOISE_TIDE = CHUNK_NOISE_MINERAL_BASE + 64, + WEATHER_NOISE_ENSO, + // 米级地表细节的三个倍频。刻意放在最后,不动已有通道。 + CHUNK_NOISE_GROUND_L, + CHUNK_NOISE_GROUND_M, + CHUNK_NOISE_GROUND_S }; uint64_t game_hash(uint64_t seed, uint64_t type, uint64_t subtype); diff --git a/src/river.c b/src/river.c new file mode 100644 index 0000000..b20214e --- /dev/null +++ b/src/river.c @@ -0,0 +1,1239 @@ +#include "river.h" +#include "world.h" +#include "chunk.h" +#include "noise.h" +#include "random.h" + +#include +#include +#include +#include + +// =============================================================== +// 参数(河流手感全在这里) +// =============================================================== +// 这个模型的骨架是标准的景观演化模型(LEM): +// +// 1. 降水 -> 径流 -> 汇流(填洼 + D8) +// 2. 河道向"均衡纵剖面"下切(S = ks * A^-0.5,也就是河流纵剖面的凹形) +// 3. 坡面扩散把山脊磨圆 +// 4. 泥沙按输移能力往下游走,超出能力的部分就地淤积 +// 5. 水面蒸发回馈给气候场,河岸让局地变湿润 +// +// 第 2 步是相对"构造基准面"下切的:河道不会被无限削低,而是停在均衡 +// 剖面上,于是高原被河流切成峡谷、盆地被泥沙填成平原,两者共存。 + +// ---- 河道判定 ---- +// 必须按"几格"来定,不能写死面积:一格本身就是 1600 km²,写成 +// 100 km² 会让每一格都满足条件(整个大陆都当成河道下切一遍)。 +// 6 格 ≈ 9600 km² 的汇水面积,对应一条像样的河。 +#define CHANNEL_MIN_CELLS 6.0 + +// ---- 均衡纵剖面 ---- +// ks = S * sqrt(A):真实河流的 ks 在 10~500 m 之间。95m 对应 +// A=1e8 m²(100km²) -> S=0.0095 (山区溪流) +// A=1e10 m²(1万km²) -> S=0.001 (大河) +// A=1e12 m²(100万km²) -> S=0.0001 (亚马逊下游) +#define KS_STEEPNESS 95.0 +#define ERODE_RATE 0.55 // 每次迭代向均衡剖面靠拢的比例 +#define MAX_CUT 260.0 // 单次迭代最大下切(米) +#define DIFFUSION 0.055 // 坡面扩散系数 +#define DIFFUSION_MAX_AREA 2.0e9 // 已经是河道就不再做坡面扩散 + +// ---- 泥沙输移 ---- +// 输移能力用"本格能带走的沉积厚度"来度量(米)。这是标定出来的形态学 +// 参数,不是物理定律:真实模型用 Qs = k*A^m*S^n 的输沙量纲,这里为了 +// 和侵蚀量直接相减而折成厚度。 +#define SED_CAP_K 0.085 +#define DEPOSIT_RATE 0.55 +#define MAX_FILL 90.0 +#define DELTA_RATE 0.60 // 入海泥沙里淤在河口/陆架的比例,其余算被带到深海 +#define DELTA_SEA_LEVEL 0.0 // 海床最多淤到海平面,防止海岸线无限外扩 + +// ---- 湖泊 ---- +// 光是"填洼深度够"还不够:分形地形上到处是几十米深的假坑。真实湖泊 +// 下面必有实际汇水,所以再要求湖底那一格本身有像样的内部流域。 +#define LAKE_MIN_DEPTH 120.0 +#define LAKE_MIN_CELLS 4.0 // 湖底格至少要有 4 格(≈6400km²)的内部汇水 +#define LAKE_MIN_BLOB 25 // 连通水面小于这个格数(4万km²)的当它是地形噪声,不算湖 +#define LAKE_FILL_RATE 0.25 // 湖泊淤积速率 + +// ---- 水力几何:Q -> 河宽/河深 ---- +// Leopold & Maddock 的幂律,指数满足 W^b·H^f·V^m 且 b+f+m=1: +// W = a·Q^0.5 H = c·Q^0.4 V = k·Q^0.1 +// 流速不单独造一个幂律,直接由连续性 V = Q/(W·H) 得到,三个量自动自洽。 +// Q=1000 -> W=285m H=4.1m V=0.86 m/s +// Q=15000 -> W=1.1km H=12m V=1.13 m/s (密西西比) +// Q=200000 -> W=4.0km H=34m V=1.45 m/s (亚马逊) +// 深泓比断面平均深 DEMPTH_MAX_RATIO 倍;枯水期深泓再按流量比缩放, +// 通航算的是枯水期深泓,不是平均值。 +#define WIDTH_A 9.0 +#define WIDTH_B 0.50 +#define DEPTH_A 0.26 +#define DEPTH_B 0.40 +#define DEPTH_MAX_RATIO 1.35 +#define LOWQ_SCALE 0.65 // 枯水期流量是年均的比例下限 +#define FLOODQ_SCALE 1.80 // 汛期流量上限倍率 +// 断面形状指数:0.5 = 抛物线,越小越接近矩形(山区峡谷) +#define SECTION_SHAPE 0.55 + +// ---- 泥沙(含沙量)---- +// 用 USLE 的思路算流域产沙,再乘一个输移比送到河道: +// A = R·K·LS·C·P +// R = 0.0487·P_mm^1.61 (Arnoldus 降水侵蚀力) +// LS = (tanθ/0.0896)^1.3 +// C = 1 - 0.85·植被覆盖 +// 注意这里算的是**坡面侵蚀量**,不是输沙量:输移比由后面的沿程落淤 +// 自动实现。早先在公式里乘过一次输移比、路由时又乘一次,等于把 +// 输移比平方了,河口含沙量因此低了一个数量级。 +#define EROSIVITY_A 0.0487 +#define EROSIVITY_B 1.61 +#define SOIL_K 0.035 // 土壤可蚀性 +#define SED_CALIB 0.10 // 整体标定:把 USLE 拉到"坡面侵蚀量"量级 +// 沿程落淤:这里必须区分"床沙质"和"冲泻质"。 +// 粉沙/黏土(黄河那种)一旦被冲起来就几乎不再落淤,可以带着 25kg/m³ +// 流过 700km 的平缓河段;砂和砾石才会随流速下降而淤积。 +// 早先所有粒径都用同一个落淤率,结果每格淤 5%,300 格之后衰减到 1e-7, +// 大河河口一粒沙都到不了。落淤率必须按床沙粒径分开。 +#define SED_DEP_SLOPE 0.0012 // 比降低于这个才开始淤 +#define SED_CONC_FLOOR 0.06 // 含沙量下限 kg/m^3,低于它就不再落淤 +// 坡面坡度:40km 网格上取不到真实坡面,用起伏半幅反推。 +// 起伏 150m 的平原 -> 0.04,起伏 2000m 的山地 -> 0.50,和真实地形同量级。 +#define HILLSLOPE_DIVISOR 4000.0 +#define HILLSLOPE_MIN 0.02 +#define HILLSLOPE_MAX 0.90 +#define ROCK_DENSITY 2650.0 // kg/m^3 + +// ---- 冰情 ---- +// Stefan 定律:冰厚 = k·sqrt(冻结指数),冻结指数 = 冬季水温的负值 × 封冻天数。 +// k=0.03 m/√(℃·day) 是湖冰的实测值:1000 ℃·day 约 0.95m 冰。 +#define ICE_SEASON_DAYS 150.0 +#define STEFAN_K 0.030 +#define ICE_MIN_M 0.02 // 薄于这个不算封冻 +#define WATER_TEMP_LAG 0.55 // 水温冬季比气温高多少(占季节振幅的比例) +#define ICE_FULL_M 0.30 // 冰厚到这个值就算整个封冻期 +#define JAM_GRAD_M 0.15 // 下游冰厚比上游厚这么多 -> 凌汛风险拉满 +#define JAM_Q_REF 800.0 // 流量参考值:大河冰坝更严重 +#define JAM_LOOKAHEAD 10 // 沿流向看几格(≈400km)来估计冰情梯度 +// 海冰:本模型没有独立的海表温度季节循环(海洋点算出来的"季节振幅"是 +// 气温的,比 SST 大得多),所以海冰仍用年均温阈值这个经验判据。 +// 湖冰和河冰走上面的 Stefan 定律——那才是用户真正要看的东西。 +#define SEA_ICE_TEMP_C (-8.0) +#define SEA_ICE_NOMINAL_M 1.20 +// 漫滩半宽:亚马逊约 50km,密西西比约 15km +#define VALLEY_A 45.0 +#define CARVE_FRACTION 0.45 // 河谷下切占"到下游落差"的比例 +#define CARVE_MAX 400.0 + +// ---- 气候反馈 ---- +#define EVAP_WET_BASE 0.15 // 陆地蒸发的水分可得性下限 +#define EVAP_WET_VEG 0.85 // 植被贡献 +#define CLIMATE_FEEDBACK_EVERY 4 // 每 N 次迭代重算一次气候场 + +// ---- 收敛 ---- +#define CONVERGE_EPS_M 0.35 // 单次迭代最大高程变化小于这个就停 + +#define SEC_PER_YEAR 31557600.0 // 365.25 天 +#define FILL_EPS 1.0e-6 // 填洼时保证严格下降的微量坡度 + +// =============================================================== +// 网格工具 +// =============================================================== + +static const int DX8[8] = { 1, 1, 0, -1, -1, -1, 0, 1 }; +static const int DY8[8] = { 0, 1, 1, 1, 0, -1, -1, -1 }; + +static inline int wrap_x(int x, int n) { + if (x < 0) x += n; + else if (x >= n) x -= n; + return x; +} + +// 一条"网格河道"需要的最小汇水面积(按格数换算,和分辨率无关) +static inline double channel_min_area(const struct River_Field *rf) { + return CHANNEL_MIN_CELLS * rf->cell_area; +} + +static inline double cell_dist(int d) { + return (d & 1) ? 1.4142135623730951 : 1.0; // 对角 / 正交 +} + +// =============================================================== +// 二叉最小堆(填洼的优先队列) +// =============================================================== + +struct Min_Heap { + int *node; + double *key; + int size; + int cap; +}; + +static bool heap_init(struct Min_Heap *h, int cap) { + h->node = malloc(sizeof(int) * cap); + h->key = malloc(sizeof(double) * cap); + h->size = 0; + h->cap = cap; + return h->node != NULL && h->key != NULL; +} + +static void heap_free(struct Min_Heap *h) { + free(h->node); + free(h->key); + h->node = NULL; h->key = NULL; h->size = h->cap = 0; +} + +static void heap_push(struct Min_Heap *h, int node, double key) { + int i = h->size++; + if (i >= h->cap) { h->size--; return; } // 不该发生:容量按格子数分配 + h->node[i] = node; + h->key[i] = key; + while (i > 0) { + int p = (i - 1) >> 1; + if (h->key[p] <= h->key[i]) break; + double tk = h->key[p]; h->key[p] = h->key[i]; h->key[i] = tk; + int tn = h->node[p]; h->node[p] = h->node[i]; h->node[i] = tn; + i = p; + } +} + +static int heap_pop(struct Min_Heap *h, double *key_out) { + if (h->size == 0) return -1; + int top = h->node[0]; + *key_out = h->key[0]; + h->size--; + if (h->size > 0) { + h->node[0] = h->node[h->size]; + h->key[0] = h->key[h->size]; + int i = 0; + for (;;) { + int l = 2 * i + 1, r = l + 1, m = i; + if (l < h->size && h->key[l] < h->key[m]) m = l; + if (r < h->size && h->key[r] < h->key[m]) m = r; + if (m == i) break; + double tk = h->key[m]; h->key[m] = h->key[i]; h->key[i] = tk; + int tn = h->node[m]; h->node[m] = h->node[i]; h->node[i] = tn; + i = m; + } + } + return top; +} + +// =============================================================== +// 内存 +// =============================================================== + +static void rf_alloc(struct River_Field *rf) { + const int n = RIVER_GRID; + const size_t nn = (size_t)n * n; + + rf->n = n; + rf->cell_m = RIVER_CELL_M; + rf->cell_area = RIVER_CELL_M * RIVER_CELL_M; + rf->topo_count = 0; + + rf->base = calloc(nn, sizeof(double)); + rf->elev = calloc(nn, sizeof(double)); + rf->filled = calloc(nn, sizeof(double)); + rf->delta = calloc(nn, sizeof(float)); + rf->area = calloc(nn, sizeof(float)); + rf->discharge = calloc(nn, sizeof(float)); + rf->width = calloc(nn, sizeof(float)); + rf->depth = calloc(nn, sizeof(float)); + rf->slope = calloc(nn, sizeof(float)); + rf->relief = calloc(nn, sizeof(float)); + rf->lake_depth = calloc(nn, sizeof(float)); + rf->veg = calloc(nn, sizeof(float)); + rf->runoff_mm = calloc(nn, sizeof(float)); + rf->depth_max = calloc(nn, sizeof(float)); + rf->sed_conc = calloc(nn, sizeof(float)); + rf->sed_load = calloc(nn, sizeof(float)); + rf->soil_loss = calloc(nn, sizeof(float)); + rf->water_temp = calloc(nn, sizeof(float)); + rf->ice_thick = calloc(nn, sizeof(float)); + rf->jam_risk = calloc(nn, sizeof(float)); + rf->perched = calloc(nn, sizeof(float)); + rf->season_amp = calloc(nn, sizeof(float)); + rf->bed = calloc(nn, 1); + rf->down = malloc(sizeof(int) * nn); + rf->strahler = calloc(nn, 1); + rf->topo = malloc(sizeof(int) * nn); +} + +static bool rf_ok(const struct River_Field *rf) { + return rf->base && rf->elev && rf->filled && rf->delta && rf->area && + rf->discharge && rf->width && rf->depth && rf->slope && rf->relief && + rf->lake_depth && rf->veg && rf->runoff_mm && rf->depth_max && + rf->sed_conc && rf->sed_load && rf->soil_loss && rf->water_temp && + rf->ice_thick && rf->jam_risk && rf->perched && rf->season_amp && + rf->bed && rf->down && + rf->strahler && rf->topo; +} + +void river_free(struct River_Field *rf) { + if (rf == NULL) return; + free(rf->base); free(rf->elev); free(rf->filled); + free(rf->delta); free(rf->area); free(rf->discharge); + free(rf->width); free(rf->depth); free(rf->slope); + free(rf->relief); free(rf->lake_depth);free(rf->veg); + free(rf->runoff_mm); free(rf->depth_max); free(rf->sed_conc); + free(rf->sed_load); free(rf->soil_loss); free(rf->water_temp); + free(rf->ice_thick); free(rf->jam_risk); free(rf->perched); + free(rf->season_amp); free(rf->bed); + free(rf->down); free(rf->strahler); free(rf->topo); + memset(rf, 0, sizeof(*rf)); +} + +// =============================================================== +// 第一步:从构造地形 + 气候场采样出基准面 +// =============================================================== + +static void sample_base(struct River_Field *rf, struct World *w) { + const int n = rf->n; + const double cm = rf->cell_m; + + for (int cy = 0; cy < n; cy++) { + double wy = ((double)cy + 0.5) * cm; + for (int cx = 0; cx < n; cx++) { + double wx = ((double)cx + 0.5) * cm; + int i = cy * n + cx; + + double z = terrain_base_elevation_coarse(wx, wy, w); + rf->base[i] = z; + + // 年径流深:Budyko 水量平衡(见 climate_runoff_mm)。 + // 亚马逊 P≈2300mm T≈26℃ -> PET≈1750mm -> 径流约 950mm, + // 换成流量 2.1e5 m³/s,和实测吻合。 + struct Climate_Sample cs; + climate_sample(&w->climate, w->seed, wx, wy, z, &cs); + rf->runoff_mm[i] = (float)climate_runoff_mm(cs.precip_mm, cs.temperature); + + // 起始植被:还没算河流,先用气候本身 + rf->veg[i] = (float)vegetation_potential(cs.temperature, cs.moisture, + cs.seasonal_amplitude, 0.0); + } + } + memcpy(rf->elev, rf->base, sizeof(double) * (size_t)n * n); +} + +// =============================================================== +// 第二步:填洼 + D8 + 汇流 + 级数 + 流量 +// =============================================================== + +static void route_flow(struct River_Field *rf) { + const int n = rf->n; + const size_t nn = (size_t)n * n; + + // ---- 优先淹没(Barnes 2014):从海洋和南北边界同时向内灌水 ---- + // 弹出顺序天然是按填平高程递增的,也就是一条拓扑序: + // 任何格子一定排在它的下游之后。后面汇流、级数、下切都直接复用它, + // 省掉一次 O(N log N) 的排序。 + struct Min_Heap h; + if (!heap_init(&h, (int)nn)) return; + + uint8_t *done = calloc(nn, 1); + if (done == NULL) { heap_free(&h); return; } + + for (int i = 0; i < (int)nn; i++) { + rf->filled[i] = rf->elev[i]; + int cy = i / n; + bool outlet = (rf->elev[i] < 0.0) || cy == 0 || cy == n - 1; + if (outlet) { done[i] = 1; heap_push(&h, i, rf->filled[i]); } + } + + int k = 0; + double key; + int i; + while ((i = heap_pop(&h, &key)) >= 0) { + rf->topo[k++] = i; + int cy = i / n, cx = i % n; + for (int d = 0; d < 8; d++) { + int ny = cy + DY8[d]; + if (ny < 0 || ny >= n) continue; + int nx = wrap_x(cx + DX8[d], n); + int j = ny * n + nx; + if (done[j]) continue; + done[j] = 1; + double f = key + FILL_EPS; + if (rf->elev[j] > f) f = rf->elev[j]; + rf->filled[j] = f; + heap_push(&h, j, f); + } + } + rf->topo_count = k; + free(done); + heap_free(&h); + + // ---- D8 要先算出来,湖泊判据要用汇水面积 ---- + // (顺序调整:原来是先判湖再定流向) + + // ---- D8:在填平的面上找最陡下降 ---- + for (int y = 0; y < n; y++) { + for (int x = 0; x < n; x++) { + int t = y * n + x; + rf->down[t] = -1; + rf->slope[t] = 0.0f; + rf->relief[t] = 0.0f; + if (rf->elev[t] < 0.0 || y == 0 || y == n - 1) continue; + + int best = -1; + double best_s = 0.0, best_drop = 0.0; + for (int d = 0; d < 8; d++) { + int ny = y + DY8[d]; + if (ny < 0 || ny >= n) continue; + int nx = wrap_x(x + DX8[d], n); + int j = ny * n + nx; + double drop = rf->filled[t] - rf->filled[j]; + if (drop <= 0.0) continue; + double s = drop / (cell_dist(d) * rf->cell_m); + if (s > best_s) { best_s = s; best = j; best_drop = drop; } + } + rf->down[t] = best; + rf->slope[t] = (float)best_s; + rf->relief[t] = (float)(best_drop > 0.0 ? best_drop : 0.0); + } + } + + // ---- 湖泊:填洼够深、而且湖底有真实汇水,才算湖 ---- + { + double lake_min_area = LAKE_MIN_CELLS * rf->cell_area; + // 先按深度打标 + for (int t = 0; t < (int)nn; t++) { + double d = rf->filled[t] - rf->elev[t]; + rf->lake_depth[t] = (d > LAKE_MIN_DEPTH) ? (float)d : 0.0f; + } + // 再按汇水面积过滤(area 还没累加,先只用深度,累加后再筛一遍) + (void)lake_min_area; + } + + // ---- 汇水面积(逆拓扑序 = 上游先算)---- + for (int t = 0; t < (int)nn; t++) rf->area[t] = (float)rf->cell_area; + for (int t = k - 1; t >= 0; t--) { + int c = rf->topo[t]; + int j = rf->down[c]; + if (j >= 0) rf->area[j] += rf->area[c]; + } + + // ---- 湖泊二次筛选:湖底那一格的内部汇水面积要够大 ---- + { + double lake_min_area = LAKE_MIN_CELLS * rf->cell_area; + for (int t = 0; t < (int)nn; t++) { + if (rf->lake_depth[t] > 0.0f && rf->area[t] < lake_min_area) + rf->lake_depth[t] = 0.0f; + } + } + + // ---- 流量:单位面积产流沿水系累积 ---- + for (int t = 0; t < (int)nn; t++) { + double mm = rf->runoff_mm[t]; + if (mm < 0.0) mm = 0.0; + rf->discharge[t] = (float)(mm * 0.001 * rf->cell_area / SEC_PER_YEAR); + } + for (int t = k - 1; t >= 0; t--) { + int c = rf->topo[t]; + int j = rf->down[c]; + if (j >= 0) rf->discharge[j] += rf->discharge[c]; + } + + // ---- 湖泊连通块过滤 ---- + // 分形地形上到处是又小又深的坑,"填洼深度够"这一条能放过一大片 + // 一格一个的假湖。真实的湖至少得连成一片,所以按 8 邻域标连通块, + // 把小于 LAKE_MIN_BLOB 格的整块抹掉。 + { + int *stack = malloc(sizeof(int) * nn); + int *label = calloc(nn, sizeof(int)); + int *sizes = malloc(sizeof(int) * nn); + if (stack && label && sizes) { + int ncomp = 0; + for (int i0 = 0; i0 < (int)nn; i0++) { + if (label[i0] || rf->lake_depth[i0] <= 0.0f) continue; + ncomp++; + int sp = 0; + stack[sp++] = i0; + label[i0] = ncomp; + int cnt = 0; + while (sp > 0) { + int c = stack[--sp]; + cnt++; + int cy = c / n, cx = c % n; + for (int dy = -1; dy <= 1; dy++) { + int yy = cy + dy; + if (yy < 0 || yy >= n) continue; + for (int dx = -1; dx <= 1; dx++) { + int j = yy * n + wrap_x(cx + dx, n); + if (label[j] || rf->lake_depth[j] <= 0.0f) continue; + label[j] = ncomp; + stack[sp++] = j; + } + } + } + sizes[ncomp] = cnt; + } + for (int i = 0; i < (int)nn; i++) { + if (label[i] && sizes[label[i]] < LAKE_MIN_BLOB) + rf->lake_depth[i] = 0.0f; + } + } + free(stack); free(label); free(sizes); + } + + // ---- Strahler 级数 ---- + memset(rf->strahler, 0, nn); + uint8_t *cnt = calloc(nn, 1); // 达到当前最大级数的子支数 + if (cnt) { + for (int t = k - 1; t >= 0; t--) { + int c = rf->topo[t]; + if (rf->strahler[c] == 0) rf->strahler[c] = 1; + int j = rf->down[c]; + if (j < 0) continue; + if (rf->strahler[c] == rf->strahler[j]) { + if (++cnt[j] >= 2) { rf->strahler[j]++; cnt[j] = 0; } + } else if (rf->strahler[c] > rf->strahler[j]) { + rf->strahler[j] = rf->strahler[c]; + cnt[j] = 1; + } + } + free(cnt); + } + + // ---- 河宽 / 河深 ---- + for (int t = 0; t < (int)nn; t++) { + double q = rf->discharge[t]; + if (q <= 0.0 || rf->area[t] < channel_min_area(rf)) { + rf->width[t] = 0.0f; + rf->depth[t] = 0.0f; + continue; + } + rf->width[t] = (float)(WIDTH_A * pow(q, WIDTH_B)); + rf->depth[t] = (float)(DEPTH_A * pow(q, DEPTH_B)); + rf->depth_max[t] = (float)(rf->depth[t] * DEPTH_MAX_RATIO); + } +} + +// =============================================================== +// 第三步:均衡剖面下切 + 坡面扩散 +// =============================================================== + +static void erode(struct River_Field *rf, double *before) { + const int n = rf->n; + const size_t nn = (size_t)n * n; + memcpy(before, rf->elev, sizeof(double) * nn); + + // ---- 河道:向均衡剖面下切(拓扑序,下游在前)---- + // z_target = 下游高程 + ks/sqrt(A) * 段长 + // 只往下切,不抬升 —— 所以构造基准高的地方会被刻出峡谷, + // 而已经低于均衡剖面的地方保持不动。 + for (int t = 0; t < rf->topo_count; t++) { + int c = rf->topo[t]; + int j = rf->down[c]; + if (j < 0) continue; + + double A = rf->area[c]; + if (A < channel_min_area(rf)) continue; + + int cx = c % n, cy = c / n; + int jx = j % n, jy = j / n; + int adx = cx > jx ? cx - jx : jx - cx; + if (adx > n / 2) adx = n - adx; + double step = ((adx == 1) && (cy != jy)) ? 1.4142135623730951 : 1.0; + step *= rf->cell_m; + + double s_eq = KS_STEEPNESS / sqrt(A); + double z_target = rf->elev[j] + s_eq * step; + double z = rf->elev[c]; + if (z <= z_target) continue; + + double cut = (z - z_target) * ERODE_RATE; + cut *= (1.0 - 0.75 * rf->veg[c]); // 植被固坡,侵蚀大幅减弱 + if (cut > MAX_CUT) cut = MAX_CUT; + if (cut > z - z_target) cut = z - z_target; + if (cut > 0.0) rf->elev[c] = z - cut; + } + + // ---- 坡面扩散:把河道之间的山脊磨圆 ---- + float *lap = malloc(sizeof(float) * nn); + if (lap) { + for (int y = 1; y < n - 1; y++) { + for (int x = 0; x < n; x++) { + int c = y * n + x; + if (rf->elev[c] < 0.0) { lap[c] = 0.0f; continue; } + int e = y * n + wrap_x(x + 1, n); + int w2 = y * n + wrap_x(x - 1, n); + int s = (y + 1) * n + x; + int nn2 = (y - 1) * n + x; + double mean = (rf->elev[e] + rf->elev[w2] + + rf->elev[s] + rf->elev[nn2]) * 0.25; + lap[c] = (float)(mean - rf->elev[c]); + } + } + for (int y = 1; y < n - 1; y++) { + for (int x = 0; x < n; x++) { + int c = y * n + x; + if (rf->elev[c] < 0.0) continue; + if (rf->area[c] > DIFFUSION_MAX_AREA) continue; // 已经是河道 + rf->elev[c] += DIFFUSION * lap[c]; + } + } + free(lap); + } +} + +// =============================================================== +// 第四步:泥沙输移与沉积 +// =============================================================== + +static double deposit(struct River_Field *rf, const double *before) { + const int n = rf->n; + const size_t nn = (size_t)n * n; + + // flux 用"折算成本格铺满的厚度(米)"来度量,和侵蚀量同量纲, + // 可以直接相减。这是标定出来的形态学写法,不是输沙量纲。 + float *flux = calloc(nn, sizeof(float)); + if (flux == NULL) return 0.0; + + for (int t = 0; t < (int)nn; t++) { + double ero = before[t] - rf->elev[t]; + flux[t] = (ero > 0.0) ? (float)ero : 0.0f; + } + + double max_fill = 0.0; + + // 逆拓扑序 = 上游在前 + for (int t = rf->topo_count - 1; t >= 0; t--) { + int c = rf->topo[t]; + int j = rf->down[c]; + double f = flux[c]; + + // ---- 尽头是湖泊:泥沙在湖里卸掉 ---- + if (j >= 0 && rf->lake_depth[j] > 0.0f) { + double dep = f * LAKE_FILL_RATE; + if (dep > MAX_FILL) dep = MAX_FILL; + rf->elev[j] += dep; + rf->lake_depth[j] = (float)((rf->filled[j] - rf->elev[j]) > 0.0 + ? (rf->filled[j] - rf->elev[j]) : 0.0); + if (dep > max_fill) max_fill = dep; + f -= dep; + } + + // ---- 尽头是大海:河口淤积成三角洲 ---- + // 黄河每年把黄土高原的泥沙搬到渤海,造出华北平原。 + if (j >= 0 && rf->elev[j] < 0.0) { + double room = DELTA_SEA_LEVEL - rf->elev[j]; + double dep = f * DELTA_RATE; + if (dep > room) dep = room; + if (dep > 0.0) { + rf->elev[j] += dep; + if (dep > max_fill) max_fill = dep; + f -= dep; + } + continue; // 剩下的随沿岸流带走 + } + + if (j < 0) continue; + + // ---- 超出输移能力的部分就地淤积(漫滩/冲积扇)---- + double cap = SED_CAP_K * sqrt(rf->area[c]) * rf->slope[c]; + if (f > cap) { + double dep = (f - cap) * DEPOSIT_RATE; + if (dep > MAX_FILL) dep = MAX_FILL; + if (dep > 0.0) { + rf->elev[c] += dep; + if (dep > max_fill) max_fill = dep; + f -= dep; + } + } + flux[j] += (float)f; + } + + // 同时更新累计改造量:采样时用它把基准面修正成最终地形 + for (int t = 0; t < (int)nn; t++) + rf->delta[t] = (float)(rf->elev[t] - rf->base[t]); + + free(flux); + return max_fill; +} + +// =============================================================== +// 第五步:气候反馈 —— 河流与植被让陆地蒸发更多,下风方向降水增加 +// =============================================================== + +static void climate_feedback(struct River_Field *rf, struct World *w) { + const int n = rf->n; + const double cm = rf->cell_m; + const int BX = (int)WORLD_BLOCK_COUNT_X; + const int BY = (int)WORLD_BLOCK_COUNT_Y; + + float *wet_sum = calloc((size_t)BX * BY, sizeof(float)); + float *cnt = calloc((size_t)BX * BY, sizeof(float)); + if (wet_sum == NULL || cnt == NULL) { free(wet_sum); free(cnt); return; } + + for (int y = 0; y < n; y++) { + double wy = ((double)y + 0.5) * cm; + int by = (int)(wy / (double)WORLD_BLOCK_SIZE); + if (by < 0) by = 0; if (by >= BY) by = BY - 1; + for (int x = 0; x < n; x++) { + double wx = ((double)x + 0.5) * cm; + int bx = (int)(wx / (double)WORLD_BLOCK_SIZE); + if (bx < 0) bx = 0; if (bx >= BX) bx = BX - 1; + int i = y * n + x; + if (rf->elev[i] < 0.0) continue; // 海洋不算 + + // 水分可得性 = 基础 + 植被 + 开阔水面 + double water_frac = 0.0; + if (rf->lake_depth[i] > 0.0f) water_frac = 1.0; + else if (rf->width[i] > 0.0f) + water_frac = rf->width[i] / rf->cell_m; + + double wet = EVAP_WET_BASE + EVAP_WET_VEG * rf->veg[i] + water_frac; + if (wet > 1.0) wet = 1.0; + + int b = by * BX + bx; + wet_sum[b] += (float)wet; + cnt[b] += 1.0f; + } + } + + // 重算气候场:climate->land_wet 直接进蒸发项 + for (int b = 0; b < BX * BY; b++) { + w->climate.land_wet[b] = (cnt[b] > 0.0f) ? (wet_sum[b] / cnt[b]) : 1.0f; + } + free(wet_sum); + free(cnt); + + climate_field_build(&w->climate, w->seed, w->blocks, w->plates); + + // 用新气候刷新产流和植被 + for (int y = 0; y < n; y++) { + double wy = ((double)y + 0.5) * cm; + for (int x = 0; x < n; x++) { + double wx = ((double)x + 0.5) * cm; + int i = y * n + x; + struct Climate_Sample cs; + climate_sample(&w->climate, w->seed, wx, wy, rf->elev[i], &cs); + rf->runoff_mm[i] = (float)climate_runoff_mm(cs.precip_mm, + cs.temperature); + rf->veg[i] = (float)vegetation_potential(cs.temperature, cs.moisture, + cs.seasonal_amplitude, 0.0); + } + } +} + + +// =============================================================== +// 第六步:泥沙 —— 流域产沙、沿程输移、含沙量 +// =============================================================== +// 含沙量不是拍出来的,是"流域侵蚀了多少 ÷ 河里流了多少水"。 +// 这也是黄河 25~35 kg/m³、亚马逊 0.2 kg/m³ 差两个数量级的来源: +// 黄土高原裸坡 + 450mm 暴雨 + 25% 的坡度,侵蚀模数是雨林的几十倍。 + +static double soil_loss_at(double precip_mm, double vegetation, double slope) { + if (precip_mm <= 0.0) return 0.0; + double R = EROSIVITY_A * pow(precip_mm, EROSIVITY_B); + double t = tan(slope); + if (t < 0.01) t = 0.01; + double LS = pow(t / 0.0896, 1.3); + double C = 1.0 - 0.85 * (vegetation < 0.0 ? 0.0 : (vegetation > 1.0 ? 1.0 : vegetation)); + if (C < 0.10) C = 0.10; + double A = R * SOIL_K * LS * C; // t/(ha·yr) + return A * 100.0 * SED_CALIB; // t/(km^2·yr),坡面侵蚀量 +} + +static void compute_sediment(struct River_Field *rf, struct World *w) { + const int n = rf->n; + const size_t nn = (size_t)n * n; + const double km2 = rf->cell_area / 1.0e6; + + // ---- 1) 本地产沙 ---- + // 坡度因子用"到下游的比降"——40km 网格上没有坡面坡度的概念, + // 河道比降是真实量出来的地形量。植被用河流层自己的(含河岸提升)。 + for (size_t i = 0; i < nn; i++) { + if (rf->elev[i] < 0.0) { rf->soil_loss[i] = 0.0f; continue; } + double wx = ((double)(i % n) + 0.5) * rf->cell_m; + double wy = ((double)(i / n) + 0.5) * rf->cell_m; + struct Climate_Sample cs; + climate_sample(&w->climate, w->seed, wx, wy, rf->elev[i], &cs); + double relief = terrain_relief_amplitude(wx, wy, w); + double hslope = relief / HILLSLOPE_DIVISOR; + if (hslope < HILLSLOPE_MIN) hslope = HILLSLOPE_MIN; + if (hslope > HILLSLOPE_MAX) hslope = HILLSLOPE_MAX; + rf->soil_loss[i] = (float)soil_loss_at(cs.precip_mm, rf->veg[i], hslope); + } + + // ---- 2) 河床质:比降 + 产沙模数 ---- + // 必须在输移之前定,因为落淤率取决于床沙粒径(见上面的注释)。 + // 这一步用产沙模数而不是含沙量——含沙量还没算出来。 + for (size_t i = 0; i < nn; i++) { + if (rf->elev[i] < 0.0 || rf->width[i] <= 0.0f) { + rf->bed[i] = RIVER_BED_NONE; + continue; + } + double sl = rf->slope[i]; + double fine = rf->soil_loss[i] / 800.0; // 越高越是细粒易蚀物质 + enum River_Bed b; + if (sl > 0.0100) b = RIVER_BED_BEDROCK; + else if (sl > 0.0040) b = (fine > 3.0) ? RIVER_BED_GRAVEL : RIVER_BED_BOULDER; + else if (sl > 0.0012) b = (fine > 3.0) ? RIVER_BED_SILT : RIVER_BED_GRAVEL; + else if (sl > 0.0004) b = (fine > 2.0) ? RIVER_BED_SILT : RIVER_BED_SAND; + else b = (fine > 1.0) ? RIVER_BED_SILT : RIVER_BED_SAND; + rf->bed[i] = (uint8_t)b; + } + + // ---- 3) 沿水系搬运:悬移质质量 = 产沙 + 上游来沙 - 落淤 ---- + // 落淤比例直接沿用形态学那一套(超出输移能力的部分就地沉积), + // 于是"三角洲/冲积平原"和"含沙量沿程递减"是同一个机制的两个侧面。 + double *mass = malloc(sizeof(double) * nn); // t/yr + if (mass == NULL) return; + for (size_t i = 0; i < nn; i++) + mass[i] = (rf->elev[i] >= 0.0) ? rf->soil_loss[i] * km2 : 0.0; + + for (int t = rf->topo_count - 1; t >= 0; t--) { + int c = rf->topo[t]; + int j = rf->down[c]; + double m = mass[c]; + + if (j >= 0 && rf->lake_depth[j] > 0.0f) { + double dep = m * LAKE_FILL_RATE; // 湖泊是沉沙池 + mass[c] = m - dep; + mass[j] += dep; + continue; + } + if (j < 0) continue; // 出图/内流盆地尽头 + + if (rf->elev[j] < 0.0) { // 入海:一部分进三角洲 + double dep = m * DELTA_RATE; + mass[c] = m - dep; + mass[j] += dep; + continue; + } + + double sl = rf->slope[c]; + double dep_base; + switch (rf->bed[c]) { + case RIVER_BED_SILT: dep_base = 0.0003; break; // 冲泻质,几乎不落淤 + case RIVER_BED_SAND: dep_base = 0.0015; break; + case RIVER_BED_GRAVEL: dep_base = 0.0040; break; + case RIVER_BED_BOULDER: dep_base = 0.0080; break; + default: dep_base = 0.0120; break; + } + double dep_frac = 0.0; + if (sl < SED_DEP_SLOPE) + dep_frac = dep_base * (1.0 - sl / SED_DEP_SLOPE); + if (dep_frac > 0.0) { + // 沉积受挟沙力下限约束:不能把含沙量一路压到 0。 + // 没有这个下限时,落淤率会随流程复利衰减,河口一粒沙都到不了。 + double q_vol = rf->discharge[c] * SEC_PER_YEAR; + double moved = m * dep_frac; + if (q_vol > 1.0) { + double conc_now = m * 1000.0 / q_vol; + if (conc_now > SED_CONC_FLOOR) { + double cap_moved = (conc_now - SED_CONC_FLOOR) / conc_now * m; + if (moved > cap_moved) moved = cap_moved; + } else { + moved = 0.0; + } + } + mass[c] = m - moved; + mass[j] += moved; + } else { + mass[j] += m; + } + } + + // ---- 4) 含沙量 = 质量通量 / 体积通量 ---- + for (size_t i = 0; i < nn; i++) { + double q = rf->discharge[i]; + double vol = q * SEC_PER_YEAR; // m^3/yr + double conc = (q > 1.0 && vol > 1.0) ? (mass[i] * 1000.0 / vol) : 0.0; + if (conc > 400.0) conc = 400.0; // 泥石流上限,防止爆表 + rf->sed_conc[i] = (float)conc; + rf->sed_load[i] = (float)mass[i]; + } + + free(mass); +} + +// =============================================================== +// 第七步:冰情与凌汛 +// =============================================================== +// 湖面结冰用 Stefan 定律(冰厚 = k·sqrt(冻结指数)),河流同理但水在流动, +// 冻结指数用水温而不是气温——水体热惯性让冬季水温明显高于气温。 +// +// 凌汛(冰坝洪水)的判据是"沿流向冰情在增强":上游先解冻,冰水一起冲进 +// 还封冻着的下游河段,壅成冰坝。黄河内蒙古段、松花江、勒拿河都是这个 +// 成因——共同点是河流从暖的纬度流向冷的纬度。 + +static void compute_ice(struct River_Field *rf, struct World *w) { + const int n = rf->n; + const size_t nn = (size_t)n * n; + + for (size_t i = 0; i < nn; i++) { + rf->water_temp[i] = 0.0f; rf->ice_thick[i] = 0.0f; + rf->jam_risk[i] = 0.0f; rf->season_amp[i] = 0.0f; + + // 冰情只发生在水面上:海洋、湖泊、河道 + bool ocean = (rf->elev[i] < 0.0); + bool lake = (rf->lake_depth[i] > 0.0f); + bool chan = (rf->width[i] > 0.0f); + if (!ocean && !lake && !chan) continue; + + double wx = ((double)(i % n) + 0.5) * rf->cell_m; + double wy = ((double)(i / n) + 0.5) * rf->cell_m; + struct Climate_Sample cs; + climate_sample(&w->climate, w->seed, wx, wy, rf->elev[i], &cs); + + double amp = cs.seasonal_amplitude; + rf->season_amp[i] = (float)amp; + + if (ocean) { + rf->water_temp[i] = (float)cs.temperature; + rf->ice_thick[i] = (cs.temperature < SEA_ICE_TEMP_C) + ? (float)SEA_ICE_NOMINAL_M : 0.0f; + continue; + } + + // 湖水热容比河水更大,冬季降温更少 + double lag = lake ? 0.75 : WATER_TEMP_LAG; + rf->water_temp[i] = (float)(cs.temperature - lag * amp * 0.5); + + // Stefan 定律:冰厚 = k·sqrt(冻结指数),冻结指数 = 冬季水温负值 × 封冻天数 + double t_winter = cs.temperature - lag * amp; + double fi = (t_winter < 0.0) ? -t_winter : 0.0; + double fdd = fi * ICE_SEASON_DAYS; + double ice = STEFAN_K * sqrt(fdd); + if (ice < ICE_MIN_M) ice = 0.0; + if (ice > 3.5) ice = 3.5; + rf->ice_thick[i] = (float)ice; + } + + // 凌汛:沿流向看 JAM_LOOKAHEAD 格,下游冰更厚就有壅塞风险 + for (size_t i = 0; i < nn; i++) { + if (rf->ice_thick[i] <= 0.0f) continue; + if (rf->elev[i] < 0.0 || rf->width[i] <= 0.0f) continue; // 只看河道 + int j = (int)i; + for (int k = 0; k < JAM_LOOKAHEAD && j >= 0; k++) j = rf->down[j]; + if (j < 0) continue; + double grad = rf->ice_thick[j] - rf->ice_thick[i]; + if (grad <= 0.0) continue; + + double g = grad / JAM_GRAD_M; if (g > 1.0) g = 1.0; + double q = rf->discharge[i] / JAM_Q_REF; if (q > 1.0) q = 1.0; + double s = rf->season_amp[i] / 15.0; if (s > 1.0) s = 1.0; + rf->jam_risk[i] = (float)(g * q * s); + } +} + +// =============================================================== +// 第八步:地上河 +// =============================================================== +// 黄河下游的"地上河":泥沙淤积把河床抬到两岸漫滩之上,全靠大堤束水。 +// 这个现象在本模型里是自然涌现的——只要淤积速率长期超过下切。 + +static void compute_perched(struct River_Field *rf) { + const int n = rf->n; + const size_t nn = (size_t)n * n; + + for (size_t i = 0; i < nn; i++) { + rf->perched[i] = 0.0f; + if (rf->elev[i] < 0.0 || rf->width[i] <= 0.0f) continue; + // 只有冲积河床才可能淤成地上河;基岩河道只会下切 + if (rf->bed[i] != RIVER_BED_SAND && rf->bed[i] != RIVER_BED_SILT) continue; + int cx = (int)(i % n), cy = (int)(i / n); + double sum = 0.0; int m = 0; + for (int dy = -1; dy <= 1; dy++) { + int yy = cy + dy; + if (yy < 0 || yy >= n) continue; + for (int dx = -1; dx <= 1; dx++) { + if (dx == 0 && dy == 0) continue; + int j = yy * n + wrap_x(cx + dx, n); + if (rf->elev[j] < 0.0 || rf->width[j] > 0.0f) continue; + sum += rf->elev[j]; m++; + } + } + if (m < 3) continue; + double d = rf->elev[i] - sum / m; + if (d > 0.0) rf->perched[i] = (float)d; + } +} + +// =============================================================== +// 主循环 +// =============================================================== + +#define RIVER_DEFAULT_ITER 18 + +void river_build(struct River_Field *rf, struct World *w, int iterations) { + if (rf == NULL || w == NULL) return; + if (iterations <= 0) iterations = RIVER_DEFAULT_ITER; + + rf_alloc(rf); + if (!rf_ok(rf)) { river_free(rf); return; } + + const size_t nn = (size_t)rf->n * rf->n; + double *before = malloc(sizeof(double) * nn); + if (before == NULL) { river_free(rf); return; } + + sample_base(rf, w); + route_flow(rf); + + for (int it = 0; it < iterations; it++) { + erode(rf, before); + deposit(rf, before); + + // 收敛判据:最大高程变化 + double max_delta = 0.0; + for (size_t t = 0; t < nn; t++) { + double d = fabs(rf->elev[t] - before[t]); + if (d > max_delta) max_delta = d; + } + + bool last = (it == iterations - 1); + if (!last && (it + 1) % CLIMATE_FEEDBACK_EVERY == 0) { + climate_feedback(rf, w); // 会重算气候场 + } + route_flow(rf); // 用新地形重新汇流 + + if (max_delta < CONVERGE_EPS_M) break; + } + + free(before); + + // ---- 定型:水力几何、泥沙、冰情 ---- + // 这三样都是"由收敛后的地形和水系推导出来的状态量",不参与迭代, + // 所以放在最后跑一次。泥沙和冰情都要重采样气候,实测约 0.4s。 + compute_sediment(rf, w); + compute_ice(rf, w); + compute_perched(rf); +} + +// =============================================================== +// 采样 +// =============================================================== + +// 点到线段的距离平方(不处理经度环绕——调用方已经把窗口绕好了) +static double seg_dist2(double px, double py, + double ax, double ay, double bx, double by) { + double vx = bx - ax, vy = by - ay; + double wx = px - ax, wy = py - ay; + double L2 = vx * vx + vy * vy; + double t = (L2 > 1e-12) ? (wx * vx + wy * vy) / L2 : 0.0; + if (t < 0.0) t = 0.0; + if (t > 1.0) t = 1.0; + double dx = wx - t * vx, dy = wy - t * vy; + return dx * dx + dy * dy; +} + +static double bilinear_delta(const struct River_Field *rf, double fx, double fy) { + const int n = rf->n; + int ix = (int)floor(fx), iy = (int)floor(fy); + double tx = fx - ix, ty = fy - iy; + if (tx < 0.0) { tx += 1.0; ix -= 1; } + if (ty < 0.0) { ty += 1.0; iy -= 1; } + + int x0 = wrap_x(ix, n), x1 = wrap_x(ix + 1, n); + int y0 = iy, y1 = iy + 1; + if (y0 < 0) y0 = 0; if (y0 >= n) y0 = n - 1; + if (y1 < 0) y1 = 0; if (y1 >= n) y1 = n - 1; + + double a = rf->delta[y0 * n + x0] * (1.0 - tx) + rf->delta[y0 * n + x1] * tx; + double b = rf->delta[y1 * n + x0] * (1.0 - tx) + rf->delta[y1 * n + x1] * tx; + return a * (1.0 - ty) + b * ty; +} + +void river_sample(const struct River_Field *rf, double wx, double wy, + struct River_Sample *out) { + river_sample_filtered(rf, wx, wy, rf ? channel_min_area(rf) : 0.0, out); +} + +void river_sample_filtered(const struct River_Field *rf, double wx, double wy, + double min_area, struct River_Sample *out) { + memset(out, 0, sizeof(*out)); + out->lake_surface = -1.0e30; + if (rf == NULL || rf->n == 0) return; + + const int n = rf->n; + const double cm = rf->cell_m; + + double fx = wx / cm - 0.5; + double fy = wy / cm - 0.5; + out->delta = bilinear_delta(rf, fx, fy); + + int cx = (int)floor(fx), cy = (int)floor(fy); + + // ---- 5x5 邻域里找最近的河道段 ---- + // 河道段 = 本格中心 -> 下游格中心。5x5 是为了不漏掉特大洪积平原的 + // 远岸(漫滩半宽最大约 50km,比一个格子还大)。 + double best_d2 = 1e300, best_q = 0.0, best_relief = 0.0, best_area = 0.0; + int best_cell = -1; + bool found = false; + + for (int dy = -2; dy <= 2; dy++) { + int yy = cy + dy; + if (yy < 0 || yy >= n) continue; + for (int dx = -2; dx <= 2; dx++) { + int xx = wrap_x(cx + dx, n); + int j = yy * n + xx; + if (rf->area[j] < min_area) continue; + + double ax = ((double)xx + 0.5) * cm; + double ay = ((double)yy + 0.5) * cm; + double bx = ax, by = ay; + int d = rf->down[j]; + if (d >= 0) { + int jx = d % n, jy = d / n; + bx = ((double)jx + 0.5) * cm; + by = ((double)jy + 0.5) * cm; + // 段跨过经度接缝时,取绕过 0 的那一侧 + if (bx - ax > (double)WORLD_W * 0.5) bx -= (double)WORLD_W; + if (bx - ax < -(double)WORLD_W * 0.5) bx += (double)WORLD_W; + } + double d2 = seg_dist2(wx, wy, ax, ay, bx, by); + if (d2 < best_d2) { + best_d2 = d2; + best_q = rf->discharge[j]; + best_relief = rf->relief[j]; + best_area = rf->area[j]; + best_cell = j; + found = true; + } + } + } + + if (found && best_q > 0.0 && best_cell >= 0) { + int bc = best_cell; + out->is_channel = true; + out->discharge = best_q; + out->area = best_area; + out->width = rf->width[bc]; + out->depth = rf->depth[bc]; + out->depth_max = rf->depth_max[bc]; + out->velocity = (rf->width[bc] * rf->depth[bc] > 0.0) + ? best_q / ((double)rf->width[bc] * rf->depth[bc]) : 0.0; + out->valley_half = VALLEY_A * pow(best_q, WIDTH_B); + out->dist = sqrt(best_d2); + + // 泥沙 / 冰情 / 形态:取最近那条河所在格的状态 + out->sed_conc = rf->sed_conc[bc]; + out->sed_load = rf->sed_load[bc]; + out->soil_loss = rf->soil_loss[bc]; + out->water_temp = rf->water_temp[bc]; + out->ice_thick = rf->ice_thick[bc]; + out->jam_risk = rf->jam_risk[bc]; + out->bed = rf->bed[bc]; + out->perched = rf->perched[bc]; + + // 洪枯季:大陆性越强洪枯比越大。通航按枯水期算,凌汛按汛期算。 + double season = rf->season_amp[bc] / 25.0; + if (season > 1.0) season = 1.0; + double low_m = 1.0 - (1.0 - LOWQ_SCALE) * season; + double flood_m = 1.0 + FLOODQ_SCALE * season; + out->low_q = best_q * low_m; + out->flood_q = best_q * flood_m; + // 水深按流量幂律缩放(H ~ Q^0.4) + out->depth_low = out->depth_max * pow(low_m, DEPTH_B); + out->ice_days = ICE_SEASON_DAYS * + (out->ice_thick >= ICE_FULL_M ? 1.0 + : out->ice_thick / ICE_FULL_M); + + // 河谷下切:深谷出现在落差大的河段,平原河段几乎不下切 + double vd = CARVE_FRACTION * best_relief; + if (vd > CARVE_MAX) vd = CARVE_MAX; + if (vd > 0.0 && out->valley_half > 0.0) { + double t = out->dist / out->valley_half; + double g = vd * exp(-t * t); + out->carve = g; + // 解析求导:坡度对地图渲染是每像素都要的,四次差分采样太贵 + out->slope = 2.0 * t / out->valley_half * g; + } + // 河道本身再压出一道窄槽,让河床低于漫滩 + double half = out->width * 0.5; + if (half > 0.0 && out->dist < half) { + out->carve += out->depth * (1.0 - out->dist / half); + out->slope += out->depth / half; + } + } + + // ---- 本格状态 ---- + // 先把"这个点所在格"的状态带出来(海冰、湖冰、含沙量、水温)。 + // 只在找到河道时赋值的话,纯海洋格拿不到冰厚,海冰会整片消失。 + // y 方向不环绕(两极是边界),越界就得夹住。这里以前只夹了 cx 没夹 cy, + // 在 y≈0 或 y≈WORLD_H 采样时会越界读(地图视图有 clamp_world_y 挡着, + // 所以一直没暴露;局部游戏层直接采样就撞上了——ASan 抓到的)。 + if (cy < 0) cy = 0; + if (cy >= n) cy = n - 1; + int ci = cy * n + wrap_x(cx, n); + out->water_temp = rf->water_temp[ci]; + out->ice_thick = rf->ice_thick[ci]; + if (!out->is_channel) { + out->sed_conc = rf->sed_conc[ci]; + out->sed_load = rf->sed_load[ci]; + out->soil_loss = rf->soil_loss[ci]; + out->jam_risk = rf->jam_risk[ci]; + out->bed = rf->bed[ci]; + out->perched = rf->perched[ci]; + } + if (rf->lake_depth[ci] > 0.0f) { + out->lake_depth = rf->lake_depth[ci]; + out->lake_surface = rf->elev[ci] + rf->lake_depth[ci]; + } + + out->vegetation = rf->veg[ci]; +} + +// =============================================================== +// 断面与通航 +// =============================================================== + +double river_depth_at(const struct River_Sample *rs, double dist) { + if (rs == NULL || rs->width <= 0.0 || rs->depth_max <= 0.0) return 0.0; + double half = rs->width * 0.5; + if (dist >= half) return 0.0; + double u = dist / half; + double w = 1.0 - u * u; + if (w < 0.0) w = 0.0; + return rs->depth_max * pow(w, SECTION_SHAPE); +} + +double river_navigable_width(const struct River_Sample *rs, double draft_m, + double ukc_frac) { + if (rs == NULL || rs->width <= 0.0 || draft_m <= 0.0) return 0.0; + double need = draft_m * (1.0 + ukc_frac); + // 用枯水期深泓:设计航道不能按汛期水深算,否则一年里有半年搁浅 + double hmax = (rs->depth_low > 0.0) ? rs->depth_low : rs->depth_max; + if (need >= hmax) return 0.0; + double r = need / hmax; + double u = 1.0 - pow(r, 1.0 / SECTION_SHAPE); + if (u <= 0.0) return 0.0; + return rs->width * sqrt(u); +} + +bool river_cell_is_channel(const struct River_Field *rf, double wx, double wy, + double min_area, double *discharge_out) { + if (rf == NULL || rf->n == 0) return false; + int cx = (int)floor(wx / rf->cell_m); + int cy = (int)floor(wy / rf->cell_m); + if (cy < 0 || cy >= rf->n) return false; + int i = cy * rf->n + wrap_x(cx, rf->n); + if (discharge_out) *discharge_out = rf->discharge[i]; + if (rf->elev[i] < 0.0) return false; + return rf->area[i] >= (float)min_area; +} + +double river_channel_min_area(const struct River_Field *rf) { + return channel_min_area(rf); +} + +bool river_submerged(const struct River_Field *rf, double wx, double wy, + double terrain_z, double *water_z) { + if (rf == NULL || rf->n == 0) return false; + const int n = rf->n; + int cx = (int)floor(wx / rf->cell_m); + int cy = (int)floor(wy / rf->cell_m); + if (cy < 0 || cy >= n) return false; + int ci = cy * n + wrap_x(cx, n); + if (rf->lake_depth[ci] <= 0.0f) return false; + + double surf = rf->elev[ci] + rf->lake_depth[ci]; + if (terrain_z >= surf) return false; + if (water_z) *water_z = surf; + return true; +} diff --git a/src/river.h b/src/river.h new file mode 100644 index 0000000..a36ba34 --- /dev/null +++ b/src/river.h @@ -0,0 +1,155 @@ +#ifndef RIVER_H +#define RIVER_H + +#include +#include +#include "terrain.h" +#include "climate.h" + +struct World; + +// =============================================================== +// 河流 / 水文 +// =============================================================== +// 世界的地形是 512km 的板块网格 + 分形起伏,本身没有排水系统。 +// 这一层在 40km 的水文网格上解一次完整的景观演化: +// +// 地形 --(气候场)--> 降水/径流 --(填洼+D8)--> 水系 +// --(均衡剖面下切)--> 河谷 --(泥沙输移)--> 冲积平原/三角洲 +// --(河流蒸发)--> 气候 ... +// +// 来回迭代到收敛,就得到既有水系、又有河谷和冲积平原的地形。 +// +// 网格取 1024x1024:WORLD_W / 1024 = 40000m,正好整除。 +// 40km 一格能把亚马逊级别的流域分成上千格,够撑起全球水系; +// 更细的河道形态(河宽、河谷断面)在采样时按流量解析地重建, +// 不需要存进网格里。 +// --------------------------------------------------------------- + +#define RIVER_GRID 1024 +#define RIVER_CELL_M ((double)WORLD_W / (double)RIVER_GRID) +#define RIVER_CELLS (RIVER_GRID * RIVER_GRID) + +// 河床质。决定河道的稳定性、含沙量上限和能不能挖沙。 +enum River_Bed { + RIVER_BED_NONE = 0, // 不是河道 + RIVER_BED_BEDROCK, // 基岩:急流、几乎不输沙 + RIVER_BED_BOULDER, // 漂石/卵石:山区河段 + RIVER_BED_GRAVEL, // 砾石 + RIVER_BED_SAND, // 沙质:宽浅、游荡、最典型的通航问题河段 + RIVER_BED_SILT, // 粉沙/淤泥:黄河那种 + RIVER_BED_COUNT +}; + +// 一次采样得到的河流信息。长度单位米,流量 m^3/s,含沙量 kg/m^3。 +struct River_Sample { + double discharge; // 年均流量 + double low_q; // 枯水期流量 + double flood_q; // 汛期流量 + double area; // 最近那条河的汇水面积 m^2 + double width; // 水面宽(满槽) + double depth; // 断面平均水深 + double depth_max; // 深泓(最深处)水深 + double depth_low; // 枯水期深泓水深——通航的实际限制 + double velocity; // 断面平均流速 m/s + double dist; // 到河道中心线的距离 + double valley_half; // 河谷/漫滩半宽 + double carve; // 相对区域面的下切量(>=0) + double slope; // 该点的局部坡度(由河谷断面解析求导,很便宜) + bool is_channel; // 该点是否落在水面宽度之内 + + // ---- 泥沙 ---- + double sed_conc; // 断面平均含沙量 kg/m^3(黄河 25~35,亚马逊 0.2) + double sed_load; // 年输沙量 t/yr + double soil_loss; // 流域产沙模数 t/(km^2·yr) + + // ---- 冰情 ---- + double water_temp; // 年均水温 ℃(水体热惯性,冬季比气温高) + double ice_thick; // 最大冰厚 m(Stefan 定律) + double ice_days; // 封冻天数 + double jam_risk; // 凌汛(冰坝)风险 0..1 + + // ---- 形态 ---- + uint8_t bed; // enum River_Bed + double perched; // 地上河:河床高出两岸漫滩多少米,<=0 = 不是地上河 + + double delta; // 区域侵蚀/沉积累计(负=下切,正=淤积) + double lake_surface; // 湖面高程;无湖时为一个极小的哨兵值 + double lake_depth; // 水深,0 = 无湖 + float vegetation; // 该格植被覆盖 0..1 +}; + +// ---- 断面与通航 ---- +// 河道横断面按抛物线近似:距中心线 dist 处的水深。 +// 通航要用的是这一条,而不是断面平均值。 +double river_depth_at(const struct River_Sample *rs, double dist); + +// 满足吃水的可通航宽度(米)。draft 是满载吃水,ukc 是龙骨下富余 +// (通常取吃水的 10~15%)。返回 0 表示这条河通不了。 +// 用枯水期深泓算——设计航道不能按汛期。 +double river_navigable_width(const struct River_Sample *rs, double draft_m, + double ukc_frac); + +struct River_Field { + int n; // 边长 = RIVER_GRID + double cell_m; // 格距 + double cell_area; // 格面积 m^2 + + double *base; // 构造基准高程(板块 + 分形起伏),不含河流改造 + double *elev; // 迭代中的当前地形 + float *delta; // 累计改造量(米),采样时叠加到基准上 + double *filled; // 洼地填平后的高程(定流向和比降用) + float *area; // 汇水面积 m^2 + float *discharge; // 流量 m^3/s + float *width; // 河宽 m + float *depth; // 河深 m + float *slope; // 到下游的比降 + float *relief; // 到下游的落差(米),决定河谷下切深度 + float *lake_depth; // 湖深 m,0 = 无湖(湖面 = elev + lake_depth) + float *veg; // 植被覆盖 0..1 + float *runoff_mm; // 年径流深 mm(Budyko) + float *depth_max; // 深泓水深 m + float *sed_conc; // 含沙量 kg/m^3 + float *sed_load; // 年输沙量 t/yr + float *soil_loss; // 流域产沙模数 t/(km^2·yr) + float *water_temp; // 年均水温 C + float *ice_thick; // 最大冰厚 m + float *jam_risk; // 凌汛风险 0..1 + float *perched; // 河床高出两岸漫滩多少米,>0 = 地上河 + float *season_amp; // 该格季节振幅 K(洪枯比、凌汛判据都要用) + uint8_t *bed; // enum River_Bed + int *down; // 下游单元下标,-1 = 汇/海/出图 + uint8_t *strahler; // Strahler 级数 + int *topo; // 拓扑序:下标越小越靠下游(填洼时的弹出顺序) + int topo_count; +}; + +// 跑完整的迭代:采样基准地形 -> 反复(汇流+侵蚀+沉积+气候反馈) -> 定型 +// iterations <= 0 时用默认值。w->rivers 由本函数写入。 +void river_build(struct River_Field *rf, struct World *w, int iterations); +void river_free(struct River_Field *rf); + +// 任意点采样。world 坐标(米)。很便宜,地图渲染和区块生成都直接调。 +void river_sample(const struct River_Field *rf, double wx, double wy, + struct River_Sample *out); + +// 同上,但只认汇水面积 >= min_area 的河道。地图配色用它把河网显示得 +// 稀一些——物理上的河道阈值(6 格)密到在 58km/px 下画不出来。 +void river_sample_filtered(const struct River_Field *rf, double wx, double wy, + double min_area, struct River_Sample *out); + +// 该点所在的 40km 水文格本身是不是一条(汇水面积 >= min_area 的)河道。 +// 地图配色要用这个而不是"附近有没有河"——后者在河网密集时会让半个 +// 大陆都判定成河道。 +bool river_cell_is_channel(const struct River_Field *rf, double wx, double wy, + double min_area, double *discharge_out); + +// "多大汇水面积才算一条河"的阈值(m²)。river.c 内部判定河道用的就是它, +// 地图和选址也要用同一个数,免得三处漂移。 +double river_channel_min_area(const struct River_Field *rf); + +// 河流/湖泊下方的地表是否被水覆盖(湖面高于地形时算淹没) +bool river_submerged(const struct River_Field *rf, double wx, double wy, + double terrain_z, double *water_z); + +#endif diff --git a/src/terrain.c b/src/terrain.c index 1a2ffe2..a0ceeb0 100644 --- a/src/terrain.c +++ b/src/terrain.c @@ -1,5 +1,92 @@ #include "terrain.h" +int wrap_block_x(int bx) { + bx = bx % (int)WORLD_BLOCK_COUNT_X; + if (bx < 0) bx += (int)WORLD_BLOCK_COUNT_X; + return bx; +} + +int wrap_block_y(int by) { + if (by < 0) by = 0; + if (by >= (int)WORLD_BLOCK_COUNT_Y) by = (int)WORLD_BLOCK_COUNT_Y - 1; + return by; +} + +// ================================================================ +// 板块属性空间混合 +// ================================================================ +// 板块归属是 512km 网格上的离散值,直接用会在边界留下硬多边形。 +// 这里用高斯核对邻域 World_Block 的板块属性做加权平均,把它变成连续场。 +// +// sigma = 0.6 个 World_Block ≈ 307 km:两块交界处邻居权重 exp(-0.5*(256/307)^2) +// ≈ 0.71,即过渡带半宽约 ±600 km,和地球板块边界变形带的量级相符。 +// +// 半径取 2 块:被截断的最大权重出现在 2 块外的对角(1448 km), +// exp(-0.5*(1448/307)^2) ≈ 3e-4,可以忽略。取 3 块只会把每次采样的 +// exp 次数从 25 涨到 49,换不到可测的精度。 +#define PLATE_BLEND_RADIUS 2 +#define PLATE_BLEND_SIGMA (WORLD_BLOCK_SIZE * 0.6) + +void plate_blend_at(struct World_Block *blocks, + struct Plate_list plates, + double wx, double wy, + struct Plate_Blend *out) { + int cx = (int)floor(wx / (double)WORLD_BLOCK_SIZE); + int cy = (int)floor(wy / (double)WORLD_BLOCK_SIZE); + + const double sigma2 = PLATE_BLEND_SIGMA * PLATE_BLEND_SIGMA; + const double inv_2s2 = 1.0 / (2.0 * sigma2); + + double total = 0.0; + double sum_oc = 0.0; + double sum_age = 0.0; + double sum_thk = 0.0; + double sum_sx = 0.0; + double sum_sy = 0.0; + + for (int dy = -PLATE_BLEND_RADIUS; dy <= PLATE_BLEND_RADIUS; dy++) { + for (int dx = -PLATE_BLEND_RADIUS; dx <= PLATE_BLEND_RADIUS; dx++) { + int bx = wrap_block_x(cx + dx); + int by = wrap_block_y(cy + dy); + int bi = by * (int)WORLD_BLOCK_COUNT_X + bx; + + double bxc = ((double)bx + 0.5) * WORLD_BLOCK_SIZE; + double byc = ((double)by + 0.5) * WORLD_BLOCK_SIZE; + + double ddx = bxc - wx; + // 注意:WORLD_W 是 UL,-WORLD_W 会先按无符号回绕成巨大的正数, + // 必须先把半边宽算成 double 再取负,否则判断恒为真、权重全被压成 0。 + double half_w = (double)WORLD_W * 0.5; + if (ddx > half_w) ddx -= (double)WORLD_W; + if (ddx < -half_w) ddx += (double)WORLD_W; + double ddy = byc - wy; + + double w = exp(-(ddx*ddx + ddy*ddy) * inv_2s2); + + int pid = blocks[bi].plate_id; + struct Plate *p = plates._p + pid; + + sum_oc += w * (p->is_ocean ? 1.0 : 0.0); + sum_age += w * (double)p->age; + sum_thk += w * p->thick; + sum_sx += w * p->speed.x; + sum_sy += w * p->speed.y; + total += w; + } + } + + if (total < 1e-12) { + out->is_ocean = 0; out->age = 0; out->thick = 0; + out->speed_x = 0; out->speed_y = 0; + return; + } + out->is_ocean = sum_oc / total; + out->age = sum_age / total; + out->thick = sum_thk / total; + out->speed_x = sum_sx / total; + out->speed_y = sum_sy / total; +} + static int plate_count(uint64_t seed){ return PLATE_MIN+game_hash(seed,PLATE_COUNT,0)%(PLATE_MAX-PLATE_MIN+1); } @@ -119,116 +206,93 @@ static void plate_age(struct Plate_list _i,uint64_t seed){ } } -static double block_dist(int i,int j) { - double ix=WORLD_BLOCK_SIZE*(i%WORLD_BLOCK_COUNT_X); - double iy=WORLD_BLOCK_SIZE*(i/WORLD_BLOCK_COUNT_X); - double jx=WORLD_BLOCK_SIZE*(j%WORLD_BLOCK_COUNT_X); - double jy=WORLD_BLOCK_SIZE*(j/WORLD_BLOCK_COUNT_X); - double dx=fabs(ix-jx); - if (dx>WORLD_W/2) dx=WORLD_W-dx; - double dy=fabs(iy-jy); - return sqrt(dx*dx+dy*dy); +// ================================================================ +// 高程 +// ================================================================ +// 旧实现用"最近的其他板块 + 边界法线"算边界抬升,问题有两个: +// 1) 板块基准高程直接按 is_ocean 二选一,边界上是几百到几千米的断崖; +// 2) other_plate_id 在中轴线上会突然换人,抬升量跟着跳变。 +// 现在改成:先混合出连续的板块属性,再用混合速度场的辐合量做抬升。 +// 辐合(两块相向)→ 挤压抬升,形成山脉; +// 辐散(两块背离)→ 张裂下沉,形成裂谷/洋中脊。 +// 这两项都是混合场的连续函数,所以边界不再有多边形硬边。 + +// 海洋/陆地基准高程,分别算完再用混合后的 is_ocean 插值。 +// 洋壳公式本来是给 5~12km 厚的玄武岩壳用的:过渡带上混合出来的厚度可能 +// 是陆壳的 50~70km,直接代进去会算出 -60km 这种无意义的深度,把海岸线 +// 拖成深渊。所以先把输入夹回各自公式的适用区间。 +static double plate_base_elev_ocean(double age, double thick) { + double t = thick < 5.0 ? 5.0 : (thick > 12.0 ? 12.0 : thick); + double a = age < 0.0 ? 0.0 : (age > 200.0 ? 200.0 : age); + return -2000.0 - (a / 200.0) * 2000.0 - (t - 5.0) * 400.0; } -static struct Vector2_double block_dir(int i,int j) { - double ix=WORLD_BLOCK_SIZE*(i%WORLD_BLOCK_COUNT_X); - double iy=WORLD_BLOCK_SIZE*(i/WORLD_BLOCK_COUNT_X); - double jx=WORLD_BLOCK_SIZE*(j%WORLD_BLOCK_COUNT_X); - double jy=WORLD_BLOCK_SIZE*(j/WORLD_BLOCK_COUNT_X); - double dx=jx-ix; - if (dx>WORLD_W/2) dx -= WORLD_W; - if (dx<-WORLD_W/2) dx+=WORLD_W; - double dy=jy-iy; - double len=sqrt(dx*dx+dy*dy); - struct Vector2_double v; - if (len<1e-9) { v.x=0;v.y=0;} - else { v.x=dx/len;v.y=dy/len;} - return v; +static double plate_base_elev_land(double age, double thick) { + return 200.0 + (thick - 30.0) * 20.0 + (age / 4000.0) * 500.0; } -static void plate_boundary_find(struct World_Block *_p,struct Plate_list _i) { - for (int i=0;iboundary_dist=WORLD_W; - (_p+i)->other_plate_id=-1; - (_p+i)->boundary_normal.x=0; - (_p+i)->boundary_normal.y=0; - int ix=i%WORLD_BLOCK_COUNT_X; - int iy=i/WORLD_BLOCK_COUNT_X; - int my_plate=(_p+i)->plate_id; - double best_dist=WORLD_W; - int best_j=-1; - for (int dy=-PLATE_SEARCH_RADIUS;dy<=PLATE_SEARCH_RADIUS;dy++) { - int jy=iy+dy; - if (jy<0 || jy>=WORLD_BLOCK_COUNT_Y) continue; - for (int dx=-PLATE_SEARCH_RADIUS;dx<=PLATE_SEARCH_RADIUS;dx++) { - if (dx == 0 && dy == 0) continue; - int jx=(ix+dx+WORLD_BLOCK_COUNT_X)%WORLD_BLOCK_COUNT_X; - int j=jy*WORLD_BLOCK_COUNT_X+jx; - if ((_p+j)->plate_id == my_plate) continue; - double d=block_dist(i,j); - if (d=0) { - (_p+i)->boundary_dist=best_dist; - (_p+i)->other_plate_id=(_p+best_j)->plate_id; - (_p+i)->boundary_normal=block_dir(i,best_j); +// 每单位"速度/World_Block"的辐合量抬升多少米。 +// 混合会削弱速度场的梯度,实测辐合量多在 ±1 以内、峰值约 8, +// 这个系数把收敛边界抬成 1~3km 的山系。 +#define UPLIFT_PER_CONVERGENCE 420.0 +// 张裂下沉比挤压抬升弱一些,不然洋中脊会挖出过深的沟 +#define SUBSIDENCE_SCALE 0.55 + +static double clamp01d(double x) { + return x < 0.0 ? 0.0 : (x > 1.0 ? 1.0 : x); +} + +static void plate_elevation(struct World_Block *_p, struct Plate_list _i, + uint64_t seed) { + const int CX = (int)WORLD_BLOCK_COUNT_X; + const int CY = (int)WORLD_BLOCK_COUNT_Y; + + // 1) 先把每个 World_Block 的板块属性混合出来,存成临时场 + struct Plate_Blend *blend = malloc(sizeof(struct Plate_Blend) * WORLD_BLOCK_COUNT); + if (blend == NULL) return; + + for (int j = 0; j < CY; j++) { + for (int k = 0; k < CX; k++) { + double wx = ((double)k + 0.5) * WORLD_BLOCK_SIZE; + double wy = ((double)j + 0.5) * WORLD_BLOCK_SIZE; + plate_blend_at(_p, _i, wx, wy, &blend[j * CX + k]); } } -} -static double plate_base_elev(struct Plate *p) { - if (p->is_ocean) { - return -2000.0-(p->age/200.0)*2000.0-(p->thick-5.0)*400.0; - } else { - return 200.0+(p->thick-30.0)*20.0+(p->age/4000.0)*500.0; - } -} + // 2) 基准高程 + 速度场辐合 + 随机起伏 + for (int j = 0; j < CY; j++) { + // y 方向不到两极,中心差分在边界退化为单侧差分 + int jm = (j > 0) ? j - 1 : j; + int jp = (j < CY - 1) ? j + 1 : j; -static double plate_boundary_elev(struct Plate *my,struct Plate *other,double conv,double dist) { - double decay=exp(-dist/PLATE_BOUNDARY_INFLUENCE); - double elev=0; - if (conv>0) { - if (!my->is_ocean && !other->is_ocean) { - double tf=(my->thick+other->thick)/100.0; - elev=conv*400.0*tf*decay; - } else if (!my->is_ocean && other->is_ocean) { - elev=conv*250.0*decay; - } else if (my->is_ocean && !other->is_ocean) { - elev=-conv*400.0*decay; - } else { - elev=conv*200.0*decay; - } - } else { - if (!my->is_ocean && !other->is_ocean) { - elev=conv*150.0*decay; - } else if (my->is_ocean && other->is_ocean) { - elev=-conv*250.0*decay; - } else { - elev=conv*50.0*decay; + for (int k = 0; k < CX; k++) { + int km = wrap_block_x(k - 1); + int kp = wrap_block_x(k + 1); + int idx = j * CX + k; + + const struct Plate_Blend *b = &blend[idx]; + + double oc = clamp01d(b->is_ocean); + double base = plate_base_elev_land(b->age, b->thick) * (1.0 - oc) + + plate_base_elev_ocean(b->age, b->thick) * oc; + + // 速度场散度(按块做中心差分,x 环绕、y 夹紧) + double dvx = (blend[j * CX + kp].speed_x - blend[j * CX + km].speed_x) * 0.5; + double dvy = (blend[jp * CX + k].speed_y - blend[jm * CX + k].speed_y) * 0.5; + double conv = -(dvx + dvy); // >0 = 辐合 + + double uplift = conv * UPLIFT_PER_CONVERGENCE; + if (uplift < 0.0) uplift *= SUBSIDENCE_SCALE; + + double noise = ((double)game_hash(seed, PLATE_HEIGHT, idx) / UINT64_MAX + - 0.5) * 200.0; + + _p[idx].elevation = base + uplift + noise; + _p[idx].convergence = conv; } } - return elev; -} -static void plate_elevation(struct World_Block *_p,struct Plate_list _i,uint64_t seed) { - for (int i=0;iplate_id; - double elev=plate_base_elev(my); - if ((_p+i)->other_plate_id>=0) { - struct Plate *other=_i._p+(_p+i)->other_plate_id; - double rel_x=my->speed.x-other->speed.x; - double rel_y=my->speed.y-other->speed.y; - double conv=rel_x*(_p+i)->boundary_normal.x+rel_y*(_p+i)->boundary_normal.y; - elev+=plate_boundary_elev(my,other,conv,(_p+i)->boundary_dist); - } - double noise=((double)game_hash(seed,PLATE_HEIGHT,i)/UINT64_MAX-0.5)*200.0; - elev+=noise; - (_p+i)->elevation=elev; - } + free(blend); } struct Plate_list plate_init(uint64_t seed, struct World_Block *block){ @@ -243,7 +307,6 @@ struct Plate_list plate_init(uint64_t seed, struct World_Block *block){ plate_thick(list,seed); plate_speed(list,seed); plate_age(list,seed); - plate_boundary_find(block, list); plate_elevation(block, list, seed); return list; } \ No newline at end of file diff --git a/src/terrain.h b/src/terrain.h index f12a4b8..0c0562e 100644 --- a/src/terrain.h +++ b/src/terrain.h @@ -15,8 +15,6 @@ #define WORLD_BLOCK_COUNT_X (WORLD_W/WORLD_BLOCK_SIZE) #define WORLD_BLOCK_COUNT_Y (WORLD_H/WORLD_BLOCK_SIZE) #define WORLD_BLOCK_COUNT (WORLD_BLOCK_COUNT_X*WORLD_BLOCK_COUNT_Y) -#define PLATE_BOUNDARY_INFLUENCE (WORLD_BLOCK_SIZE * 4) -#define PLATE_SEARCH_RADIUS 20 struct Vector2_double { double x; @@ -63,15 +61,29 @@ struct World_Block { int plate_id; double nearest_plate_dist; double elevation; - double boundary_dist; - int other_plate_id; - struct Vector2_double boundary_normal; + double convergence; // 板块速度场的辐合量(>0 挤压抬升,<0 张裂下沉) }; -struct World { - +// 连续化的板块属性:World_Block 上的离散值经高斯混合后的结果 +struct Plate_Blend { + double is_ocean; // 0 = 全陆地,1 = 全海洋,中间是过渡 + double age; + double thick; + double speed_x, speed_y; }; +// struct World 的完整定义见 world.h(需要 Compound_Settings / Climate_Field,属于 world 层) + struct Plate_list plate_init(uint64_t seed,struct World_Block *block); +// 在 (wx, wy) 处用高斯核对附近 World_Block 的板块属性做加权平均。 +// 板块归属是 512km 网格上的离散值,不混合就会在图上留下硬多边形。 +void plate_blend_at(struct World_Block *blocks, struct Plate_list plates, + double wx, double wy, struct Plate_Blend *out); + +// World_Block 索引环绕:x 方向首尾相接,y 方向夹紧到两极。 +// chunk.c 与 compound.c 都要用,所以放在 terrain 层导出。 +int wrap_block_x(int bx); +int wrap_block_y(int by); + #endif \ No newline at end of file diff --git a/src/weather.c b/src/weather.c new file mode 100644 index 0000000..d1ead09 --- /dev/null +++ b/src/weather.c @@ -0,0 +1,866 @@ +#include "weather.h" +#include "world.h" +#include "climate.h" +#include "chunk.h" +#include "river.h" +#include "noise.h" +#include "random.h" + +#include +#include +#include + +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif +#define D2R (M_PI / 180.0) +#define R2D (180.0 / M_PI) + +// =============================================================== +// 参数 +// =============================================================== + +// ---- 季节滞后 ---- +// 地表升温要等太阳,热容越大滞后越久。真实值:大陆约 1 个月, +// 海洋约 2 个月,深湖介于两者之间。 +#define LAG_LAND_DAYS 28.0 +#define LAG_OCEAN_DAYS 78.0 +#define LAG_LAKE_DAYS 45.0 + +// ---- 昼夜 ---- +// 晴朗沙漠可达 ±15℃,密林 ±5℃,海面只有 ±0.7℃。 +#define DIURNAL_CLEAR 14.0 +#define DIURNAL_WATER_F 0.06 +#define DIURNAL_VEG_F 0.60 +#define DIURNAL_CLOUD_F 0.55 + +// ---- 季风 ---- +// 海陆温差到这个值,季风指数拉满。东亚夏季风的陆海温差能到 10~15K。 +#define MONSOON_REF_C 3.2 +// 季风的地理加权:一片全是海(或全是陆)的纬度带没有海陆热力对比, +// 也就没有季风。真实的季风只出现在有大陆的经度上。 +#define MONSOON_LANDFRAC_LO 0.25 +#define MONSOON_LANDFRAC_HI 0.55 +// 雨季窗口(相对春分的天数,按地球年表达,会按年长缩放) +#define MONSOON_ONSET_20N 61.0 // 春分 +61 天 ≈ 5/20,南海季风爆发 +#define MONSOON_ONSET_27N 87.0 // ≈ 6/15,江淮梅雨(第一次北跳) +#define MONSOON_ONSET_35N 117.0 // ≈ 7/15,华北雨季(第二次北跳) +#define MONSOON_RAMP_DAYS 10.0 +#define MONSOON_LEN_20N 120.0 +#define MONSOON_LEN_SLOPE 2.2 +#define MONSOON_LEN_MIN 35.0 +#define MONSOON_RETREAT 15.0 +#define MONSOON_GAIN 2.6 // 雨季把降水强度放大多少倍 +#define MONSOON_WIND 9.0 // 季风风速 m/s +// 科里奥利对季风的偏转。近地面气流并不直冲热低压:它在科氏力作用下 +// 偏向低压右侧(北半球),越接近地转越是沿着等压线走。 +// 赤道 f→0:气流直冲内陆(印度洋季风刚爆发时就是这样) +// 20°+ :接近地转,沿等压线绕低压(东亚夏季风的西南气流) +// MONSOON_CROSS_MAX 是最大穿越角(弧度,90° 表示完全地转)。 +#define MONSOON_CROSS_MAX 1.481 // ≈85° +#define MONSOON_LAT_REF 20.0 // 参考纬度:这里的 f 作为偏转强度基准 + +// ---- 冰情 ---- +#define ICE_SEASON_DAYS 150.0 + +// ---- 降水的时间分配 ---- +// 年降水不是均匀落下来的:真正在下雨的时间只占全年的一小部分。 +#define WET_FRACTION_LAND 0.055 +#define WET_FRACTION_OCEAN 0.075 +// 对流性降水的日变化:午后最强 +#define CONVECTIVE_AMP 0.85 +// 云的日变化:对流云午后发展、海洋层积云夜间最盛 +#define CLOUD_DIURNAL 0.35 +// 积雪反照率对气温的反馈强度(K)。雪面反照率 0.8 对裸地 0.2, +// 春季太阳一强,有雪的地方升温被显著压住。 +#define SNOW_ALBEDO_K 5.0 + +// ---- 台风 ---- +#define STORM_STEP_SECONDS 1800.0 // 积分步长(30 分钟) +#define STORM_MAX_CATCHUP (86400.0 * 30.0) +#define STORM_GENESIS_LAT_MIN 7.0 +#define STORM_GENESIS_LAT_MAX 24.0 +#define STORM_SST_MIN 26.5 // 生成所需海温 ℃ +#define STORM_BASE_RATE 2.2e-6 // 每 30 分钟每"适宜格"的生成概率 +#define STORM_VMAX_MIN 18.0 // m/s +#define STORM_VMAX_MAX 68.0 +#define STORM_P_MIN 900.0 // 中心气压下限 hPa +#define STORM_P_AMBIENT 1010.0 +#define STORM_RADIUS_MIN 1.2e5 // 影响半径 m +#define STORM_RADIUS_MAX 5.0e5 +#define STORM_GROW_RATE 0.55 // 每步强度增长(暖海) +#define STORM_DECAY_LAND 1.35 +#define STORM_DECAY_COLD 0.85 +#define STORM_RECURVE_LAT 21.0 +#define STORM_BETA_DRIFT 1.8 // β 漂移的极向速度上限 m/s +#define STORM_MAX_AGE_DAYS 14.0 +#define STORM_RAIN_PEAK 55.0 // 眼墙降水率 mm/h +#define STORM_RAIN_CORE 14.0 +#define STORM_SURGE_MAX 4.5 // 风暴增水上限 m + +// =============================================================== +// 小工具 +// =============================================================== + +static double weather_clamp(double x, double lo, double hi) { + return x < lo ? lo : (x > hi ? hi : x); +} +static double weather_smoothstep(double t) { + t = weather_clamp(t, 0.0, 1.0); + return t * t * (3.0 - 2.0 * t); +} +static double smoothstep_ab(double a, double b, double x) { + if (b <= a) return x >= b ? 1.0 : 0.0; + return weather_smoothstep((x - a) / (b - a)); +} + +double weather_latitude(double wy) { + return 90.0 - (wy / (double)WORLD_H) * 180.0; +} + +// =============================================================== +// 预计算 +// =============================================================== + +void weather_field_build(struct Weather_Field *wf, struct World *w) { + const int BY = (int)WORLD_BLOCK_COUNT_Y; + const int BX = (int)WORLD_BLOCK_COUNT_X; + memset(wf, 0, sizeof(*wf)); + wf->bands = BY; + + wf->insol_min = calloc(BY, sizeof(float)); + wf->insol_max = calloc(BY, sizeof(float)); + wf->insol_mean = calloc(BY, sizeof(float)); + wf->band_landfrac = calloc(BY, sizeof(float)); + wf->band_T_land = calloc(BY, sizeof(float)); + wf->band_A_land = calloc(BY, sizeof(float)); + wf->band_T_ocean = calloc(BY, sizeof(float)); + wf->band_A_ocean = calloc(BY, sizeof(float)); + if (!wf->insol_min || !wf->band_T_ocean) { weather_field_free(wf); return; } + + // ---- 每个纬度带的年日辐射极值(季节相位查表要用)---- + for (int j = 0; j < BY; j++) { + double wy = ((double)j + 0.5) * WORLD_BLOCK_SIZE; + double lat = weather_latitude(wy); + double mn, mx, me; + astro_insolation_range(&w->planet, lat, &mn, &mx, &me); + wf->insol_min[j] = (float)mn; + wf->insol_max[j] = (float)mx; + wf->insol_mean[j] = (float)me; + } + + // ---- 每个纬度带的海陆热力对比 ---- + // 季风就是靠这个驱动的:陆地热容小、季节振幅大、相位早; + // 海洋热容大、振幅小、相位晚。两者之差决定风往哪吹。 + for (int j = 0; j < BY; j++) { + double wy = ((double)j + 0.5) * WORLD_BLOCK_SIZE; + double sTl = 0, sAl = 0; int nl = 0; + double sTo = 0, sAo = 0; int no = 0; + for (int k = 0; k < BX; k++) { + int idx = j * BX + k; + double wx = ((double)k + 0.5) * WORLD_BLOCK_SIZE; + struct Climate_Sample cs; + climate_sample(&w->climate, w->seed, wx, wy, + w->blocks[idx].elevation, &cs); + if (w->blocks[idx].elevation < 0.0) { + sTo += cs.temperature; sAo += cs.seasonal_amplitude; no++; + } else { + sTl += cs.temperature; sAl += cs.seasonal_amplitude; nl++; + } + } + wf->band_landfrac[j] = (float)((double)nl / BX); + wf->band_T_land[j] = nl ? (float)(sTl / nl) : 0.0f; + wf->band_A_land[j] = nl ? (float)(sAl / nl) : 0.0f; + wf->band_T_ocean[j] = no ? (float)(sTo / no) : 0.0f; + wf->band_A_ocean[j] = no ? (float)(sAo / no) : 0.0f; + } + + // 台风系统 + memset(&wf->storms, 0, sizeof(wf->storms)); + wf->storms.last_seconds = -1.0; + wf->storms.next_id = 1; +} + +void weather_field_free(struct Weather_Field *wf) { + if (wf == NULL) return; + free(wf->insol_min); free(wf->insol_max); free(wf->insol_mean); + free(wf->band_landfrac); free(wf->band_T_land); free(wf->band_A_land); + free(wf->band_T_ocean); free(wf->band_A_ocean); + memset(wf, 0, sizeof(*wf)); +} + +// 按纬度带双线性插值海陆温度(带季节与滞后) +static void band_temps(const struct Weather_Field *wf, + const struct Planet_Params *p, + double wy, double t_seconds, + double *T_land, double *T_ocean) { + double by = wy / (double)WORLD_BLOCK_SIZE - 0.5; + int iy = (int)floor(by); + double fy = by - iy; + if (iy < 0) { iy = 0; fy = 0.0; } + if (iy > wf->bands - 2) { iy = wf->bands - 2; fy = 1.0; } + + struct Game_Time tl = game_time_at(t_seconds - LAG_LAND_DAYS * p->day_seconds); + struct Game_Time to = game_time_at(t_seconds - LAG_OCEAN_DAYS * p->day_seconds); + double sl = weather_season_phase(wf, p, wy, tl.seconds); + double so = weather_season_phase(wf, p, wy, to.seconds); + + double Tl = wf->band_T_land[iy] * (1 - fy) + wf->band_T_land[iy + 1] * fy; + double Al = wf->band_A_land[iy] * (1 - fy) + wf->band_A_land[iy + 1] * fy; + double To = wf->band_T_ocean[iy] * (1 - fy) + wf->band_T_ocean[iy + 1] * fy; + double Ao = wf->band_A_ocean[iy] * (1 - fy) + wf->band_A_ocean[iy + 1] * fy; + + if (T_land) *T_land = Tl + Al * sl; + if (T_ocean) *T_ocean = To + Ao * so; +} + +double weather_season_phase(const struct Weather_Field *wf, + const struct Planet_Params *p, + double wy, double t_seconds) { + double by = wy / (double)WORLD_BLOCK_SIZE - 0.5; + int iy = (int)floor(by); + double fy = by - iy; + if (iy < 0) { iy = 0; fy = 0.0; } + if (iy > wf->bands - 2) { iy = wf->bands - 2; fy = 1.0; } + + double mn = wf->insol_min[iy] * (1 - fy) + wf->insol_min[iy + 1] * fy; + double mx = wf->insol_max[iy] * (1 - fy) + wf->insol_max[iy + 1] * fy; + double me = wf->insol_mean[iy] * (1 - fy) + wf->insol_mean[iy + 1] * fy; + + double half = (mx - mn) * 0.5; + if (half < 1e-6) return 0.0; // 赤道:没有季节 + + struct Game_Time gt = game_time_at(t_seconds); + double v = astro_daily_insolation(p, >, weather_latitude(wy)); + return weather_clamp((v - me) / half, -1.0, 1.0); +} + +double weather_monsoon_index(const struct Weather_Field *wf, + const struct Planet_Params *p, + double wy, double t_seconds) { + // 关键是取"海陆温差的**季节异常**"而不是绝对差: + // 年均的陆海温差驱动的是定常波(比如北美东岸的岸外槽), + // 季风是季节性的反转,所以要把年平均值减掉。 + double by = wy / (double)WORLD_BLOCK_SIZE - 0.5; + int iy = (int)floor(by); + double fy = by - iy; + if (iy < 0) { iy = 0; fy = 0.0; } + if (iy > wf->bands - 2) { iy = wf->bands - 2; fy = 1.0; } + double lf = wf->band_landfrac[iy] * (1 - fy) + wf->band_landfrac[iy + 1] * fy; + double geo = smoothstep_ab(MONSOON_LANDFRAC_LO, MONSOON_LANDFRAC_HI, lf); + if (geo <= 0.0) return 0.0; + + double Tl, To; + band_temps(wf, p, wy, t_seconds, &Tl, &To); + + // 年平均值(把季节相位取 0 就是年均) + double Tl0 = wf->band_T_land[iy] * (1 - fy) + wf->band_T_land[iy + 1] * fy; + double To0 = wf->band_T_ocean[iy] * (1 - fy) + wf->band_T_ocean[iy + 1] * fy; + + double anom = (Tl - Tl0) - (To - To0); + return weather_clamp(anom / MONSOON_REF_C, -1.0, 1.0) * geo; +} + +// 雨季开始的日子(相对春分的天数,按地球年表达) +static double monsoon_onset_rel(double alat) { + if (alat <= 20.0) return MONSOON_ONSET_20N - (20.0 - alat) * 2.0; + if (alat <= 27.0) return MONSOON_ONSET_20N + + (alat - 20.0) * (MONSOON_ONSET_27N - MONSOON_ONSET_20N) / 7.0; + return MONSOON_ONSET_27N + + (alat - 27.0) * (MONSOON_ONSET_35N - MONSOON_ONSET_27N) / 8.0; +} + +double weather_monsoon_rain(const struct Weather_Field *wf, + const struct Planet_Params *p, + double wy, double t_seconds) { + double lat = weather_latitude(wy); + double alat = fabs(lat); + if (alat < 8.0 || alat > 55.0) return 0.0; // 季风区之外 + + double mi = weather_monsoon_index(wf, p, wy, t_seconds); + if (mi <= 0.0) return 0.0; // 冬季风:不下雨 + + struct Game_Time gt = game_time_at(t_seconds); + double doy = astro_day_of_year(p, >); + double rel = doy - p->equinox_day; // 相对春分的天数 + if (lat < 0.0) rel += p->year_days * 0.5; // 南半球季节反转 + rel = fmod(rel, p->year_days); + if (rel < 0.0) rel += p->year_days; + + // 把"地球日"缩放到这颗行星的年长 + double scale = p->year_days / EARTH_YEAR_DAYS; + double onset = monsoon_onset_rel(alat) * scale; + double length = MONSOON_LEN_20N - (alat - 20.0) * MONSOON_LEN_SLOPE; + if (length < MONSOON_LEN_MIN) length = MONSOON_LEN_MIN; + length *= scale; + double ramp = MONSOON_RAMP_DAYS * scale; + double retreat = MONSOON_RETREAT * scale; + + // 北推慢、南退快 —— 这正是"南方早北方晚"的来源: + // onset 随纬度线性推后,20N 在 5 月下旬、35N 要等到 7 月中旬。 + double win = smoothstep_ab(onset, onset + ramp, rel); + double back = 1.0 - smoothstep_ab(onset + length, onset + length + retreat, rel); + return mi * win * back; +} + +// 降水的季节重分配权重。水文层把年降水按这个权重分到 12 个月再归一化, +// 所以季风只改变"什么时候下",不改变"一年下多少"。 +double weather_precip_weight(const struct Weather_Field *wf, + const struct Planet_Params *p, + double wy, double t_seconds) { + if (wf == NULL || p == NULL) return 1.0; + return 1.0 + MONSOON_GAIN * weather_monsoon_rain(wf, p, wy, t_seconds); +} + +// =============================================================== +// 台风 +// =============================================================== +// 该点的海表温度(℃)。河流层算过年均水温,这里叠上季节。 +static double sea_temp_at(struct World *w, double wx, double wy, double t_seconds) { + struct Climate_Sample cs; + climate_sample(&w->climate, w->seed, wx, wy, 0.0, &cs); + struct Planet_Params *p = &w->planet; + struct Game_Time tl = game_time_at(t_seconds - LAG_OCEAN_DAYS * p->day_seconds); + double s = weather_season_phase(&w->weather, p, wy, tl.seconds); + return cs.temperature + cs.seasonal_amplitude * s; +} + +static double rand_unit(uint64_t seed, uint64_t a, uint64_t b) { + return (double)(game_hash(seed, 0xB0000000u + a, b) >> 11) / 9007199254740992.0; +} + +static void storm_spawn(struct Weather_Field *wf, struct World *w, double t) { + struct Storm_Field *sf = &wf->storms; + int slot = -1; + for (int i = 0; i < STORM_MAX; i++) + if (!sf->storms[i].active) { slot = i; break; } + if (slot < 0) return; + + // 找一块满足条件的暖海面 + for (int tries = 0; tries < 24; tries++) { + double u = rand_unit(w->seed, 1, sf->next_id * 24 + tries); + double v = rand_unit(w->seed, 2, sf->next_id * 24 + tries); + // 纬度 -> 世界 y:weather_latitude(wy) = 90 - wy/WORLD_H*180 + double lat0 = STORM_GENESIS_LAT_MIN + + (STORM_GENESIS_LAT_MAX - STORM_GENESIS_LAT_MIN) * u; + double wy = (90.0 - lat0) / 180.0 * (double)WORLD_H; + // 南北半球各一半 + if (v < 0.5) wy = (double)WORLD_H - wy; + double wx = rand_unit(w->seed, 3, sf->next_id * 24 + tries) * (double)WORLD_W; + + int bx = (int)(wx / (double)WORLD_BLOCK_SIZE); + int by = (int)(wy / (double)WORLD_BLOCK_SIZE); + if (bx < 0 || bx >= (int)WORLD_BLOCK_COUNT_X) continue; + if (by < 0 || by >= (int)WORLD_BLOCK_COUNT_Y) continue; + if (w->blocks[by * (int)WORLD_BLOCK_COUNT_X + bx].elevation >= 0.0) continue; + if (sea_temp_at(w, wx, wy, t) < STORM_SST_MIN) continue; + // 科里奥利太弱就组织不起气旋:|f| 需要超过一个下限 + if (fabs(astro_coriolis(&w->planet, weather_latitude(wy))) < + fabs(astro_coriolis(&w->planet, STORM_GENESIS_LAT_MIN))) continue; + + struct Storm *s = &sf->storms[slot]; + memset(s, 0, sizeof(*s)); + s->active = true; + s->id = sf->next_id++; + s->x = wx; + s->y = wy; + // 初生在信风里:西行 + 轻微极向 + double lat = weather_latitude(wy); + double sgn = (lat >= 0.0) ? 1.0 : -1.0; + s->vx = -6.5; + s->vy = sgn * 1.0; + s->intensity = 0.18; + s->radius = STORM_RADIUS_MIN; + s->age_days = 0.0; + s->born_seconds = t; + s->basin = (int)(wx / (double)WORLD_W * 8.0); + sf->active_count++; + sf->spawned_total += 1.0; + return; + } +} + +static void storm_step(struct Storm *s, struct World *w, double dt) { + double days = dt / 86400.0; + struct Planet_Params *p = &w->planet; + + double lat = weather_latitude(s->y); + double sgn = (lat >= 0.0) ? 1.0 : -1.0; + + // ---- 路径 ---- + // 副高西缘之外继续西行,越过之后转向极向(经典的转向路径)。 + double dist_from_ridge = fabs(lat) - STORM_RECURVE_LAT; + if (dist_from_ridge > 0.0) { + double t = weather_clamp(dist_from_ridge / 12.0, 0.0, 1.0); + s->vx += (-6.5 - s->vx) * t * 0.25 + t * 9.0 * days; // 逐渐转向东 + s->vy += sgn * 2.2 * t * days * 10.0; + } else { + s->vx *= (1.0 - 0.05 * days); + } + // β 漂移:f = 2Ω sinφ 随纬度变化,这个梯度给台风一个净的极向漂移 + // ("北偏")。赤道上 f 的梯度为零,所以漂移也消失——这正是台风 + // 不在赤道生成的原因之一。漂移速度正比于 |f|。 + { + double f = astro_coriolis(p, lat); + double fr = astro_coriolis(p, MONSOON_LAT_REF); + double bf = fabs(f / fr); + if (bf > 1.0) bf = 1.0; + // +y 向南,所以"极向"= -sgn + s->vy += (-sgn) * STORM_BETA_DRIFT * bf * days; + } + double sp = sqrt(s->vx * s->vx + s->vy * s->vy); + if (sp > 22.0) { s->vx *= 22.0 / sp; s->vy *= 22.0 / sp; } + + s->x += s->vx * dt; + s->y += s->vy * dt; + if (s->x < 0.0) s->x += (double)WORLD_W; + if (s->x >= (double)WORLD_W) s->x -= (double)WORLD_W; + if (s->y < 0.0 || s->y >= (double)WORLD_H) { s->intensity = 0.0; s->active = false; return; } + + // ---- 强度 ---- + int bx = (int)(s->x / (double)WORLD_BLOCK_SIZE); + int by = (int)(s->y / (double)WORLD_BLOCK_SIZE); + bx = bx < 0 ? 0 : (bx >= (int)WORLD_BLOCK_COUNT_X ? (int)WORLD_BLOCK_COUNT_X - 1 : bx); + by = by < 0 ? 0 : (by >= (int)WORLD_BLOCK_COUNT_Y ? (int)WORLD_BLOCK_COUNT_Y - 1 : by); + bool over_ocean = w->blocks[by * (int)WORLD_BLOCK_COUNT_X + bx].elevation < 0.0; + + double sst = over_ocean ? sea_temp_at(w, s->x, s->y, s->born_seconds + s->age_days * 86400.0) : 0.0; + double dI; + if (!over_ocean) { + dI = -STORM_DECAY_LAND * days; // 登陆迅速减弱 + } else if (sst < STORM_SST_MIN) { + dI = -STORM_DECAY_COLD * days; // 冷海 + } else { + dI = STORM_GROW_RATE * days * weather_clamp((sst - STORM_SST_MIN) / 4.0, 0.0, 1.0); + dI *= (1.0 - s->intensity); // 越强增长越慢 + } + s->intensity = weather_clamp(s->intensity + dI, 0.0, 1.0); + s->radius = STORM_RADIUS_MIN + (STORM_RADIUS_MAX - STORM_RADIUS_MIN) * s->intensity; + s->age_days += days; + + // 绝对纬度太高、或者寿命到了就消散 + if (fabs(weather_latitude(s->y)) > 48.0) s->intensity *= (1.0 - 1.2 * days); + if (s->age_days > STORM_MAX_AGE_DAYS) s->intensity -= 0.12 * days; + if (s->intensity <= 0.02) { s->active = false; } +} + +void weather_storms_update(struct Weather_Field *wf, struct World *w, + double t_seconds) { + struct Storm_Field *sf = &wf->storms; + if (sf->last_seconds < 0.0) { sf->last_seconds = t_seconds; return; } + + double dt_total = t_seconds - sf->last_seconds; + if (dt_total <= 0.0) return; + if (dt_total > STORM_MAX_CATCHUP) dt_total = STORM_MAX_CATCHUP; + + while (dt_total > 0.0) { + double dt = dt_total > STORM_STEP_SECONDS ? STORM_STEP_SECONDS : dt_total; + + sf->active_count = 0; + for (int i = 0; i < STORM_MAX; i++) { + if (!sf->storms[i].active) continue; + storm_step(&sf->storms[i], w, dt); + if (sf->storms[i].active) sf->active_count++; + } + + // 生成:暖季、暖海面。速率用"适宜格"的面积近似,简化成一个基准率 + // 乘以暖季因子,避免每步都去扫全球。 + struct Game_Time gt = game_time_at(sf->last_seconds); + double season = 0.5 - 0.5 * cos(2.0 * M_PI * + (astro_day_of_year(&w->planet, >) - w->planet.equinox_day) + / w->planet.year_days - M_PI); // 北半球盛夏 = 1 + double rate = STORM_BASE_RATE * (0.35 + 0.65 * season) * dt; + // MJO:台风在季节内振荡的活跃位相里**成簇**生成,生成率可以 + // 差两三倍——这是真实台风活动最明显的季节内特征。 + // 这里取传播波的固定经度相位当作全球生成率的调制(簇生)。 + double mjo_g = weather_mjo_index(&w->planet, >, 0.0); + double enso = weather_enso_index(&w->planet, >); + rate *= (1.0 + 0.55 * mjo_g + 0.30 * enso); + if (rate < 0.0) rate = 0.0; + sf->spawn_accum += rate; + while (sf->spawn_accum >= 1.0) { + sf->spawn_accum -= 1.0; + storm_spawn(wf, w, sf->last_seconds); + } + + sf->last_seconds += dt; + dt_total -= dt; + } +} + +// 台风在某点的影响 +static void storm_effect(const struct Storm_Field *sf, double wx, double wy, + double *out_intensity, double *out_dist, + double *out_wind, double *out_rain, double *out_surge) { + *out_intensity = 0.0; *out_dist = 1e30; + *out_wind = 0.0; *out_rain = 0.0; *out_surge = 0.0; + + for (int i = 0; i < STORM_MAX; i++) { + const struct Storm *s = &sf->storms[i]; + if (!s->active) continue; + double dx = s->x - wx; + if (dx > (double)WORLD_W * 0.5) dx -= (double)WORLD_W; + if (dx < -(double)WORLD_W * 0.5) dx += (double)WORLD_W; + double dy = s->y - wy; + double d = sqrt(dx * dx + dy * dy); + if (d < *out_dist) *out_dist = d; + if (d > s->radius * 4.0) continue; + + double r = d / s->radius; + // 风:眼区平静,眼墙最强,外围按幂律衰减 + double wind_f = (r < 0.25) ? (r / 0.25) * 0.45 + : exp(-(r - 0.9) * (r - 0.9) / 0.75); + double vmax = STORM_VMAX_MIN + (STORM_VMAX_MAX - STORM_VMAX_MIN) * s->intensity; + double w = vmax * wind_f; + + // 降水:眼墙环状最强,眼内反而少 + double ring = exp(-((r - 0.75) * (r - 0.75)) / 0.16); + double core = STORM_RAIN_CORE * exp(-(r * r) / 0.05); + double rain = (STORM_RAIN_PEAK * s->intensity * ring + core) ; + + double eff = weather_clamp(s->intensity * wind_f * 2.0, 0.0, 1.0); + if (eff > *out_intensity) *out_intensity = eff; + if (w > *out_wind) *out_wind = w; + if (rain > *out_rain) *out_rain = rain; + double surge = STORM_SURGE_MAX * s->intensity * + exp(-(d * d) / (2.0 * s->radius * s->radius)); + if (surge > *out_surge) *out_surge = surge; + } +} + +// =============================================================== +// 冰情随时间的演化 +// =============================================================== +// river.c 里的冰厚是"冬季最大值"(静态的年景)。真实湖面是随季节 +// 封冻又开河的,所以这里用同一个 Stefan 定律,但把冻结指数乘上 +// "已经冷了多久"——季节相位为负(冬半年)时才积累。 + +double weather_ice_thickness(const struct Planet_Params *p, double t_winter_water, + double season_phase) { + if (t_winter_water >= 0.0) return 0.0; + // 冬半年才结冰:season_phase < 0 是当地冬季 + double cold = -season_phase; + if (cold <= 0.0) return 0.0; + double fdd = (-t_winter_water) * (ICE_SEASON_DAYS * 0.5) * cold; + double ice = 0.030 * sqrt(fdd); + if (ice < 0.02) ice = 0.0; + if (ice > 3.5) ice = 3.5; + return ice; +} + +// =============================================================== +// 年际振荡与季节内振荡 +// =============================================================== + +// 该存档的随机通道小工具(复用 rand_unit 的哈希) +static double wrnd(uint64_t seed, uint64_t ch) { + return (double)(game_hash(seed, 0xC1000000u + ch, 0) >> 11) + / 9007199254740992.0; +} + +double weather_enso_center_lon(const struct Planet_Params *p) { + // 由种子决定的"暖池异常中心"经度 + return -180.0 + 360.0 * wrnd(p->seed, WEATHER_NOISE_ENSO); +} + +double weather_enso_index(const struct Planet_Params *p, + const struct Game_Time *t) { + // 以"年"为单位的连续时间 + double y = t->seconds / (p->day_seconds * p->year_days); + // 两个不可通约的周期:2.6~5.0 年 与 1.7~3.3 年 + double per1 = 2.6 + 2.4 * wrnd(p->seed, WEATHER_NOISE_ENSO + 1); + double per2 = 1.7 + 1.6 * wrnd(p->seed, WEATHER_NOISE_ENSO + 2); + double ph1 = 2.0 * M_PI * wrnd(p->seed, WEATHER_NOISE_ENSO + 3); + double ph2 = 2.0 * M_PI * wrnd(p->seed, WEATHER_NOISE_ENSO + 4); + double v = 0.62 * sin(2.0 * M_PI * y / per1 + ph1) + + 0.38 * sin(2.0 * M_PI * y / per2 + ph2); + return weather_clamp(v, -1.0, 1.0); +} + +double weather_mjo_index(const struct Planet_Params *p, + const struct Game_Time *t, double lon_deg) { + // 周期 30~60 天,向东传播(相位随经度递减) + double per = 30.0 + 30.0 * wrnd(p->seed, WEATHER_NOISE_ENSO + 5); + double days = t->seconds / p->day_seconds; + double ph = 2.0 * M_PI * days / per - lon_deg * D2R; + // 季节锁相:北半球冬春季(当地夏末到春初)最强 + double y = days / p->year_days; + double doy = astro_day_of_year(p, t); + double seasonal = 0.55 + 0.45 * cos(2.0 * M_PI * + (doy - p->equinox_day) / p->year_days + M_PI); + (void)y; + return weather_clamp(cos(ph) * seasonal, -1.0, 1.0); +} + +// =============================================================== +// 采样 +// =============================================================== + +void weather_sample(struct World *w, double wx, double wy, double elevation, + double t_seconds, struct Weather_Sample *out) { + memset(out, 0, sizeof(*out)); + out->freeze_month = -1; + out->break_month = -1; + if (w == NULL) return; + + struct Planet_Params *p = &w->planet; + struct Weather_Field *wf = &w->weather; + + struct Climate_Sample cs; + climate_sample(&w->climate, w->seed, wx, wy, elevation, &cs); + + // ---- 年均值(不传时间时就是这些)---- + out->temperature = cs.temperature; + out->wind_x = cs.wind_x * 6.0; + out->wind_y = cs.wind_y * 6.0; + out->wind_speed = 6.0; + out->gust = 6.0 * 1.35; + out->humidity = weather_clamp(cs.moisture * 0.65 + 0.30, 0.0, 1.0); + out->cloud = weather_clamp(cs.precipitation * 0.8, 0.0, 1.0); + out->pressure = 1013.0; + out->water_temp = cs.temperature; + + // ---- 水文层:逐月的雪/土壤水/水温/冰/流量 ---- + struct Hydro_Sample hs; + hydro_sample(w, wx, wy, elevation, t_seconds, &hs); + + out->swe_mm = hs.swe_mm; + out->snow_cover = hs.snow_cover; + out->water_temp = hs.water_temp; + out->ice_thick = hs.ice_thick; + out->ice_trend = hs.ice_trend; + out->jam_risk = hs.jam_risk; + out->freeze_month = hs.freeze_month; + out->break_month = hs.break_month; + + bool ocean = (elevation < 0.0); + + if (t_seconds < 0.0) { + out->temp_min = out->temp_max = cs.temperature; + out->dew_point = cs.temperature - (1.0 - out->humidity) * 20.0; + out->precipitation = (hs.precip_mm > 0.0) + ? hs.precip_mm / (p->year_days / 12.0) / 24.0 : 0.0; + out->precip_24h = out->precipitation * 24.0; + return; + } + + struct Game_Time now = game_time_at(t_seconds); + double lat = weather_latitude(wy); + double lon = weather_longitude(wx); + double alat = fabs(lat); + + // ---- 年际(ENSO)与季节内(MJO)---- + double enso = weather_enso_index(p, &now); + double mjo = weather_mjo_index(p, &now, lon); + out->enso = enso; + out->mjo = mjo; + + // 热带权重:这两个都是热带现象,中高纬影响靠遥相关衰减 + double trop = exp(-(lat * lat) / (2.0 * 28.0 * 28.0)); + // ENSO 的海温异常:暖池异常中心附近变暖,西侧(对流区)变冷 + double dlon = lon - weather_enso_center_lon(p); + while (dlon > 180.0) dlon -= 360.0; + while (dlon < -180.0) dlon += 360.0; + double sst_anom = enso * (2.4 * exp(-(dlon / 70.0) * (dlon / 70.0)) + - 0.9 * exp(-((dlon - 180.0) / 95.0) * + ((dlon - 180.0) / 95.0))); + // 降水对 ENSO 的响应:暖异常处对流增强,冷异常处被抑制 + double enso_rain = 1.0 + 0.45 * enso * trop * + (exp(-(dlon / 70.0) * (dlon / 70.0)) - + exp(-((dlon - 180.0) / 95.0) * ((dlon - 180.0) / 95.0))); + if (enso_rain < 0.15) enso_rain = 0.15; + + // ---- 太阳与季节 ---- + double cz = astro_solar_cos_zenith(p, &now, lat, lon); + out->solar_elev = asin(weather_clamp(cz, -1.0, 1.0)) * R2D; + out->insolation = astro_insolation(p, &now, lat, lon); + + double lake_depth = 0.0, veg = 0.0; + if (w->rivers != NULL) { + struct River_Sample rs; + river_sample(w->rivers, wx, wy, &rs); + lake_depth = rs.lake_depth; + veg = rs.vegetation; + } + if (veg <= 0.0 && !ocean) veg = weather_clamp(cs.moisture * 0.6, 0.0, 1.0); + bool water = ocean || lake_depth > 0.0; + + double lag_days = ocean ? LAG_OCEAN_DAYS : (lake_depth > 0.0 ? LAG_LAKE_DAYS + : LAG_LAND_DAYS); + double season = weather_season_phase(wf, p, wy, + t_seconds - lag_days * p->day_seconds); + double T = cs.temperature + cs.seasonal_amplitude * season; + + // ---- 云量(先粗估,昼夜振幅要用)---- + double base_cloud = weather_clamp(cs.precipitation * 0.75 + + cs.moisture * 0.25, 0.0, 1.0); + out->cloud = base_cloud; + + // ---- 昼夜 ---- + // 最低温出现在日出前(约 4 时),最高温在午后(约 15 时),所以用一条 + // 偏向午后的余弦,而不是对称的。 + double hour = astro_local_hour(p, &now, lon); + double diurnal_shape = cos(2.0 * M_PI * (hour - 15.0) / 24.0); + double amp_d = DIURNAL_CLEAR; + if (water) amp_d *= DIURNAL_WATER_F; + amp_d *= (1.0 - DIURNAL_VEG_F * veg); + amp_d *= (1.0 - DIURNAL_CLOUD_F * out->cloud); + if (cz < 0.0) diurnal_shape *= (1.0 + 0.35 * (-cz)); + T += amp_d * diurnal_shape; + + // ---- 积雪反照率反馈 ---- + // 雪面反照率 0.8、裸地 0.2,所以有雪的地方春季升温被压住, + // 融雪因此拖后——这是真实世界春季最重要的一个正反馈。 + if (hs.snow_cover > 0.0) { + double sw = weather_clamp(out->insolation / 250.0, 0.0, 1.6); + T -= SNOW_ALBEDO_K * hs.snow_cover * sw; + } + + out->temperature = T; + out->temp_max = T + amp_d * 0.35; + out->temp_min = T - amp_d * 0.65; + + // ---- 相对湿度:昼夜循环 ---- + // 水汽压一天之内几乎不变,变的是饱和水汽压(跟着气温走),所以 + // 相对湿度在日出前最高、午后最低。用 Magnus 公式从"日平均湿度" + // 反推露点,再按当前气温算 RH。 + { + double Tmean = cs.temperature + cs.seasonal_amplitude * season; + double e_s_mean = 6.112 * exp(17.67 * Tmean / (Tmean + 243.5)); + double e = out->humidity * e_s_mean; // 水汽压保持不变 + double e_s = 6.112 * exp(17.67 * T / (T + 243.5)); + double rh = (e_s > 1e-6) ? e / e_s : out->humidity; + out->humidity = weather_clamp(rh, 0.02, 1.0); + double ln = log(weather_clamp(e / 6.112, 1e-4, 1e4)); + out->dew_point = 243.5 * ln / (17.67 - ln); + } + + // ---- 季风 ---- + // ENSO 会削弱夏季风:厄尔尼诺年印度季风降水偏少是最稳的遥相关之一。 + double mi = weather_monsoon_index(wf, p, wy, t_seconds) * (1.0 - 0.22 * enso); + double mr = weather_monsoon_rain(wf, p, wy, t_seconds); + out->monsoon = mi; + out->monsoon_rain = mr; + + // ---- 降水 ---- + // 季节分配(雨带随太阳南北迁移 + 季风集中)已经在水文层的 12 个月 + // 序列里了,这里只加**日内**和**天气尺度**的变化,避免重复计入季节。 + double mdays = p->year_days / 12.0; + double rate = hs.precip_mm / (mdays * 24.0); + double wet_frac = ocean ? WET_FRACTION_OCEAN : WET_FRACTION_LAND; + if (rate > 0.0) rate /= wet_frac; + + // 对流性降水的日变化:陆地午后最强,海洋凌晨最强 + double conv_phase = ocean ? 4.0 : 16.0; + double conv = 1.0 + CONVECTIVE_AMP * + weather_clamp(cos(2.0 * M_PI * (hour - conv_phase) / 24.0), + -1.0, 1.0) * (ocean ? 0.4 : 1.0); + rate *= conv; + + // 年际 + 季节内 + rate *= enso_rain; + rate *= (1.0 + 0.55 * mjo * trop); + if (rate < 0.0) rate = 0.0; + + // 台风 + double s_int, s_dist, s_wind, s_rain, s_surge; + storm_effect(&wf->storms, wx, wy, &s_int, &s_dist, &s_wind, &s_rain, &s_surge); + out->storm = s_int; + out->storm_dist = s_dist; + rate += s_rain; + out->precipitation = rate; + out->precip_24h = rate * 24.0 * wet_frac; + + // 云的实时修正:对流云午后发展、海洋层积云夜间最多 + double cloud_diurnal = 1.0 + CLOUD_DIURNAL * + weather_clamp(cos(2.0 * M_PI * (hour - conv_phase) / 24.0), + -1.0, 1.0); + out->cloud = weather_clamp(base_cloud * cloud_diurnal + mr * 0.30 + + s_int * 0.5 + 0.12 * mjo * trop, 0.0, 1.0); + out->humidity = weather_clamp(out->humidity + mr * 0.12 + s_int * 0.2, + 0.0, 1.0); + + // 雪的判据用湿球温度近似 + out->snow = weather_clamp((1.0 - T) / 3.0, 0.0, 1.0); + + // ---- 风 ---- + double wx_v = cs.wind_x * 6.0; + double wy_v = cs.wind_y * 6.0; + + // 季风:大陆热低压把空气从海洋吸进来。气压梯度力的方向 = 指向内陆 + // = 海洋距离场的负梯度,再由科里奥利力偏转。这样季风风向就依赖于 + // "海岸线在哪",而不是简单地南北吹。 + if (fabs(mi) > 0.01) { + double h = (double)WORLD_BLOCK_SIZE * 0.5; + double oxp = climate_ocean_dist_at(&w->climate, wx + h, wy); + double oxm = climate_ocean_dist_at(&w->climate, wx - h, wy); + double oyp = climate_ocean_dist_at(&w->climate, wx, wy + h); + double oym = climate_ocean_dist_at(&w->climate, wx, wy - h); + double gx = -(oxp - oxm) / (2.0 * h); + double gy = -(oyp - oym) / (2.0 * h); + double gl = sqrt(gx * gx + gy * gy); + if (gl > 1e-12) { + gx /= gl; gy /= gl; + double f = astro_coriolis(p, lat); + double fr = astro_coriolis(p, MONSOON_LAT_REF); + double frac = tanh(fabs(f / fr)); + // 地理上的逆时针(北半球偏向低压)= 本坐标系(y 向南)里的顺时针 + double ang = MONSOON_CROSS_MAX * frac * ((f >= 0.0) ? 1.0 : -1.0); + double ca = cos(ang), sa = sin(ang); + double ux = gx * ca + gy * sa; + double uy = -gx * sa + gy * ca; + double vmag = MONSOON_WIND * fabs(mi); + wx_v += ux * vmag; + wy_v += uy * vmag; + } + } + // 台风环流:绕中心逆时针(北半球) + if (s_int > 0.0 && s_dist < 1e29) { + for (int i = 0; i < STORM_MAX; i++) { + const struct Storm *st = &wf->storms.storms[i]; + if (!st->active) continue; + double dx = wx - st->x, dy = wy - st->y; + if (dx > (double)WORLD_W * 0.5) dx -= (double)WORLD_W; + if (dx < -(double)WORLD_W * 0.5) dx += (double)WORLD_W; + double d = sqrt(dx * dx + dy * dy); + if (d > st->radius * 4.0 || d < 1.0) continue; + double vmax = STORM_VMAX_MIN + + (STORM_VMAX_MAX - STORM_VMAX_MIN) * st->intensity; + double r = d / st->radius; + double v = vmax * exp(-(r - 0.9) * (r - 0.9) / 0.75); + double ss = (weather_latitude(st->y) >= 0.0) ? 1.0 : -1.0; + wx_v += ss * (-dy / d) * v; + wy_v += ss * ( dx / d) * v; + } + } + out->wind_x = wx_v; + out->wind_y = wy_v; + out->wind_speed = sqrt(wx_v * wx_v + wy_v * wy_v); + + // ---- 阵风 ---- + // 阵风系数:开阔海面 ~1.2,陆地 ~1.35,对流/台风下能到 2。 + double gust_f = 1.20 + (ocean ? 0.0 : 0.15) + + 0.30 * out->cloud * (1.0 - veg * 0.5) + + 0.55 * s_int; + out->gust = out->wind_speed * gust_f; + + // ---- 气压 ---- + // 平均场 + 大气潮汐 + 季风低压 + 台风。 + // 大气半日潮 S2(p) 是气压记录里最稳定的信号:赤道振幅约 1.5hPa, + // 峰值在地方时 10 时和 22 时,向极地按 cos²φ 衰减。日变化 S1(p) + // 陆地大(2~3hPa)海洋小(0.3hPa),午后最低。 + double p_s2 = 1.5 * cos(lat * D2R) * cos(lat * D2R) * + cos(4.0 * M_PI * (hour - 10.0) / 24.0); + double p_s1 = (ocean ? 0.35 : 2.1) * cos(2.0 * M_PI * (hour - 4.0) / 24.0); + double p_sl = 1013.0 + (cs.moisture - 0.5) * 12.0 - mr * 6.0 + + p_s2 + p_s1 + 1.5 * enso * trop; + p_sl -= s_int * (STORM_P_AMBIENT - STORM_P_MIN); + out->pressure = p_sl; + + // ---- 月相、潮汐 ---- + out->lunar_phase = astro_lunar_phase(p, &now); + out->moonlight = astro_moonlight(p, &now); + out->tide_m = astro_tide_m(p, &now, lat, lon, + hs.tidal_range > 0.0 ? hs.tidal_range : 0.5, + hs.tidal_form) + s_surge; +} diff --git a/src/weather.h b/src/weather.h new file mode 100644 index 0000000..a209d7f --- /dev/null +++ b/src/weather.h @@ -0,0 +1,188 @@ +#ifndef WEATHER_H +#define WEATHER_H + +#include +#include +#include "terrain.h" +#include "astro.h" + +struct World; + +// =============================================================== +// 天气层 +// =============================================================== +// 气候层给出的是**年均值**(降水场、大陆度、年均温),这一层把年均值 +// 展开成随时间变化的函数: +// +// 天文辐射 -> 季节相位(南北半球相反,地轴倾角直接生效) +// -> 海陆热力差 -> 季风 -> 雨季随纬度北推 +// 自转 -> 昼夜变化 +// 卫星 -> 月相 / 潮汐 +// 台风 -> 移动的强天气系统,叠加在背景场上 +// +// 所有函数都接受"游戏时间(秒)",不传时间就等于取年均值。 +// --------------------------------------------------------------- + +// 一个采样点的瞬时天气 +struct Weather_Sample { + double temperature; // 瞬时气温 ℃ + double temp_min; // 当日最低 + double temp_max; // 当日最高 + double solar_elev; // 太阳高度角(度,负 = 地平线下) + double insolation; // 瞬时天文辐射 W/m^2 + + double precipitation; // 瞬时降水强度 mm/h + double precip_24h; // 近 24 小时累计 mm + double humidity; // 相对湿度 0..1(有昼夜循环) + double dew_point; // 露点 ℃ + double cloud; // 云量 0..1(有昼夜循环) + double snow; // 降水是否以雪为主 0..1 + double swe_mm; // 积雪的雪水当量 mm(有记忆,来自水文层) + double snow_cover; // 积雪覆盖率 0..1 + + double wind_x, wind_y; // 风矢量 m/s(吹向的方向) + double wind_speed; + double gust; // 阵风 m/s(阵风系数 1.2~2.0) + double pressure; // 海平面气压 hPa(含大气潮汐) + + double monsoon; // 季风指数 -1..1(+1 = 夏季风最强) + double monsoon_rain; // 雨季强度 0..1(含随纬度推进) + + double storm; // 台风影响强度 0..1 + double storm_dist; // 到最近台风中心的距离 m + + double tide_m; // 潮位(相对平均海平面) + double moonlight; // 月光 0..1 + double lunar_phase; // 月相 0..1 + + // ---- 随时间变化的冰情 ---- + // 来自水文层(hydro.c)的年内冰情序列,所以湖面会随季节封冻和开河。 + double ice_thick; // 当前冰厚 m + double ice_trend; // 冰厚变化趋势 m/月,>0 结冰、<0 开河 + double jam_risk; // 凌汛风险 0..1(只在开河期拉高) + double water_temp; // 当前水温 ℃(海洋/湖泊/河道) + int freeze_month; // 封冻月 0..11,-1 = 全年不冻 + int break_month; // 开河月 + + // ---- 年际与季节内振荡 ---- + double enso; // ENSO 指数 -1..1(+1 = 厄尔尼诺位相) + double mjo; // MJO 指数 -1..1(+1 = 活跃位相,降水偏多) +}; + +// 当天冰厚(Stefan 定律,但用季节相位限制成"冬季积累、春季消融") +double weather_ice_thickness(const struct Planet_Params *p, double t_winter_water, + double season_phase); + +// =============================================================== +// 台风 +// =============================================================== +// 生成条件(参考西北太平洋):海温 > 26.5℃、纬度 5~25°、暖季。 +// 路径:先在信风里西行,到副高西缘转向极向,最后在冷海/陆地上消散。 + +#define STORM_MAX 32 + +struct Storm { + bool active; + uint64_t id; + double x, y; // 世界坐标(米) + double vx, vy; // 移动速度 m/s + double intensity; // 0..1(1 = 超强台风) + double radius; // 影响半径(米) + double age_days; + double born_seconds; + int basin; // 生成海盆编号(用于命名/统计) +}; + +struct Storm_Field { + struct Storm storms[STORM_MAX]; + int active_count; + uint64_t next_id; + double last_seconds; // 上次推进到的时间 + double spawn_accum; // 生成概率累加器 + double spawned_total; +}; + +// =============================================================== +// 季风:按纬度带预计算的海陆热力对比 +// =============================================================== + +struct Weather_Field { + int bands; // = WORLD_BLOCK_COUNT_Y + + float *insol_min; // 每个纬度带的年日辐射极值(算季节相位要用, + float *insol_max; // 逐次调用 astro_insolation_range 太贵) + float *insol_mean; + + float *band_landfrac; // 该纬度带的陆地占比 + float *band_T_land; // 陆地带年均温 + float *band_A_land; // 陆地季节振幅 + float *band_T_ocean; + float *band_A_ocean; + + struct Storm_Field storms; +}; + +void weather_field_build(struct Weather_Field *wf, struct World *w); +void weather_field_free(struct Weather_Field *wf); + +// 推进台风系统到指定游戏时间。可以在每帧调用,内部按固定步长积分。 +void weather_storms_update(struct Weather_Field *wf, struct World *w, + double t_seconds); + +// =============================================================== +// 采样 +// =============================================================== + +// 世界 x -> 经度(度) +static inline double weather_longitude(double wx) { + return wx / (double)WORLD_W * 360.0 - 180.0; +} +// 世界 y -> 纬度(度) +double weather_latitude(double wy); + +// 季节相位 -1..1,走的是查表版(比 astro_season_phase 快两个数量级) +double weather_season_phase(const struct Weather_Field *wf, + const struct Planet_Params *p, + double wy, double t_seconds); + +// 季风指数 -1..1 +double weather_monsoon_index(const struct Weather_Field *wf, + const struct Planet_Params *p, + double wy, double t_seconds); + +// 雨季强度 0..1:季风指数 × 雨季窗口(雨带随纬度北推,南方早北方晚) +double weather_monsoon_rain(const struct Weather_Field *wf, + const struct Planet_Params *p, + double wy, double t_seconds); + +// 降水的季节重分配权重(未归一化)= 1 + 季风增益 × 雨季窗口。 +// 水文层用它把年降水分配到 12 个月,再按年归一化——季风是重新分配 +// 水,不是凭空造水。 +double weather_precip_weight(const struct Weather_Field *wf, + const struct Planet_Params *p, + double wy, double t_seconds); + +// =============================================================== +// 年际振荡(ENSO)与季节内振荡(MJO) +// =============================================================== +// 真实气候里最大的"年与年不一样"的来源就是 ENSO:2~7 年的不规则振荡, +// 热带中东太平洋海温异常 ±2~3K,通过大气遥相关改掉全球降水、季风强度 +// 和台风生成数。这里用两个由种子决定周期、不可通约的正弦叠加来近似 +// 它的功率谱(不是周期现象,但能量集中在 2~7 年)。 +double weather_enso_index(const struct Planet_Params *p, + const struct Game_Time *t); + +// MJO:30~60 天、向东传播的热带季节内振荡。它是热带降水最强的 +// 季节内信号(活跃位相降水可翻倍,不活跃位相几乎不下雨),也是 +// 台风成簇生成的原因。lon_deg 为经度,波向东传所以相位随经度递减。 +double weather_mjo_index(const struct Planet_Params *p, + const struct Game_Time *t, double lon_deg); + +// ENSO 的海温异常中心经度(度)。真实世界在 150°W 附近,这里由种子决定。 +double weather_enso_center_lon(const struct Planet_Params *p); + +// 瞬时天气。t_seconds < 0 表示只取年均值(不计算昼夜/季节/台风)。 +void weather_sample(struct World *w, double wx, double wy, double elevation, + double t_seconds, struct Weather_Sample *out); + +#endif diff --git a/src/world.c b/src/world.c new file mode 100644 index 0000000..b09aec8 --- /dev/null +++ b/src/world.c @@ -0,0 +1,126 @@ +#include "world.h" +#include "river.h" +#include + +// =============================================================== +// 创建世界选项 → 区块生成参数 +// =============================================================== +// 这三个数组就是"选项接进生成器"的全部语义。想改手感只改这里。 +// +// ore_abundance : 只放大非造岩矿物(矿石/煤/宝石/稀土…),造岩矿物保持 1.0, +// 否则整个地壳成分会被一起抬起来,看不出"矿多矿少"。 +// difficulty : 平移每种化合物的噪声阈值。阈值越高越难越过, +// 矿化区域越小越分散 —— 影响的是"矿好不好找"。 +// realism : 对最终权重取幂。标准=1.0 保持地质规则原样; +// 休闲<1 把分布压平(处处都有点矿);硬核>1 让岩石/板块/ +// 环境的约束更尖锐(贫富分化,找矿更依赖地质知识)。 +// --------------------------------------------------------------- + +static const double ORE_ABUNDANCE_MULT[ORE_COUNT] = { + 0.4, // ORE_SCARCE + 1.0, // ORE_NORMAL + 1.8, // ORE_ABUNDANT + 3.0 // ORE_PARADISE +}; + +static const double DIFFICULTY_THRESHOLD_SHIFT[DIFFICULTY_COUNT] = { + -0.05, // DIFFICULTY_EASY 阈值降低,矿化区域更大 + 0.00, // DIFFICULTY_NORMAL + 0.05, // DIFFICULTY_HARD + 0.12 // DIFFICULTY_BRUTAL +}; + +static const double REALISM_GEOLOGY_GAMMA[REALISM_COUNT] = { + 0.7, // REALISM_CASUAL + 1.0, // REALISM_STANDARD + 1.4 // REALISM_HARDCORE +}; + +void world_compound_settings(const struct World_Config *config, + struct Compound_Settings *out) { + int ore = config->ore_abundance; + int diff = config->difficulty; + int real = config->realism; + + if (ore < 0 || ore >= ORE_COUNT) ore = ORE_NORMAL; + if (diff < 0 || diff >= DIFFICULTY_COUNT) diff = DIFFICULTY_NORMAL; + if (real < 0 || real >= REALISM_COUNT) real = REALISM_STANDARD; + + double ore_mult = ORE_ABUNDANCE_MULT[ore]; + + for (int c = 0; c < COMPOUND_COUNT; c++) { + out->abundance[c] = + compound_is_rock_forming((enum Compound_Id)c) ? 1.0 : ore_mult; + } + + out->threshold_shift = DIFFICULTY_THRESHOLD_SHIFT[diff]; + out->geology_gamma = REALISM_GEOLOGY_GAMMA[real]; +} + +// =============================================================== +// 世界生命周期 +// =============================================================== + +struct World *world_create(const struct World_Config *config) { + struct World *w = calloc(1, sizeof(struct World)); + if (w == NULL) return NULL; + + w->seed = config->seed; + w->config = *config; + w->now = game_time_at(0.0); + planet_params_init(&w->planet, w->seed); + world_compound_settings(config, &w->settings); + + w->blocks = malloc(sizeof(struct World_Block) * WORLD_BLOCK_COUNT); + if (w->blocks == NULL) { + free(w); + return NULL; + } + + w->plates = plate_init(w->seed, w->blocks); + + // 第一步:用地形生成气候(降水 / 温度 / 大陆度) + climate_field_build(&w->climate, w->seed, w->blocks, w->plates); + + // 第二步:地形 + 气候 -> 水系;水系再回头改地形和气候,反复迭代到收敛。 + // 这里就是"来回修饰很多次"的那一层,细节全在 river.c。 + w->rivers = calloc(1, sizeof(struct River_Field)); + if (w->rivers != NULL) { + river_build(w->rivers, w, config->river_iterations); + if (w->rivers->n == 0) { // 分配失败,降级成"没有河流的世界" + free(w->rivers); + w->rivers = NULL; + } + } + + // 第三步:天气层。把年均气候展开成时间的函数——季节相位查表、 + // 海陆热力对比(季风的驱动)、台风系统。 + weather_field_build(&w->weather, w); + + // 第四步:季节水文层。把年降水分配到 12 个月(雨带迁移 + 季风), + // 过一遍积雪/土壤水桶,沿水系汇流成 12 个月的水文过程线,并算出 + // 水温、湖面分层、冰厚与封冻/开河日期、潮差。约 70MB,见 hydro.c。 + w->hydro = calloc(1, sizeof(struct Hydro_Field)); + if (w->hydro != NULL) { + hydro_build(w->hydro, w); + if (w->hydro->n == 0) { free(w->hydro); w->hydro = NULL; } + } + return w; +} + +void world_destroy(struct World *w) { + if (w == NULL) return; + weather_field_free(&w->weather); + if (w->hydro != NULL) { + hydro_free(w->hydro); + free(w->hydro); + } + if (w->rivers != NULL) { + river_free(w->rivers); // 约 70MB 的水文网格,必须先放 + free(w->rivers); + } + climate_field_free(&w->climate); + free(w->plates._p); + free(w->blocks); + free(w); +} diff --git a/src/world.h b/src/world.h new file mode 100644 index 0000000..0dd190a --- /dev/null +++ b/src/world.h @@ -0,0 +1,78 @@ +#ifndef WORLD_STATE_H +#define WORLD_STATE_H + +#include +#include "terrain.h" +#include "compound.h" +#include "climate.h" +#include "astro.h" +#include "weather.h" +#include "hydro.h" + +struct River_Field; // 完整定义见 river.h + +// --------------------------------------------------------------- +// 创建世界界面的选项 +// --------------------------------------------------------------- + +enum { + DIFFICULTY_EASY, + DIFFICULTY_NORMAL, + DIFFICULTY_HARD, + DIFFICULTY_BRUTAL, + DIFFICULTY_COUNT +}; + +enum { + ORE_SCARCE, + ORE_NORMAL, + ORE_ABUNDANT, + ORE_PARADISE, + ORE_COUNT +}; + +enum { + REALISM_CASUAL, + REALISM_STANDARD, + REALISM_HARDCORE, + REALISM_COUNT +}; + +#define WORLD_NAME_MAX 64 + +struct World_Config { + char name[WORLD_NAME_MAX]; + uint64_t seed; + int difficulty; + int ore_abundance; + int realism; + int river_iterations; // 景观演化迭代次数,<=0 = 用默认值 +}; + +// --------------------------------------------------------------- +// 世界状态 +// --------------------------------------------------------------- + +struct World { + uint64_t seed; + struct World_Config config; + struct Compound_Settings settings; // 由 config 的三个选项推导,见 world_compound_settings + struct Climate_Field climate; // 全球降水场 / 大陆度,见 climate.c + struct River_Field *rivers; // 水系、河谷、冲积平原,见 river.c + struct Planet_Params planet; // 天文参数(地球基准 + 种子微扰) + struct Weather_Field weather; // 季风纬度带、日辐射查表、台风系统 + struct Hydro_Field *hydro; // 12 个月的雪/土壤水/水温/流量/冰,见 hydro.c + struct Game_Time now; // 当前世界时间 + struct World_Block *blocks; // WORLD_BLOCK_COUNT 个,承载板块/高程 + struct Plate_list plates; +}; + +struct World *world_create(const struct World_Config *config); +void world_destroy(struct World *w); + +// 把创建世界的三个选项翻译成区块生成参数。 +// 所有数值都在 world.c 顶部的表里,改语义只改那一处。 +void world_compound_settings(const struct World_Config *config, + struct Compound_Settings *out); + +#endif