aboutsummaryrefslogtreecommitdiffstats
path: root/src/game/data.cpp
blob: bbcf2d0be38f738e64c3a5fa61482648b3d33e11 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
#include "game/data.hpp"
#include "engine/script.hpp"

#include <filesystem>
#include <algorithm>
#include <cstdio>

// sol2's string-literal table keys trip a GCC -Warray-bounds false positive
// under inlining/optimisation. The access is correct; silence the noise here.
#if defined(__GNUC__) && !defined(__clang__)
#pragma GCC diagnostic ignored "-Warray-bounds"
#endif

namespace fs = std::filesystem;

namespace {
constexpr float DEG2RAD = 3.14159265358979323846f / 180.0f;

MaterialDef read_material(const sol::table& m) {
    MaterialDef d{};
    d.name            = m.get_or("name", std::string("unnamed"));
    d.stiffness       = m.get_or("stiffness", 600.0f);
    d.damping         = m.get_or("damping", 12.0f);
    d.mass            = m.get_or("mass", 0.25f);
    d.max_compression = m.get_or("max_compression", 0.90f);
    d.max_expansion   = m.get_or("max_expansion", 1.10f);
    d.angle_threshold = m.get_or("angle_threshold", 30.0f) * DEG2RAD;  // data is degrees
    d.min_length      = m.get_or("min_length", 0.4f);
    d.max_length      = m.get_or("max_length", 3.0f);
    d.max_link_length = m.get_or("max_link_length", 6.0f);
    d.hit_points      = m.get_or("hit_points", 150.0f);
    d.flammable       = m.get_or("flammable", true);
    d.burn_rate       = m.get_or("burn_rate", 15.0f);
    d.spread_time     = m.get_or("spread_time", 2.0f);
    d.blocks_projectiles = m.get_or("blocks_projectiles", true);
    d.blocks_beam        = m.get_or("blocks_beam", true);
    d.tension_only    = m.get_or("tension_only", false);
    d.half_width      = m.get_or("half_width", 0.15f);
    // Defaults match the flat costs struts used before they became per-material.
    d.cost_metal      = m.get_or("cost_metal", 5.0f);
    d.cost_energy     = m.get_or("cost_energy", 25.0f);
    d.texture         = m.get_or("texture", std::string(""));
    d.texture_forts   = m.get_or("texture_forts", std::string(""));

    sol::optional<sol::table> col = m["color"];
    d.r = col ? col->get_or(1, 0.8f) : 0.8f;
    d.g = col ? col->get_or(2, 0.5f) : 0.5f;
    d.b = col ? col->get_or(3, 0.2f) : 0.2f;
    d.a = col ? col->get_or(4, 1.0f) : 1.0f;
    return d;
}
} // namespace

std::vector<MaterialDef> load_materials(ScriptEngine& script,
                                        const std::string& data_dir) {
    std::vector<MaterialDef> out;

    // 1. Base data.
    if (!script.run_file(data_dir + "/materials.lua")) return out;

    // 2. Mods, ordered by (priority asc, path). Each mod.lua sets Priority;
    //    each materials.lua mutates the shared global Materials table.
    std::error_code ec;
    std::string mods_dir = data_dir + "/mods";
    std::vector<std::pair<int, std::string>> mods;
    if (fs::is_directory(mods_dir, ec)) {
        for (const auto& e : fs::directory_iterator(mods_dir, ec)) {
            if (!e.is_directory()) continue;
            std::string mp = e.path().string();
            if (!fs::exists(mp + "/materials.lua")) continue;
            int priority = 5;
            if (fs::exists(mp + "/mod.lua") && script.run_file(mp + "/mod.lua")) {
                sol::optional<int> p = script.lua()["Priority"];
                if (p) priority = *p;
            }
            mods.emplace_back(priority, mp);
        }
        std::sort(mods.begin(), mods.end());
        for (const auto& [prio, mp] : mods) {
            printf("Mod: applying %s (priority %d)\n", mp.c_str(), prio);
            script.run_file(mp + "/materials.lua");
        }
    }

    // 3. Read the final Materials array (1-based Lua array part, in order).
    sol::optional<sol::table> mats = script.lua()["Materials"];
    if (!mats) {
        fprintf(stderr, "load_materials: no global 'Materials' table\n");
        return out;
    }
    for (std::size_t i = 1; ; i++) {
        sol::object o = (*mats)[i];
        if (o.get_type() != sol::type::table) break;
        out.push_back(read_material(o.as<sol::table>()));
    }
    printf("Loaded %zu materials from Lua\n", out.size());
    return out;
}

namespace {
// Run <data_dir>/<file> then every mod's <file> (priority, name order).
void run_layered(ScriptEngine& script, const std::string& data_dir,
                 const std::string& file) {
    if (!script.run_file(data_dir + "/" + file)) return;
    std::error_code ec;
    std::string mods_dir = data_dir + "/mods";
    std::vector<std::pair<int, std::string>> mods;
    if (fs::is_directory(mods_dir, ec)) {
        for (const auto& e : fs::directory_iterator(mods_dir, ec)) {
            if (!e.is_directory()) continue;
            std::string mp = e.path().string();
            if (!fs::exists(mp + "/" + file)) continue;
            int priority = 5;
            if (fs::exists(mp + "/mod.lua") && script.run_file(mp + "/mod.lua")) {
                sol::optional<int> p = script.lua()["Priority"];
                if (p) priority = *p;
            }
            mods.emplace_back(priority, mp);
        }
        std::sort(mods.begin(), mods.end());
        for (const auto& [prio, mp] : mods)
            script.run_file(mp + "/" + file);
    }
}

WeaponDef read_weapon(const sol::table& w) {
    WeaponDef d{};
    d.name               = w.get_or("name", std::string("unnamed"));
    d.muzzle_speed       = w.get_or("muzzle_speed", 35.0f);
    d.reload             = w.get_or("reload", 2.0f);
    d.splash_damage      = w.get_or("splash_damage", 200.0f);
    d.splash_radius      = w.get_or("splash_radius", 3.0f);
    d.knockback          = w.get_or("knockback", 60.0f);
    d.projectile_radius  = w.get_or("projectile_radius", 0.15f);
    d.fire_chance        = w.get_or("fire_chance", 0.0f);
    d.min_fire_angle     = w.get_or("min_fire_angle", -20.0f) * DEG2RAD;
    d.max_fire_angle     = w.get_or("max_fire_angle",  30.0f) * DEG2RAD;
    d.is_beam            = w.get_or("is_beam", false);
    d.beam_range         = w.get_or("beam_range", 60.0f);
    d.beam_dps           = w.get_or("beam_dps", 120.0f);
    d.beam_duration      = w.get_or("beam_duration", 1.5f);
    d.energy_cost        = w.get_or("energy_cost", 0.0f);
    d.recoil             = w.get_or("recoil", 0.0f);
    d.texture            = w.get_or("texture", std::string(""));
    d.projectile_texture = w.get_or("projectile_texture", std::string(""));
    d.texture_forts            = w.get_or("texture_forts", std::string(""));
    d.projectile_texture_forts = w.get_or("projectile_texture_forts", std::string(""));
    return d;
}
} // namespace

std::vector<WeaponDef> load_weapons(ScriptEngine& script, const std::string& data_dir) {
    std::vector<WeaponDef> out;
    run_layered(script, data_dir, "weapons.lua");
    sol::optional<sol::table> ws = script.lua()["Weapons"];
    if (!ws) { fprintf(stderr, "load_weapons: no global 'Weapons' table\n"); return out; }
    for (std::size_t i = 1; ; i++) {
        sol::object o = (*ws)[i];
        if (o.get_type() != sol::type::table) break;
        out.push_back(read_weapon(o.as<sol::table>()));
    }
    printf("Loaded %zu weapons from Lua\n", out.size());
    return out;
}

void build_map(const MapDef& m, BuildGraph& graph) {
    graph.nodes.clear();
    graph.edges.clear();
    // Clearing the vectors does NOT touch the private adjacency and edge-key
    // caches, so rebuild them now. Skipping this leaves the PREVIOUS map's edge
    // keys in the set and add_edge then refuses the new map's beams as
    // duplicates, quietly producing a fort that collapses on load.
    graph.rebuild();
    // Set the ground BEFORE welding: node_at asks is_on_ground() to decide which
    // endpoints are pinned foundations.
    graph.ground_level = m.ground_level;

    auto mat_index = [&](const std::string& nm) -> int {
        for (int i = 0; i < (int)graph.materials.size(); i++)
            if (graph.materials[i].name == nm) return i;
        return 0;
    };
    auto node_at = [&](float x, float y) -> int {
        int n = graph.find_nearest_node(x, y, BuildGraph::SNAP_RADIUS);
        return (n >= 0) ? n : graph.add_node(x, y, graph.is_on_ground(y));
    };

    int built = 0;
    for (const auto& b : m.beams) {
        int na = node_at(b.x1, b.y1), nb = node_at(b.x2, b.y2);
        if (graph.add_edge(na, nb, mat_index(b.material)) >= 0) { built++; continue; }
        // A dropped beam silently weakens the fort, so never fail quietly:
        // endpoints closer than SNAP_RADIUS collapse onto one node, and a
        // repeated node pair is refused as a duplicate.
        fprintf(stderr,
                "map '%s': beam (%g,%g)-(%g,%g) [%s] rejected -> nodes %d,%d%s\n",
                m.name.c_str(), b.x1, b.y1, b.x2, b.y2, b.material.c_str(),
                na, nb, na == nb ? " (endpoints snapped together)" : " (duplicate)");
    }

    for (auto& e : graph.edges) e.settle = 0.0f;   // prebuilt = already cured
    graph.rebuild();
    printf("Map '%s': %d prebuilt struts, ground %.1f\n",
           m.name.c_str(), built, m.ground_level);
}

namespace {
DeviceDef read_device(const sol::table& d) {
    DeviceDef v{};
    v.name            = d.get_or("name", std::string("device"));
    v.hp              = d.get_or("hp", 100.0f);
    v.energy_rate     = d.get_or("energy_rate", 0.0f);
    v.metal_rate      = d.get_or("metal_rate", 0.0f);
    v.energy_storage  = d.get_or("energy_storage", 0.0f);
    v.metal_storage   = d.get_or("metal_storage", 0.0f);
    v.needs_deposit   = d.get_or("needs_deposit", false);
    v.wind            = d.get_or("wind", false);
    v.wind_max_rate   = d.get_or("wind_max_rate", 15.0f);
    v.wind_max_height = d.get_or("wind_max_height", 20.0f);
    v.is_core         = d.get_or("is_core", false);
    v.half_w          = d.get_or("half_w", 0.6f);
    v.half_h          = d.get_or("half_h", 0.6f);
    v.cost_metal      = d.get_or("cost_metal", 0.0f);
    v.cost_energy     = d.get_or("cost_energy", 0.0f);
    v.texture         = d.get_or("texture", std::string(""));
    v.texture_forts   = d.get_or("texture_forts", std::string(""));
    sol::optional<sol::table> col = d["color"];
    v.r = col ? col->get_or(1, 0.8f) : 0.8f;
    v.g = col ? col->get_or(2, 0.8f) : 0.8f;
    v.b = col ? col->get_or(3, 0.8f) : 0.8f;
    return v;
}
} // namespace

std::vector<DeviceDef> load_devices(ScriptEngine& script, const std::string& data_dir) {
    std::vector<DeviceDef> out;
    run_layered(script, data_dir, "devices.lua");
    sol::optional<sol::table> ds = script.lua()["DeviceDefs"];
    if (!ds) { fprintf(stderr, "load_devices: no 'DeviceDefs' table\n"); return out; }
    for (std::size_t i = 1; ; i++) {
        sol::object o = (*ds)[i];
        if (o.get_type() != sol::type::table) break;
        out.push_back(read_device(o.as<sol::table>()));
    }
    printf("Loaded %zu devices from Lua\n", out.size());
    return out;
}

namespace {
MapDef read_map(const sol::table& M) {
    MapDef m;
    m.name         = M.get_or("name", std::string("unnamed"));
    m.description  = M.get_or("description", std::string(""));
    m.ground_level = M.get_or("ground_level", 1.0f);

    if (sol::optional<sol::table> dep = M["deposits"]) {
        for (std::size_t i = 1; ; i++) {
            sol::object o = (*dep)[i];
            if (o.get_type() != sol::type::table) break;
            sol::table p = o.as<sol::table>();
            m.deposits.emplace_back(p.get_or(1, 0.0f), p.get_or(2, 0.0f));
        }
    }
    if (sol::optional<sol::table> dv = M["devices"]) {
        for (std::size_t i = 1; ; i++) {
            sol::object o = (*dv)[i];
            if (o.get_type() != sol::type::table) break;
            sol::table d = o.as<sol::table>();
            m.devices.push_back({ d.get_or("type", std::string("reactor")),
                                  d.get_or("x", 0.0f), d.get_or("y", 0.0f),
                                  d.get_or("team", 0) });
        }
    }
    if (sol::optional<sol::table> wp = M["weapons"]) {
        for (std::size_t i = 1; ; i++) {
            sol::object o = (*wp)[i];
            if (o.get_type() != sol::type::table) break;
            sol::table w = o.as<sol::table>();
            m.weapons.push_back({ w.get_or("type", std::string("cannon")),
                                  w.get_or("x", 0.0f), w.get_or("y", 0.0f) });
        }
    }
    // structures[] -> beams[] {x1,y1,x2,y2,material}, flattened: which fort a
    // beam belonged to does not matter once it is welded into the graph.
    if (sol::optional<sol::table> st = M["structures"]) {
        for (std::size_t si = 1; ; si++) {
            sol::object so = (*st)[si];
            if (so.get_type() != sol::type::table) break;
            sol::table S = so.as<sol::table>();
            sol::optional<sol::table> beams = S["beams"];
            if (!beams) continue;
            for (std::size_t bi = 1; ; bi++) {
                sol::object bo = (*beams)[bi];
                if (bo.get_type() != sol::type::table) break;
                sol::table b = bo.as<sol::table>();
                m.beams.push_back({ b.get_or(1, 0.0f), b.get_or(2, 0.0f),
                                    b.get_or(3, 0.0f), b.get_or(4, 0.0f),
                                    b.get_or(5, std::string("wood")) });
            }
        }
    }
    return m;
}
} // namespace

std::vector<MapDef> load_maps(ScriptEngine& script, const std::string& data_dir) {
    std::vector<MapDef> out;
    run_layered(script, data_dir, "maps.lua");
    sol::optional<sol::table> maps = script.lua()["Maps"];
    if (!maps) { fprintf(stderr, "load_maps: no global 'Maps' table\n"); return out; }
    for (std::size_t i = 1; ; i++) {
        sol::object o = (*maps)[i];
        if (o.get_type() != sol::type::table) break;
        out.push_back(read_map(o.as<sol::table>()));
    }
    printf("Loaded %zu maps\n", out.size());
    return out;
}