diff --git a/CMakeLists.txt b/CMakeLists.txt index b19f49cab..614958cb2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -381,6 +381,7 @@ set(SOURCES "application/scriptedinput.cpp" "input/editormouseinput.cpp" "application/editoruilayer.cpp" +"application/editoruimodel.cpp" "application/editoruipanels.cpp" "application/scenarioloadermode.cpp" "application/scenarioloaderuilayer.cpp" diff --git a/application/editormode.cpp b/application/editormode.cpp index 7c9231d2b..2afaaa5cb 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -16,6 +16,8 @@ http://mozilla.org/MPL/2.0/. #include #include #include "application/editormode.h" +#include "vehicle/DynObj.h" +#include "vehicle/Train.h" #include "application/editormodeshared.h" #include "application/editorgestures.h" #include "scene/scenenodegroups.h" @@ -564,6 +566,18 @@ editor_mode::editor_mode() { ui()->set_workspace_options(editor_ui::workspace::roads, [this]() { render_road_tool_options(); }, [this]() { render_road_selection(); }); ui()->set_workspace_options(editor_ui::workspace::terrain, [this]() { render_terrain_tool_options(); }); ui()->set_workspace_bank(editor_ui::workspace::terrain, [this]() { render_texture_browser(); }, STR("Textures")); + ui()->set_workspace_options(editor_ui::workspace::models, [this]() { ui()->model_panel().render_tools(); }, [this]() { ui()->model_panel().render_selection(); }); + ui()->set_workspace_bank(editor_ui::workspace::models, [this]() { ui()->model_panel().render_bank(); }, STR("Model")); + ui()->set_edit_model([this]() { choose_work_area(work_area::models); }); + ui()->model_panel().place_model = [this](std::string const &File) { place_model_file(File); }; + ui()->model_panel().enter_cab = [this](TDynamicObject &Vehicle) { return enter_cab(Vehicle); }; + ui()->model_panel().place_vehicle = [this]() { + // the Trainset tool of the tracks: a click on a track, the vehicle picked, Place + choose_work_area(work_area::tracks); + show_track_tab(track_tab::lineside); + m_vehicle.tab().expand = true; + ui()->set_status(STR("Click a track, pick the vehicle and Place it; F7 goes back to the models")); + }; // a node picked in the scene window is selected as if clicked in the view; a double click flies the camera to it ui()->set_scene_select([this](scene::basic_node *Node, bool const Focus) { if (Focus) @@ -585,6 +599,7 @@ editor_mode::editor_mode() { ui()->set_new_scenery([this]() { m_newscenery_asked = true; }); ui()->set_open_scenery([this]() { m_openscenery_asked = true; }); ui()->set_memcell_focus([this](scene::basic_node *Node) { start_focus(Node); }); + ui()->set_model_focus([this](glm::dvec3 const &Point, double const Radius) { focus_sphere(Point, Radius); }); ui()->set_edit_menu([this]() { render_edit_menu(); }); ui()->set_tools_menu([this]() { render_track_presets_menu(); @@ -755,10 +770,12 @@ void editor_mode::start_focus(scene::basic_node *node, double duration) if (!node) return; - glm::dvec3 const center = node->location(); + focus_sphere(node->location(), std::max(1.0, static_cast(node->radius())), duration); +} +void editor_mode::focus_sphere(glm::dvec3 const ¢er, double const radius, double const duration) +{ // distance that frames the object's bounding sphere within the vertical FOV, with some margin - double const radius = std::max(1.0, static_cast(node->radius())); double const fovy = glm::radians(static_cast(Global.FieldOfView) / std::max(0.01, static_cast(Global.ZoomFactor))); double distance = radius / std::tan(fovy * 0.5) * 1.6; distance = std::clamp(distance, radius * 1.5, static_cast(kMaxPlacementDistance)); @@ -1732,7 +1749,33 @@ bool editor_mode::update() update_road_tool(); draw_road_overlay(); // the roads and the terrain are fields of work, their tools are drawn in the tool options window in place of the edit mode ones - ui()->set_workspace(m_terrain_open ? editor_ui::workspace::terrain : m_roadtool.window ? editor_ui::workspace::roads : editor_ui::workspace::none); + // the cab of the vehicle driven is drawn while it's edited in the field of work of the models, as from the seat of the driver + { + auto const &panel{ui()->model_panel()}; + auto const cabview{m_models_open && panel.shows_cab() && simulation::Train != nullptr && simulation::Train->Dynamic() == panel.vehicle()}; + if (cabview != m_cabview) + { + // the view from the cab has the vehicle as the owner of the camera (the sounds and the drops on the glass go by it), the + // free view none + m_cabview = cabview; + FreeFlyModeFlag = false == cabview; + if (false == cabview) + Camera.m_owner = nullptr; + else if (Camera.m_owner != panel.vehicle()) + { + Camera.m_owner = panel.vehicle(); + Camera.m_owneroffset = simulation::Train->pMechSittingPosition; + } + Global.pCamera = Camera; + } + } + ui()->set_workspace([this]() { + if (m_models_open) + return editor_ui::workspace::models; + if (m_terrain_open) + return editor_ui::workspace::terrain; + return m_roadtool.window ? editor_ui::workspace::roads : editor_ui::workspace::none; + }()); steps.step("roads"); // --- array: the one made last is kept in line with its settings --- @@ -4810,6 +4853,8 @@ void editor_mode::render_open_scenery_popup() void editor_mode::terrain_workspace(bool const Open) { m_terrain_open = Open; + if (Open) + m_models_open = false; if (false == Open) m_terrain_tool = terrain_tool::none; else if (m_streamer.active()) @@ -5796,8 +5841,9 @@ void editor_mode::render_array() void editor_mode::choose_edit_mode(nodebank_panel::edit_mode const Mode) { - // an edit mode is the field of work instead of the tracks, roads or terrain + // an edit mode is the field of work instead of the tracks, roads, terrain or models m_track_window_open = false; + m_models_open = false; m_roadtool.window = false; terrain_workspace(false); if (Mode != nodebank_panel::MODIFY) @@ -5805,8 +5851,70 @@ void editor_mode::choose_edit_mode(nodebank_panel::edit_mode const Mode) ui()->set_mode(Mode); } +bool editor_mode::enter_cab(TDynamicObject &Vehicle) +{ + // the train of the vehicle, made as the simulation makes it when someone gets in: it loads the cab + auto *train{simulation::Trains.find(Vehicle.name())}; + if (train == nullptr) + { + train = new TTrain(); + if (false == train->Init(&Vehicle)) + { + delete train; + ui()->set_status(format(STR_C("The cab of %s couldn't be loaded, the log says why"), Vehicle.name().c_str()), true); + return false; + } + simulation::Trains.insert(train); + } + if (false == m_driven_before_cab.has_value()) + m_driven_before_cab = (simulation::Train != nullptr) ? simulation::Train->Dynamic()->name() : std::string{}; + simulation::Train = train; + if ((Vehicle.mdKabina == nullptr) || (Vehicle.mdKabina == Vehicle.mdModel)) + return false; + // in the seat of the driver, looking ahead from the cab taken + auto const side{Vehicle.OccupiedCab() < 0 ? -1.0 : 1.0}; + auto const look{Vehicle.VectorFront() * side}; + Camera.Pos = Vehicle.GetWorldPosition(train->pMechSittingPosition); + Camera.Angle = glm::vec3(0.0f, static_cast(std::atan2(-look.x, -look.z)), 0.0f); + Camera.m_owner = &Vehicle; + Camera.m_owneroffset = train->pMechSittingPosition; + Global.pCamera = Camera; + ui()->set_status(format(STR_C("In the cab of %s; the editor draws it while the cab is edited"), Vehicle.name().c_str())); + return true; +} + +void editor_mode::place_model_file(std::string const &File, std::string const &Parameters) +{ + // on the ground some way ahead of the camera, as far as Insert would put it by a click there + auto const view{GfxRenderer->Camera_View_Matrix()}; + glm::dvec3 ahead{-view[0][2], 0.0, -view[2][2]}; + ahead = glm::length(ahead) > 1e-6 ? glm::normalize(ahead) : glm::dvec3{0.0, 0.0, 1.0}; + auto const where{placement_on_ground(Camera.Pos + ahead * 12.0)}; + // a name in a line of the scenery ends at a space: a file with one would be read as another + if (File.find_first_of(" \t") != std::string::npos) + { + ui()->set_status(format(STR_C("The model %s can't be put in: a scenery doesn't take a space in the name of a file"), File.c_str()), true); + return; + } + auto *placed{simulation::State.create_model("node -1 0 none model 0 0 0 0 " + File + " none " + (Parameters.empty() ? std::string{} : Parameters + " ") + "endmodel", "editor_", where)}; + if (placed == nullptr) + { + ui()->set_status(format(STR_C("The model %s couldn't be put in, the log says why"), File.c_str()), true); + return; + } + placed->m_name = "editor_" + placed->uuid.to_string(); + std::string as_text; + placed->export_as_text(as_text); + push_snapshot(placed, EditorSnapshot::Action::Add, as_text); + m_node = placed; + ui()->set_node(m_node); + ui()->set_status(format(STR_C("%s stands in the scenery; Whole model in the toolbar moves it"), File.c_str())); +} + editor_mode::work_area editor_mode::current_work_area() const { + if (m_models_open) + return work_area::models; // the terrain is shown over the tracks, see the tool options window if (m_terrain_open) return work_area::terrain; @@ -5835,6 +5943,7 @@ void editor_mode::choose_work_area(work_area const Area) break; case work_area::roads: m_track_window_open = false; + m_models_open = false; terrain_workspace(false); m_roadtool.window = true; break; @@ -5843,6 +5952,11 @@ void editor_mode::choose_work_area(work_area const Area) m_roadtool.window = false; terrain_workspace(true); break; + case work_area::models: + // a model of the scenery or a vehicle; a click on another model selects it, as in the surroundings + choose_edit_mode(nodebank_panel::MODIFY); + m_models_open = true; + break; } } @@ -5861,8 +5975,9 @@ void editor_mode::render_workspaces() {STR_C("Roads"), work_area::roads, editor_icons::icon::work_roads, STR_C("Roads and junctions, level crossings, the points where the traffic comes and goes")}, {STR_C("Terrain"), work_area::terrain, editor_icons::icon::work_terrain, STR_C("Heightmap terrain: chunks, sculpting, painting, water, orthophoto")}, {STR_C("Catenary"), work_area::catenary, editor_icons::icon::work_catenary, STR_C("The overhead catenary: poles with cantilevers, gantries, the wires of the chains")}, + {STR_C("Models"), work_area::models, editor_icons::icon::work_models, STR_C("The models of the vehicles and of the scenery: their lights, the parts of a vehicle, moving and turning their parts")}, }; - char const *const keys[] = {"F2", "F3", "F4", "F5", "F6"}; + char const *const keys[] = {"F2", "F3", "F4", "F5", "F6", "F7"}; auto const current{current_work_area()}; auto const &style{ImGui::GetStyle()}; auto *list{ImGui::GetWindowDrawList()}; @@ -7046,6 +7161,9 @@ void editor_mode::render_shortcuts_window() bool editor_mode::gizmo_shown() const { + // the models move their parts with a gizmo of their own, the model as a whole only when Whole model is chosen + if (m_models_open) + return ui()->model_panel().moves_whole(); return ui()->mode() == nodebank_panel::TRACK ? m_track_gizmo_on : m_gizmo_enabled; } @@ -7123,8 +7241,9 @@ void editor_mode::render_gizmo() return; } - // the transform gizmo is suppressed while editing terrain, so the brush/chunk tool owns the mouse - if (!gizmo_shown() || terrain_brush() || terrain_clicking()) + // the transform gizmo is suppressed while editing terrain, so the brush/chunk tool owns the mouse; the window of an EU07M + // model shows the gizmo of a node of the model instead + if (!gizmo_shown() || terrain_brush() || terrain_clicking() || ui()->model_gizmo_shown()) { m_gizmo_using = false; m_track_gizmo_using = false; @@ -7493,6 +7612,9 @@ void editor_mode::on_scroll(double const Xoffset, double const Yoffset) void editor_mode::update_camera(double const Deltatime) { Camera.Update(); + // in the cab the camera moves with the vehicle, by its offset in it, as the camera of the driver does + if (m_cabview && Camera.m_owner != nullptr) + Camera.Pos = Camera.m_owner->GetWorldPosition(Camera.m_owneroffset); if (Global.EditorOrtho) { Camera.Angle.x = -M_PI_2; @@ -7586,6 +7708,7 @@ void editor_mode::ride_enter() void editor_mode::enter() { m_statebackup = {Global.pCamera, FreeFlyModeFlag, Global.ControlPicking}; + m_cabview = false; // the view from outside to start with, the cab is drawn again once it's edited // the editor changes the tracks, their sleepers are worked out as they're needed track_sleepers::lay_in_background(false); // the editor may remove the tracks and the vehicles the recording refers to: it ends here @@ -7692,6 +7815,14 @@ void editor_mode::enter() void editor_mode::exit() { + // a pantograph held down by the model panel would cut the power of the vehicle driven next, one held up would rise without air + ui()->model_panel().release_holds(); + // the vehicle driven before a cab was entered in the editor is the player's again + if (m_driven_before_cab.has_value()) + { + simulation::Train = m_driven_before_cab->empty() ? nullptr : simulation::Trains.find(*m_driven_before_cab); + m_driven_before_cab.reset(); + } m_ride.leave(); track_sleepers::lay_in_background(true); // the driver's view has no menu to switch the drawn cursor off: the system one there @@ -7895,6 +8026,7 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in case GLFW_KEY_F4: choose_work_area(work_area::roads); break; case GLFW_KEY_F5: choose_work_area(work_area::terrain); break; case GLFW_KEY_F6: choose_work_area(work_area::catenary); break; + case GLFW_KEY_F7: choose_work_area(work_area::models); break; // the edit modes in the order of the toolbar; in the track mode the digits typed as a value were taken already case GLFW_KEY_1: handled = ui()->mode() != nodebank_panel::TRACK; if (handled) choose_edit_mode(nodebank_panel::MODIFY); break; case GLFW_KEY_2: handled = ui()->mode() != nodebank_panel::TRACK; if (handled) choose_edit_mode(nodebank_panel::ADD); break; @@ -7993,6 +8125,18 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in // shortcuts: undo/redo. not in the middle of a drag, it would go on from the state which was undone if (Global.ctrlState && (Key == GLFW_KEY_Z || Key == GLFW_KEY_Y) && is_press(Action) && (m_track_gizmo_using || m_track_set_using || m_straights.dragging || m_extend.active || m_switch.placing || m_point_drag.active || m_handle_drag.active || m_roadtool.lifting)) return; + // in the field of work of the models the changes of the model are taken back first, then those of the scenery (a model put in or + // moved as a whole); while the whole model is moved, those of the scenery + if (Global.ctrlState && (Key == GLFW_KEY_Z || Key == GLFW_KEY_Y) && is_press(Action) && m_models_open) + { + auto &panel{ui()->model_panel()}; + auto const whole{panel.moves_whole()}; + if (Key == GLFW_KEY_Z && (whole || false == panel.undo())) + undo_last(); + else if (Key == GLFW_KEY_Y && (whole || false == panel.redo())) + redo_last(); + return; + } if (Global.ctrlState && Key == GLFW_KEY_Z && is_press(Action)) { // in the catenary tool its own changes are taken back first @@ -8035,6 +8179,8 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in // the chunks of the terrain selected, where the terrain is the field of work; else what's selected in the scenery if (is_press(Action) && m_terrain_open && false == m_terrain_selection.empty()) remove_selected_chunks(); + else if (is_press(Action) && m_models_open) + ui()->model_panel().remove_selected(); // a light of the model; the scenery isn't changed there else if (is_press(Action)) delete_selected(); break; @@ -8363,8 +8509,12 @@ void editor_mode::on_mouse_button(int const Button, int const Action, int const auto const additive{mode == nodebank_panel::MODIFY && (Mods & GLFW_MOD_SHIFT) != 0}; GfxRenderer->Pick_Node_Callback( [this, mode, rotation_mode, fixed_rotation_value, additive](scene::basic_node *node) { - // the press turned out to be meant for the UI - if (!viewport_click()) + // the press turned out to be meant for the UI, or for the gizmo or a mark of a light of the model window + if (!viewport_click() || ui()->model_took_press()) + return; + // in the field of work of the models a click picks a part of the model shown, or another model; anything else + // leaves the selection as it is + if (m_models_open && (ui()->model_panel().pick(node) || dynamic_cast(node) == nullptr)) return; auto *const previous{m_node}; diff --git a/application/editormode.h b/application/editormode.h index ad09e9d5e..498f58ba3 100644 --- a/application/editormode.h +++ b/application/editormode.h @@ -73,6 +73,7 @@ class TAnimModel; // a tool of a field of work of the editor, a button in the toolbar and over the 3d view struct editor_tool_button; class TTrack; +class TDynamicObject; struct catenary_editor; // application/editormodecatenary.h @@ -344,6 +345,8 @@ class editor_mode : public application_mode, private editor_track::observer, pri // focus camera smoothly on specified node void start_focus(scene::basic_node *node, double duration = 0.6); + // the camera flown to look at a sphere of the world, from the side it views it from now + void focus_sphere(glm::dvec3 const &Center, double Radius, double Duration = 0.6); // drops the node straight down onto the nearest surface below (terrain or another object). its group goes along with it, // unless Alone: then the node goes by itself. Joined: undone together with the change before @@ -869,6 +872,14 @@ class editor_mode : public application_mode, private editor_track::observer, pri // samples the selected model instance's geometry into the chunks of the terrain it covers, then removes it void capture_terrain(); bool m_terrain_open{false}; // the terrain is the field of work, chosen in the toolbar + bool m_models_open{false}; // the models are the field of work, chosen in the toolbar + // a model of the folder of the models put in the scenery and selected; Parameters go after its skin, such as "lights 3" + void place_model_file(std::string const &File, std::string const &Parameters = {}); + bool enter_cab(TDynamicObject &Vehicle); // the cab of the vehicle loaded as by getting in, the camera in the seat of the driver + // the vehicle driven before the first "Get in the cab" of the editor (its name; empty when none was), driven again as the editor + // is left: the cab entered is the editor's, not the player's + std::optional m_driven_before_cab; + bool m_cabview{false}; // the cab of the vehicle driven is drawn, as from the seat of the driver float m_terrain_spacing{2.0f}; // point spacing of the chunks made and of the spacing tool float m_terrain_baseheight{0.0f}; // height of chunks made where there's no ground int m_terrain_add_count{4}; // chunks along a side added around the camera @@ -998,6 +1009,7 @@ class editor_mode : public application_mode, private editor_track::observer, pri void render_viewport_overlays(); // the tools of the field of work, in the order of the toolbar void work_area_tools(std::vector &Buttons); + void model_tools(std::vector &Buttons); // the toolbar of the field of work of the models // the tools of the field of work in the toolbar, as icons with their names void render_toolbar_tools(); // what the row of the toolbar holds, written at its left end: the fields of work, the tools @@ -1211,7 +1223,8 @@ class editor_mode : public application_mode, private editor_track::observer, pri tracks, roads, terrain, - catenary // the catenary tool of the tracks, as a field of work of its own + catenary, // the catenary tool of the tracks, as a field of work of its own + models // the EU07M models of the scenery and of the vehicles }; work_area current_work_area() const; void choose_work_area(work_area const Area); diff --git a/application/editormodenmt.cpp b/application/editormodenmt.cpp index 1b83a96ef..fc51970af 100644 --- a/application/editormodenmt.cpp +++ b/application/editormodenmt.cpp @@ -2293,6 +2293,9 @@ void editor_mode::render_empty_scenery_hint() auto const &tracks{simulation::Paths.sequence()}; if (std::any_of(tracks.begin(), tracks.end(), [](TTrack const *Track) { return Track != nullptr && false == Track->m_editorremoved && rail(*Track); })) return; + // a scenery of models alone, such as one put up to look at a model, isn't empty either + if (std::ranges::any_of(simulation::Instances.sequence(), [](TAnimModel const *Instance) { return Instance != nullptr; })) + return; auto const low{editor_ui::view_min()}; auto const high{editor_ui::view_max()}; auto *list{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; diff --git a/application/editormodeselftestscene.cpp b/application/editormodeselftestscene.cpp index 78234e7b9..bf1a08e5c 100644 --- a/application/editormodeselftestscene.cpp +++ b/application/editormodeselftestscene.cpp @@ -372,6 +372,102 @@ editor_mode::selftest_result editor_mode::selftest_scene(std::string const &comm WriteLog(format("SELFTEST mapstate tiles on the ground %zu, at guessed heights %zu", grounded, guessed)); return selftest_result::handled; } + if (command == "modelmode") + { + // the field of work of the models + choose_work_area(work_area::models); + WriteLog("SELFTEST modelmode"); + return selftest_result::handled; + } + if (command == "modeltool") + { + // lights, parts, elements or animations + std::string name; + words >> name; + using model_tool = eu07m_model_panel::tool; + auto tool{model_tool::lights}; + if (name == "parts") + tool = model_tool::parts; + else if (name == "elements") + tool = model_tool::elements; + else if (name == "animations") + tool = model_tool::animations; + ui()->model_panel().choose_tool(tool); + WriteLog("SELFTEST modeltool " + name); + return selftest_result::handled; + } + if (command == "modelplace") + { + // a model of the folder of the models put in front of the camera, with the parameters of the node after its skin + std::string file; + words >> file; + std::string parameters; + std::getline(words >> std::ws, parameters); + place_model_file(file, parameters); + WriteLog("SELFTEST modelplace " + file + (m_node != nullptr ? "" : ": not placed")); + return selftest_result::handled; + } + if (command == "modelvehicle") + { + // a vehicle of the name, its body or its cab ("cab") + std::string name; + std::string part; + words >> name >> part; + auto const picked{ui()->model_panel().pick_vehicle(name, part == "cab" ? 1 : 0)}; + WriteLog("SELFTEST modelvehicle " + name + " " + part + (picked ? "" : ": no such vehicle")); + return selftest_result::handled; + } + if (command == "modelsave") + { + auto const saved{ui()->model_panel().save_model()}; + WriteLog(std::string{"SELFTEST modelsave"} + (saved ? "" : ": not saved")); + return selftest_result::handled; + } + if (command == "modelbrightness") + { + float brightness{1.f}; + words >> brightness; + auto const set{ui()->model_panel().set_brightness(brightness)}; + WriteLog("SELFTEST modelbrightness " + std::to_string(brightness) + (set ? "" : ": no light picked")); + return selftest_result::handled; + } + if (command == "modelimport") + { + auto const imported{ui()->model_panel().import_model()}; + WriteLog(std::string{"SELFTEST modelimport"} + (imported ? "" : ": not imported")); + return selftest_result::handled; + } + if (command == "modeladdlight") + { + // a light added in the middle of the part picked: spot or point + std::string kind; + words >> kind; + auto const added{ui()->model_panel().add_test_light(kind == "spot")}; + WriteLog("SELFTEST modeladdlight " + kind + (added ? "" : ": not added")); + return selftest_result::handled; + } + if (command == "modelundo" || command == "modelredo" || command == "modelremove") + { + auto &panel{ui()->model_panel()}; + auto done{false}; + if (command == "modelundo") + done = panel.undo(); + else if (command == "modelredo") + done = panel.redo(); + else + done = panel.remove_selected(); + WriteLog("SELFTEST " + command + (done ? "" : ": nothing done")); + return selftest_result::handled; + } + if (command == "modelnode") + { + // a node picked in the window of the EU07M model shown + std::string name; + words >> name; + auto const found{ui()->select_model_node(name)}; + WriteLog("SELFTEST modelnode " + name + (found ? "" : ": no such node")); + return selftest_result::handled; + } if (command == "selectmodel") { glm::dvec3 point{0.0}; diff --git a/application/editormodetrack.cpp b/application/editormodetrack.cpp index 95f3062b2..8bfdef532 100644 --- a/application/editormodetrack.cpp +++ b/application/editormodetrack.cpp @@ -28,6 +28,7 @@ http: #include "scene/scene.h" #include "scene/scenelayers.h" #include "simulation/simulation.h" +#include "model/AnimModel.h" #include "utilities/Logs.h" #include "utilities/translation.h" @@ -506,6 +507,7 @@ void editor_mode::show_track_tab(track_tab const Wanted) { auto const Tab{Wanted == track_tab::straights || Wanted == track_tab::route ? plan_tab_for(selected_track()) : Wanted}; m_track_window_open = true; + m_models_open = false; m_roadtool.window = false; if (Tab == m_track_tab) return; @@ -2284,6 +2286,9 @@ void editor_mode::draw_empty_scenery_hint() auto const &paths{simulation::Paths.sequence()}; if (std::any_of(paths.begin(), paths.end(), [](TTrack const *Track) { return Track != nullptr && false == Track->m_editorremoved; })) return; + // a scenery of models alone, such as one put up to look at a model, isn't one to lay tracks in + if (std::ranges::any_of(simulation::Instances.sequence(), [](TAnimModel const *Instance) { return Instance != nullptr; })) + return; // the line of the empty scenery in the middle of the view says the same: it gives way to this one m_empty_hint_frame = ImGui::GetFrameCount(); auto *list{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; diff --git a/application/editormodeviewport.cpp b/application/editormodeviewport.cpp index c0aa76bfc..5cfcc06ae 100644 --- a/application/editormodeviewport.cpp +++ b/application/editormodeviewport.cpp @@ -17,6 +17,7 @@ http://mozilla.org/MPL/2.0/. #include "editor/editorFormat.hpp" #include "editor/editorIcons.hpp" #include "editor/editorSettings.hpp" +#include "model/AnimModel.h" #include "rendering/renderer.h" #include "utilities/Globals.h" #include "utilities/translation.h" @@ -235,6 +236,9 @@ void editor_mode::work_area_tools(std::vector &Buttons) Buttons.push_back({icon::lanes, STR_C("Show lanes"), nullptr, STR_C("The lanes of the roads drawn as the paths the vehicles take"), tool.lanes, [&tool]() { tool.lanes = !tool.lanes; }, true}); break; } + case work_area::models: + model_tools(Buttons); + break; case work_area::terrain: { // what the left button does on the terrain @@ -287,6 +291,41 @@ void editor_mode::work_area_tools(std::vector &Buttons) } } +void editor_mode::model_tools(std::vector &Buttons) +{ + using model_tool = eu07m_model_panel::tool; + auto &panel{ui()->model_panel()}; + auto const add = [&Buttons, &panel](icon const Picture, char const *Label, char const *Tooltip, model_tool const Tool) { + Buttons.push_back({Picture, Label, nullptr, Tooltip, panel.current_tool() == Tool, [&panel, Tool]() { panel.choose_tool(Tool); }}); + }; + add(icon::light, STR_C("Lights"), STR_C("The light sources of the model: change them, add them by a click on the model"), model_tool::lights); + if (panel.has_vehicle()) + add(icon::pantograph, STR_C("Parts of the vehicle"), STR_C("Pantographs up or down, lamps lit or off, couplers and hoses connected or not"), model_tool::parts); + add(icon::parts_tree, STR_C("All parts"), STR_C("All the parts of the model as a tree, with a search by name"), model_tool::elements); + if (panel.has_animations()) + add(icon::animation, STR_C("Animations"), STR_C("The animations of the model, tried in the view"), model_tool::animations); + auto const turning{panel.turning()}; + // the gizmo of the editor follows them while it moves the whole model + Buttons.push_back({icon::translate, STR_C("Move"), nullptr, STR_C("The arrows in the view move the part picked"), false == turning, [this, &panel]() { + panel.set_turning(false); + m_gizmo_op = gizmo_operation::translate; + }, true}); + Buttons.push_back({icon::rotate, STR_C("Turn"), nullptr, STR_C("The rings in the view turn the part picked"), turning, [this, &panel]() { + panel.set_turning(true); + m_gizmo_op = gizmo_operation::rotate; + }}); + auto const whole{panel.moves_whole()}; + Buttons.push_back({icon::objects, STR_C("Whole model"), nullptr, STR_C("The gizmo moves or turns the whole model in the scenery, not its part; the change is one of the scenery, saved with it"), whole, + [this, &panel, whole]() { + panel.set_whole(false == whole); + m_gizmo_op = panel.turning() ? gizmo_operation::rotate : gizmo_operation::translate; + }}); + Buttons.back().enabled = (dynamic_cast(m_node) != nullptr); + auto const marks{panel.marks_shown()}; + Buttons.push_back({icon::select, STR_C("Marks of the lights"), nullptr, STR_C("The round marks of the light sources in the view; a click on one picks the light"), marks, + [&panel, marks]() { panel.show_marks(false == marks); }, true}); +} + void editor_mode::render_toolbar_caption(char const *Text) { // as wide in both rows, so the buttons of the rows start one under the other. the rows are drawn with no spacing of items @@ -449,7 +488,7 @@ void editor_mode::render_viewport_gizmo() // the gizmo moves the models and the tracks; on the terrain the mouse is the brush's // in the tracks the row stays with the gizmo hidden, so it can be brought out with a click auto const tracks{ui()->mode() == nodebank_panel::TRACK}; - if ((false == tracks && false == m_gizmo_enabled) || current_work_area() == work_area::terrain || (tracks && track_plan_tab())) + if ((false == tracks && false == m_gizmo_enabled) || current_work_area() == work_area::terrain || current_work_area() == work_area::models || (tracks && track_plan_tab())) return; auto const tooltip{STR_C("What the handles of the gizmo on the selection do when dragged; Ctrl held snaps the values")}; auto const on{gizmo_shown()}; diff --git a/application/editoruilayer.cpp b/application/editoruilayer.cpp index 42a3d6289..a1eb0746a 100644 --- a/application/editoruilayer.cpp +++ b/application/editoruilayer.cpp @@ -637,6 +637,7 @@ void editor_ui::render_() render_tool_options(); render_inspector(); render_scene(); + m_modelpanel.update(m_node, m_workspace == workspace::models); // status bar: the outcome of the last operation, and the selected node if (ImGui::BeginViewportSideBar("##editorstatusbar", viewport, ImGuiDir_Down, ImGui::GetFrameHeight(), flags)) { @@ -731,7 +732,7 @@ void editor_ui::render_tool_options() return; ImGui::SetNextWindowSize(ImVec2S(400, 300), ImGuiCond_FirstUseEver); auto const current{mode()}; - auto const active{m_workspace == workspace::terrain || (m_workspace == workspace::roads && current != nodebank_panel::TRACK) ? m_workspace : workspace::none}; + auto const active{m_workspace == workspace::terrain || m_workspace == workspace::models || (m_workspace == workspace::roads && current != nodebank_panel::TRACK) ? m_workspace : workspace::none}; // a change of the mode brings the window forward, in case it shares its dock with another one auto const shown{active != workspace::none ? 100 + static_cast(active) : static_cast(current)}; if (shown != m_toolmode) @@ -766,6 +767,8 @@ void editor_ui::render_tool_options() name = STR_C("Roads"); else if (active == workspace::terrain) name = STR_C("Terrain"); + else if (active == workspace::models) + name = STR_C("Models"); ImGui::SeparatorText(name); if (active != workspace::none) { @@ -780,7 +783,8 @@ void editor_ui::render_tool_options() } else render_mode_options(current); - if (ImGui::CollapsingHeader(STR_C("Gizmo"))) + // the models have a gizmo of their own, over the part picked + if (active != workspace::models && ImGui::CollapsingHeader(STR_C("Gizmo"))) { if (m_gizmooptions) m_gizmooptions(); @@ -810,6 +814,8 @@ void editor_ui::render_inspector() ImGui::End(); return; } + if (m_editmodel && m_modelpanel.editable(m_node) && ImGui::Button(STR_C("Edit this model (F7)"))) + m_editmodel(); if (ImGui::CollapsingHeader(STR_C("Node properties"), ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::Indent(); diff --git a/application/editoruilayer.h b/application/editoruilayer.h index d7fc890e1..fcf0f2a94 100644 --- a/application/editoruilayer.h +++ b/application/editoruilayer.h @@ -11,6 +11,7 @@ http://mozilla.org/MPL/2.0/. #include "application/uilayer.h" #include "application/editoruipanels.h" +#include "application/editoruimodel.h" namespace scene { @@ -115,6 +116,16 @@ class editor_ui : public ui_layer void set_new_scenery(std::function New) { m_newscenery = std::move(New); } void set_open_scenery(std::function Open) { m_openscenery = std::move(Open); } void set_memcell_focus(std::function Focus) { m_memcellspanel.focus = std::move(Focus); } + void set_model_focus(std::function Focus) { m_modelpanel.focus = std::move(Focus); } + // the window of an EU07M model shows its own gizmo, of the node picked in it, in place of the one of the editor + bool model_gizmo_shown() const { return m_modelpanel.gizmo_shown(); } + // the last press in the 3d view went to that gizmo or to a mark of a light of the model, not to picking a node + bool model_took_press() const { return m_modelpanel.took_press(); } + bool select_model_node(std::string_view Name) { return m_modelpanel.select_node(Name); } + // the field of work of the models: the model shown and edited there + eu07m_model_panel &model_panel() { return m_modelpanel; } + // the inspector offers to edit the model selected in the field of work of the models + void set_edit_model(std::function Edit) { m_editmodel = std::move(Edit); } // draws the base layers under the scenery at the bottom of the layers window (they live in the editor mode) void set_base_layers(std::function Renderer) { m_layerspanel.base_layers = std::move(Renderer); } void show_layers() @@ -144,6 +155,7 @@ class editor_ui : public ui_layer none, roads, terrain, + models, count_ }; void set_workspace(workspace const Workspace) @@ -268,6 +280,8 @@ class editor_ui : public ui_layer std::function m_bendoptions; bool m_bendexpand{false}; scene::basic_node *m_node{nullptr}; // currently bound scene node, if any + eu07m_model_panel m_modelpanel; // the EU07M model of the selected instance or of a vehicle, in the field of work of the models + std::function m_editmodel; bool m_track{false}; // windows of an unpinned dock, and the edge they're hidden at struct autohide_group diff --git a/application/editoruimodel.cpp b/application/editoruimodel.cpp new file mode 100644 index 000000000..bd0ea593f --- /dev/null +++ b/application/editoruimodel.cpp @@ -0,0 +1,2526 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "application/editoruimodel.h" + +#include "application/editorprojection.h" + +#include "model/AnimModel.h" +#include "model/Model3d.h" +#include "model/eu07m/eu07m_build.h" +#include "model/eu07m/eu07m_convert.h" +#include "model/eu07m/eu07m_dump.h" +#include "model/eu07m/eu07m_io.h" +#include "model/eu07m/eu07m_store.h" +#include "scene/scenenode.h" +#include "simulation/simulation.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/utilities.h" +#include "vehicle/DynObj.h" +#include "vehicle/Train.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +namespace payload = eu07m::payload; + +// the nodes of a model the panel shows open at once +constexpr std::size_t small_model{32}; + +// the radius of the sphere around a node the camera frames, metres: close enough to see a lamp +constexpr double node_focus_radius{1.0}; + +// the flags of a node of a light source added here, as those of the light points converted from E3D: a transform of its own +// (0x8000) and the passes it is drawn in (0xB0) +constexpr std::uint32_t light_node_flags{0x80B0}; + +// the room left for the labels beside the fields of the properties, in heights of the font +constexpr float label_width{13.f}; + +// the model of the part of the vehicle: 0 the body, 1 the cab +TModel3d *vehicle_model(TDynamicObject const *Vehicle, int const Part) +{ + if (Vehicle == nullptr) + { + return nullptr; + } + return Part == 1 ? Vehicle->mdKabina : Vehicle->mdModel; +} + +// the submodels of the model in the order of the nodes of its file: the tree the game has, walked depth first +void collect_submodels(TSubModel *Submodel, std::vector &Submodels) +{ + for (auto *submodel{Submodel}; submodel != nullptr; submodel = submodel->NextGet()) + { + Submodels.push_back(submodel); + collect_submodels(submodel->ChildGet(), Submodels); + } +} + +// the name of a component type, its four characters +std::string fourcc_text(std::uint32_t const Type) +{ + std::string result(4, ' '); + for (std::size_t idx = 0; idx < 4; ++idx) + { + result[idx] = static_cast((Type >> (8 * idx)) & 0xFF); + } + return result; +} + +struct type_name +{ + std::uint32_t type; + char const *name; +}; + +// what a component is, in words +char const *component_name(std::uint32_t const Type) +{ + namespace component = eu07m::component; + static std::array const names{{{component::properties, "Properties"}, + {component::socket, "Socket"}, + {component::joint, "Joint"}, + {component::spring, "Spring"}, + {component::chain, "Chain"}, + {component::variants, "Variants"}, + {component::channel, "Channel"}, + {component::light_slot, "Light slot"}, + {component::light, "Light source"}, + {component::emitter, "Emitter"}, + {component::model_reference, "Attached model"}, + {component::collision, "Collision shape"}, + {component::legacy_animation, "Animation (E3D)"}, + {component::legacy_text, "Text (E3D)"}, + {component::legacy_stars, "Stars (E3D)"}, + {component::legacy_material, "Material (E3D)"}}}; + auto const found{std::ranges::find(names, Type, &type_name::type)}; + return found != names.end() ? STR_C(found->name) : STR_C("Component"); +} + +struct part_label +{ + char const *name; + char const *text; +}; + +// what a part of the vehicle is, in words; its own name when it isn't known +char const *part_text(char const *Name) +{ + static std::array const labels{{{"headlamp11", "Upper headlamp, front"}, + {"headlamp12", "Right headlamp, front"}, + {"headlamp13", "Left headlamp, front"}, + {"highbeam12", "Right high beam, front"}, + {"highbeam13", "Left high beam, front"}, + {"headsignal12", "Right signal lamp, front"}, + {"headsignal13", "Left signal lamp, front"}, + {"headlamp21", "Upper headlamp, rear"}, + {"headlamp22", "Right headlamp, rear"}, + {"headlamp23", "Left headlamp, rear"}, + {"highbeam22", "Right high beam, rear"}, + {"highbeam23", "Left high beam, rear"}, + {"headsignal22", "Right signal lamp, rear"}, + {"headsignal23", "Left signal lamp, rear"}, + {"coupler1", "Coupler hook, front"}, + {"coupler2", "Coupler hook, rear"}, + {"cpneumatic1", "Brake hose, front"}, + {"cpneumatic1r", "Brake hose, front, other side"}, + {"cpneumatic2", "Brake hose, rear"}, + {"cpneumatic2r", "Brake hose, rear, other side"}, + {"pneumatic1", "Supply hose, front"}, + {"pneumatic1r", "Supply hose, front, other side"}, + {"pneumatic2", "Supply hose, rear"}, + {"pneumatic2r", "Supply hose, rear, other side"}}}; + std::string_view const name{Name}; + auto const found{std::ranges::find_if(labels, [name](part_label const &Label) { return name == Label.name; })}; + return found != labels.end() ? STR_C(found->text) : Name; +} + +// the lamps are named head... and high... +bool is_lamp(std::string_view const Name) +{ + return Name.starts_with("head") || Name.starts_with("high"); +} + +// the lamps of the front end have 1 before their last digit, those of the rear 2 +bool is_front(std::string_view const Name) +{ + return (Name.size() >= 2) && (Name[Name.size() - 2] == '1'); +} + +// a string of the model edited by its text; an empty text is no string +bool edit_string(char const *Label, eu07m::model &Model, std::uint32_t &Id) +{ + std::array buffer{}; + auto const text{Model.string(Id)}; + std::memcpy(buffer.data(), text.data(), std::min(text.size(), buffer.size() - 1)); + ImGui::InputText(Label, buffer.data(), buffer.size()); + if (false == ImGui::IsItemDeactivatedAfterEdit()) + { + return false; + } + std::string_view const edited{buffer.data()}; + Id = edited.empty() ? eu07m::no_index : Model.intern(edited); + return true; +} + +// an enumeration of the format picked from the names of its values +template bool edit_enum(char const *Label, Enum_ &Value, std::initializer_list Names) +{ + std::vector const names{Names}; + auto index{static_cast(Value)}; + if (false == ImGui::Combo(Label, &index, names.data(), static_cast(names.size()))) + { + return false; + } + Value = static_cast(index); + return true; +} + +bool edit_flag(char const *Label, std::uint8_t &Flags, std::uint8_t const Bit) +{ + auto set{(Flags & Bit) != 0}; + if (false == ImGui::Checkbox(Label, &set)) + { + return false; + } + Flags = static_cast(set ? (Flags | Bit) : (Flags & ~Bit)); + return true; +} + +// a rotation as a quaternion x y z w, edited as angles in degrees +bool edit_rotation(char const *Label, std::array &Rotation) +{ + glm::quat const turn{Rotation[3], Rotation[0], Rotation[1], Rotation[2]}; + auto angles{glm::degrees(glm::eulerAngles(turn))}; + if (false == ImGui::DragFloat3(Label, glm::value_ptr(angles), 0.5f, 0.f, 0.f, "%.1f")) + { + return false; + } + auto const turned{glm::normalize(glm::quat{glm::radians(angles)})}; + Rotation = {turned.x, turned.y, turned.z, turned.w}; + return true; +} + +// the half angle of a cone in degrees, for the cosine the format keeps +bool edit_cone(char const *Label, float &Cosine) +{ + auto angle{glm::degrees(std::acos(std::clamp(Cosine, -1.f, 1.f)))}; + if (false == ImGui::DragFloat(Label, &angle, 0.25f, 0.f, 180.f, "%.1f")) + { + return false; + } + Cosine = std::cos(glm::radians(angle)); + return true; +} + +// the place of the node in the space of its parent +bool edit_place(eu07m::node_record &Node) +{ + auto changed{ImGui::DragFloat3(STR_C("Position, m"), Node.translation.data(), 0.005f, 0.f, 0.f, "%.3f")}; + changed |= edit_rotation(STR_C("Rotation, degrees"), Node.rotation); + changed |= ImGui::DragFloat3(STR_C("Scale"), Node.scale.data(), 0.01f, 0.f, 0.f, "%.3f"); + return changed; +} + +// the distances from which and up to which the node is drawn, kept squared +bool edit_range(eu07m::node_record &Node) +{ + auto from{std::sqrt(std::max(Node.range_min_sq, 0.f))}; + auto to{std::sqrt(std::max(Node.range_max_sq, 0.f))}; + auto changed{false}; + if (ImGui::DragFloat(STR_C("Visible from, m"), &from, 0.5f, 0.f, 100000.f, "%.1f")) + { + Node.range_min_sq = from * from; + changed = true; + } + if (ImGui::DragFloat(STR_C("Visible up to, m (0: no limit)"), &to, 0.5f, 0.f, 100000.f, "%.1f")) + { + Node.range_max_sq = to * to; + changed = true; + } + return changed; +} + +// the payload of the component at Offset of its data, edited by Edit; written back when it changed +template bool edit_payload(eu07m::model &Model, std::uint32_t const Index, std::size_t const Offset, Edit_ &&Edit) +{ + auto const &record{Model.components[Index]}; + auto const at{std::size_t{record.data_offset} + Offset}; + if ((Offset + sizeof(Payload_) > record.data_size) || (at + sizeof(Payload_) > Model.component_data.size())) + { + ImGui::TextDisabled("%s", STR_C("The data of the component is cut short")); + return false; + } + Payload_ value; + std::memcpy(&value, Model.component_data.data() + at, sizeof(value)); + if (false == Edit(value)) + { + return false; + } + std::memcpy(Model.component_data.data() + at, &value, sizeof(value)); + return true; +} + +bool edit_socket(eu07m::model &Model, payload::socket &Socket) +{ + auto changed{edit_string(STR_C("Role"), Model, Socket.role)}; + changed |= edit_enum(STR_C("End of the vehicle"), Socket.end, {STR_C("none"), STR_C("front"), STR_C("rear")}); + changed |= ImGui::InputScalar(STR_C("Index"), ImGuiDataType_U16, &Socket.index); + changed |= ImGui::DragFloat3(STR_C("Position, m"), Socket.position.data(), 0.001f, 0.f, 0.f, "%.4f"); + changed |= edit_rotation(STR_C("Rotation, degrees"), Socket.rotation); + return changed; +} + +bool edit_joint(eu07m::model &Model, payload::joint &Joint) +{ + auto changed{edit_enum(STR_C("Kind"), Joint.kind, {STR_C("fixed"), STR_C("hinge"), STR_C("ball"), STR_C("slider"), STR_C("screw")})}; + auto limited{Joint.limited != 0}; + if (ImGui::Checkbox(STR_C("Limited"), &limited)) + { + Joint.limited = limited ? 1 : 0; + changed = true; + } + changed |= edit_string(STR_C("Role"), Model, Joint.role); + changed |= ImGui::DragFloat3(STR_C("Axis"), Joint.axis.data(), 0.01f, -1.f, 1.f, "%.3f"); + changed |= ImGui::DragFloat(STR_C("Minimum"), &Joint.minimum, 0.01f); + changed |= ImGui::DragFloat(STR_C("Maximum"), &Joint.maximum, 0.01f); + changed |= ImGui::DragFloat(STR_C("Rest"), &Joint.rest, 0.01f); + if (Joint.kind == payload::joint_kind::screw) + { + changed |= ImGui::DragFloat(STR_C("Pitch, m a turn"), &Joint.pitch, 0.0005f, 0.f, 1.f, "%.4f"); + } + return changed; +} + +bool edit_channel(eu07m::model &Model, payload::channel &Channel) +{ + auto changed{edit_string(STR_C("Name"), Model, Channel.name)}; + changed |= ImGui::DragFloat(STR_C("Minimum"), &Channel.minimum, 0.01f); + changed |= ImGui::DragFloat(STR_C("Maximum"), &Channel.maximum, 0.01f); + changed |= ImGui::DragFloat(STR_C("Initial value"), &Channel.initial, 0.01f); + return changed; +} + +bool edit_binding(payload::channel_binding &Binding) +{ + auto changed{edit_enum(STR_C("Bound to"), Binding.kind, {STR_C("joint"), STR_C("clip"), STR_C("variants"), STR_C("light slot")})}; + auto target{Binding.target == eu07m::no_index ? -1 : static_cast(Binding.target)}; + if (ImGui::InputInt(STR_C("Target (component or clip, -1 none)"), &target)) + { + Binding.target = target < 0 ? eu07m::no_index : static_cast(target); + changed = true; + } + changed |= ImGui::DragFloat(STR_C("Scale"), &Binding.scale, 0.01f); + changed |= ImGui::DragFloat(STR_C("Offset"), &Binding.offset, 0.01f); + return changed; +} + +// a point light shines all around (the cone of -1); a spot made of one gets a cone to start with +void set_light_kind(payload::light &Light, payload::light_kind const Kind) +{ + Light.kind = Kind; + if (Kind == payload::light_kind::point) + { + Light.cos_falloff = -1.f; + Light.cos_hotspot = -1.f; + } + else if (Light.cos_falloff <= -1.f) + { + Light.cos_falloff = std::cos(glm::radians(30.f)); + Light.cos_hotspot = std::cos(glm::radians(20.f)); + } +} + +bool edit_light(payload::light &Light) +{ + auto kind{Light.kind}; + auto changed{edit_enum(STR_C("Kind"), kind, {STR_C("point"), STR_C("spot")})}; + if (changed) + { + set_light_kind(Light, kind); + } + changed |= ImGui::ColorEdit3(STR_C("Colour"), Light.color.data()); + changed |= ImGui::DragFloat(STR_C("Intensity"), &Light.hotspot_power, 0.01f, 0.f, 100.f, "%.2f"); + changed |= ImGui::DragFloat(STR_C("Glowing sphere radius, m"), &Light.radius, 0.005f, 0.f, 10.f, "%.3f"); + if (Light.kind == payload::light_kind::spot) + { + changed |= edit_cone(STR_C("Cone, half angle in degrees"), Light.cos_falloff); + changed |= edit_cone(STR_C("Hotspot, half angle in degrees"), Light.cos_hotspot); + } + changed |= edit_flag(STR_C("Lights itself"), Light.flags, payload::light_flags::shade_self); + changed |= edit_flag(STR_C("No shadows"), Light.flags, payload::light_flags::no_shadows); + changed |= edit_flag(STR_C("Soft falloff"), Light.flags, payload::light_flags::soft_falloff); + changed |= edit_flag(STR_C("Light only"), Light.flags, payload::light_flags::light_only); + return changed; +} + +bool edit_light_slot(payload::light_slot &Slot) +{ + auto changed{ImGui::InputScalar(STR_C("Slot"), ImGuiDataType_U16, &Slot.slot)}; + changed |= ImGui::DragFloat(STR_C("Initial state"), &Slot.initial, 0.01f, 0.f, 10.f); + changed |= ImGui::ColorEdit3(STR_C("Colour (negative: of the sources)"), Slot.color.data(), ImGuiColorEditFlags_Float | ImGuiColorEditFlags_HDR); + return changed; +} + +bool edit_emitter(payload::emitter &Emitter) +{ + auto changed{edit_enum(STR_C("Kind"), Emitter.kind, {STR_C("smoke"), STR_C("steam"), STR_C("sparks")})}; + changed |= ImGui::DragFloat3(STR_C("Direction"), Emitter.direction.data(), 0.01f, -1.f, 1.f, "%.3f"); + return changed; +} + +bool edit_collision(eu07m::model &Model, payload::collision &Collision) +{ + auto changed{edit_enum(STR_C("Shape"), Collision.kind, {STR_C("box"), STR_C("sphere"), STR_C("capsule")})}; + changed |= edit_string(STR_C("Role"), Model, Collision.role); + changed |= ImGui::DragFloat3(STR_C("Centre"), Collision.centre.data(), 0.001f, 0.f, 0.f, "%.4f"); + changed |= edit_rotation(STR_C("Rotation, degrees"), Collision.rotation); + changed |= ImGui::DragFloat3(STR_C("Half extents"), Collision.size.data(), 0.001f, 0.f, 1000.f, "%.4f"); + return changed; +} + +bool edit_reference(eu07m::model &Model, payload::model_reference &Reference) +{ + auto changed{edit_string(STR_C("Model path"), Model, Reference.path)}; + changed |= edit_string(STR_C("Skin"), Model, Reference.skin); + return changed; +} + +bool edit_channel_component(eu07m::model &Model, std::uint32_t const Index) +{ + payload::channel channel; + auto changed{edit_payload(Model, Index, 0, [&Model, &channel](payload::channel &Value) { + auto const result{edit_channel(Model, Value)}; + channel = Value; + return result; + })}; + for (std::uint32_t binding = 0; binding < channel.binding_count; ++binding) + { + ImGui::PushID(static_cast(binding)); + auto const number{binding + 1}; + ImGui::SeparatorText(std::vformat(STR("Binding {}"), std::make_format_args(number)).c_str()); + changed |= edit_payload(Model, Index, sizeof(payload::channel) + binding * sizeof(payload::channel_binding), [](payload::channel_binding &Value) { return edit_binding(Value); }); + ImGui::PopID(); + } + return changed; +} + +// the components the panel edits field by field; the others are shown by their size +bool edit_component(eu07m::model &Model, std::uint32_t const Index) +{ + namespace component = eu07m::component; + switch (Model.components[Index].type) + { + case component::socket: return edit_payload(Model, Index, 0, [&Model](payload::socket &Value) { return edit_socket(Model, Value); }); + case component::joint: return edit_payload(Model, Index, 0, [&Model](payload::joint &Value) { return edit_joint(Model, Value); }); + case component::light: return edit_payload(Model, Index, 0, [](payload::light &Value) { return edit_light(Value); }); + case component::light_slot: return edit_payload(Model, Index, 0, [](payload::light_slot &Value) { return edit_light_slot(Value); }); + case component::emitter: return edit_payload(Model, Index, 0, [](payload::emitter &Value) { return edit_emitter(Value); }); + case component::collision: return edit_payload(Model, Index, 0, [&Model](payload::collision &Value) { return edit_collision(Model, Value); }); + case component::model_reference: + return edit_payload(Model, Index, 0, [&Model](payload::model_reference &Value) { return edit_reference(Model, Value); }); + case component::channel: return edit_channel_component(Model, Index); + default: break; + } + ImGui::TextDisabled("%s", std::vformat(STR("{} bytes, not edited here"), std::make_format_args(Model.components[Index].data_size)).c_str()); + return false; +} + +// the components aimed at the node, whether its range lists them or not +std::vector node_components(eu07m::model const &Model, std::uint32_t const Node) +{ + std::vector components; + for (std::uint32_t idx = 0; idx < Model.components.size(); ++idx) + { + if ((Model.components[idx].kind == eu07m::target_kind::node) && (Model.components[idx].target == Node)) + { + components.push_back(idx); + } + } + return components; +} + +// the name of the node and what its components are, in words +std::string node_label(eu07m::model const &Model, std::uint32_t const Node, std::vector const &Components) +{ + auto const name{Model.string(Model.nodes[Node].name)}; + auto label{name.empty() ? std::string{STR_C("(no name)")} : std::string{name}}; + std::vector kinds; + for (auto const component : Components) + { + auto const *kind{component_name(Model.components[component].type)}; + if (std::ranges::find(kinds, kind) == kinds.end()) + { + kinds.push_back(kind); + } + } + for (std::size_t idx = 0; idx < kinds.size(); ++idx) + { + label += (idx == 0 ? " [" : ", "); + label += kinds[idx]; + } + if (false == kinds.empty()) + { + label += "]"; + } + return label; +} + +} // namespace + +namespace +{ + +using box = std::pair; + +// the box of the geometry of the node, in its space; none for a node without geometry +std::optional node_box(eu07m::model const &Model, std::uint32_t const Node) +{ + auto const mesh{Model.nodes[Node].mesh}; + if ((mesh < 0) || (static_cast(mesh) >= Model.meshes.size())) + { + return std::nullopt; + } + auto const &record{Model.meshes[mesh]}; + std::optional result; + auto const last{std::min(std::size_t{record.primitive_first} + record.primitive_count, Model.primitives.size())}; + for (auto idx = std::size_t{record.primitive_first}; idx < last; ++idx) + { + auto const &primitive{Model.primitives[idx]}; + auto const end{std::min(std::size_t{primitive.base_vertex} + primitive.vertex_count, Model.positions.size())}; + for (auto vertex = std::size_t{primitive.base_vertex}; vertex < end; ++vertex) + { + glm::vec3 const point{Model.positions[vertex][0], Model.positions[vertex][1], Model.positions[vertex][2]}; + result = result ? box{glm::min(result->first, point), glm::max(result->second, point)} : box{point, point}; + } + } + return result; +} + +// the space of the submodel in the space of the model, as it stands in the file (not as an animation turned it) +glm::dmat4 model_space(TSubModel const &Submodel) +{ + float4x4 matrix; + Submodel.ParentMatrix(&matrix); + return glm::dmat4{glm::make_mat4(matrix.readArray())}; +} + +glm::dvec3 point_of(glm::dmat4 const &Matrix, glm::dvec3 const &Point) +{ + return glm::dvec3{Matrix * glm::dvec4{Point, 1.0}}; +} + +// the twelve edges of the box in the space of Matrix +void draw_box(ImDrawList *Drawlist, screen_projection const &Projection, glm::dmat4 const &Matrix, box const &Box, ImU32 const Color) +{ + auto const corner = [&Matrix, &Box](int const Index) { + return point_of(Matrix, glm::dvec3{(Index & 1) ? Box.second.x : Box.first.x, (Index & 2) ? Box.second.y : Box.first.y, (Index & 4) ? Box.second.z : Box.first.z}); + }; + for (int idx = 0; idx < 8; ++idx) + { + for (int const axis : {1, 2, 4}) + { + if ((idx & axis) == 0) + { + Projection.line(Drawlist, corner(idx), corner(idx | axis), Color, 2.f); + } + } + } +} + +// the axes of the space of Matrix from its origin: x red, y green, z blue +void draw_axes(ImDrawList *Drawlist, screen_projection const &Projection, glm::dmat4 const &Matrix, double const Length) +{ + auto const origin{point_of(Matrix, glm::dvec3{0.0})}; + Projection.line(Drawlist, origin, point_of(Matrix, glm::dvec3{Length, 0.0, 0.0}), IM_COL32(230, 60, 60, 255), 2.f); + Projection.line(Drawlist, origin, point_of(Matrix, glm::dvec3{0.0, Length, 0.0}), IM_COL32(60, 210, 60, 255), 2.f); + Projection.line(Drawlist, origin, point_of(Matrix, glm::dvec3{0.0, 0.0, Length}), IM_COL32(70, 120, 255, 255), 2.f); +} + +ImU32 light_colour(payload::light const &Light, int const Alpha) +{ + auto const channel = [](float const Value) { return static_cast(std::clamp(Value, 0.f, 1.f) * 255.f); }; + return IM_COL32(channel(Light.color[0]), channel(Light.color[1]), channel(Light.color[2]), Alpha); +} + +// the radius of the mark of a light source, pixels +constexpr float mark_radius{7.f}; + +} // namespace + +namespace +{ + +using part_hold = TDynamicObject::part_hold; +using pantograph_hold = TDynamicObject::pantograph_hold; + +// the buttons of a lamp, a coupler or a hose, and of a pantograph, in the order of these holds +constexpr std::array part_holds{part_hold::on, part_hold::off, part_hold::xon, part_hold::none}; +constexpr std::array pantograph_holds{pantograph_hold::up, pantograph_hold::down, pantograph_hold::none}; + +// the most changes taken back +constexpr std::size_t undo_depth{50}; + +// how far from the box of the geometry of a part a click still picks it, metres +constexpr double pick_margin{0.03}; + +// the radius of the sphere the camera frames around a vehicle, in its lengths +constexpr double vehicle_focus{0.6}; + +struct colour_preset +{ + char const *name; + std::array colour; +}; + +// the colours a light is often given +constexpr std::array colour_presets{{{"Warm white", {1.f, 0.85f, 0.6f}}, + {"White", {1.f, 1.f, 1.f}}, + {"Cold white", {0.8f, 0.9f, 1.f}}, + {"Red", {1.f, 0.08f, 0.04f}}, + {"Yellow", {1.f, 0.75f, 0.1f}}, + {"Green", {0.1f, 1.f, 0.3f}}, + {"Blue", {0.2f, 0.45f, 1.f}}}}; + +// a row of buttons of which one is chosen, as a switch of a few positions; the position clicked, none when none was +std::optional choice_buttons(char const *Id, std::size_t const Chosen, std::span const Labels) +{ + std::optional clicked; + ImGui::PushID(Id); + for (std::size_t idx = 0; idx < Labels.size(); ++idx) + { + if (idx > 0) + { + ImGui::SameLine(0.f, ImGui::GetStyle().ItemInnerSpacing.x); + } + auto const chosen{idx == Chosen}; + if (chosen) + { + ImGui::PushStyleColor(ImGuiCol_Button, ImGui::GetStyleColorVec4(ImGuiCol_HeaderActive)); + } + if (ImGui::Button(Labels[idx])) + { + clicked = idx; + } + if (chosen) + { + ImGui::PopStyleColor(); + } + } + ImGui::PopID(); + return clicked; +} + +template std::size_t position_of(std::array const &Values, Value_ const Value) +{ + return static_cast(std::ranges::find(Values, Value) - Values.begin()); +} + +// the name of a part in the first column of a table, the tooltip on it +void part_cell(char const *Text, char const *Tooltip) +{ + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted(Text); + if ((Tooltip != nullptr) && ImGui::IsItemHovered()) + { + ImGui::SetTooltip("%s", Tooltip); + } + ImGui::TableNextColumn(); +} + +// a row of a table: how the editor holds a part of the vehicle +void part_hold_row(TDynamicObject &Vehicle, std::size_t const Part) +{ + auto const *name{TDynamicObject::held_part_name(Part)}; + auto const variants{std::format("{0}_on / {0}_off / {0}_xon", name)}; + part_cell(part_text(name), variants.c_str()); + std::array const lamp{STR_C("Lit"), STR_C("Off"), STR_C("Dimmed"), STR_C("As the vehicle has it")}; + std::array const coupler{STR_C("Connected"), STR_C("Disconnected"), STR_C("Other position"), STR_C("As the vehicle has it")}; + if (auto const clicked{choice_buttons(name, position_of(part_holds, Vehicle.held_part(Part)), is_lamp(name) ? lamp : coupler)}) + { + Vehicle.hold_part(Part, part_holds[*clicked]); + } +} + +// a row of a table: how the editor holds a pantograph +void pantograph_hold_row(TDynamicObject &Vehicle, int const Pantograph) +{ + auto const number{Pantograph + 1}; + auto const label{std::vformat(STR("Pantograph {}"), std::make_format_args(number))}; + part_cell(label.c_str(), nullptr); + std::array const labels{STR_C("Up"), STR_C("Down"), STR_C("As the vehicle has it")}; + if (auto const clicked{choice_buttons(label.c_str(), position_of(pantograph_holds, Vehicle.held_pantograph(Pantograph)), labels)}) + { + Vehicle.hold_pantograph(Pantograph, pantograph_holds[*clicked]); + } +} + +// the parts of the vehicle Pick takes, those the model has, in a table under the title, with buttons to hold them all at once +template void part_group(TDynamicObject &Vehicle, char const *Title, bool const Lamps, Pick_ const &Pick) +{ + std::vector parts; + for (std::size_t idx = 0; idx < TDynamicObject::held_part_total; ++idx) + { + if (Vehicle.held_part_present(idx) && Pick(std::string_view{TDynamicObject::held_part_name(idx)})) + { + parts.push_back(idx); + } + } + if (parts.empty()) + { + return; + } + ImGui::SeparatorText(Title); + ImGui::PushID(Title); + auto const all = [&Vehicle, &parts](part_hold const Hold) { + for (auto const part : parts) + { + Vehicle.hold_part(part, Hold); + } + }; + if (ImGui::SmallButton(Lamps ? STR_C("Light them all") : STR_C("Connect them all"))) + { + all(part_hold::on); + } + ImGui::SameLine(); + if (ImGui::SmallButton(Lamps ? STR_C("Put them all out") : STR_C("Disconnect them all"))) + { + all(part_hold::off); + } + ImGui::SameLine(); + if (ImGui::SmallButton(STR_C("All as the vehicle has them"))) + { + all(part_hold::none); + } + if (ImGui::BeginTable("##parts", 2, ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_RowBg)) + { + for (auto const part : parts) + { + part_hold_row(Vehicle, part); + } + ImGui::EndTable(); + } + ImGui::PopID(); +} + +// the vehicle is still in the simulation +bool vehicle_exists(TDynamicObject const *Vehicle) +{ + return std::ranges::find(simulation::Vehicles.sequence(), Vehicle) != simulation::Vehicles.sequence().end(); +} + +// the scenery model is still in the scenery +bool instance_exists(TAnimModel const *Instance) +{ + return std::ranges::find(simulation::Instances.sequence(), Instance) != simulation::Instances.sequence().end(); +} + +// the place of the node, its range and its flags as another record has them +bool same_place(eu07m::node_record const &Left, eu07m::node_record const &Right) +{ + return (Left.translation == Right.translation) && (Left.rotation == Right.rotation) && (Left.scale == Right.scale) && (Left.flags == Right.flags) && + (Left.range_min_sq == Right.range_min_sq) && (Left.range_max_sq == Right.range_max_sq); +} + +// the point lies in the box, or within the margin of it +bool inside(std::pair const &Box, glm::dvec3 const &Point, double const Margin) +{ + auto const low{glm::dvec3{Box.first} - Margin}; + auto const high{glm::dvec3{Box.second} + Margin}; + return (Point.x >= low.x) && (Point.y >= low.y) && (Point.z >= low.z) && (Point.x <= high.x) && (Point.y <= high.y) && (Point.z <= high.z); +} + +// the turn which brings -z, the axis of a spot, onto the direction +glm::quat aim(glm::vec3 const &Direction) +{ + glm::vec3 const axis{0.f, 0.f, -1.f}; + auto const cosine{glm::dot(axis, Direction)}; + if (cosine < -0.9999f) + { + // the other way round: half a turn about y + return glm::quat{0.f, 0.f, 1.f, 0.f}; + } + auto const cross{glm::cross(axis, Direction)}; + return glm::normalize(glm::quat{1.f + cosine, cross.x, cross.y, cross.z}); +} + +// a text with no case, to look for another in it +std::string lowered(std::string_view const Text) +{ + std::string result{Text}; + std::ranges::transform(result, result.begin(), [](unsigned char const Character) { return static_cast(std::tolower(Character)); }); + return result; +} + +// the half angle of a cone in degrees, from its cosine +float cone_degrees(float const Cosine) +{ + return glm::degrees(std::acos(std::clamp(Cosine, -1.f, 1.f))); +} + +// the width of the beam of a spot and its bright middle, in degrees from its axis +bool edit_beam(payload::light &Light) +{ + auto changes{false}; + auto width{cone_degrees(Light.cos_falloff)}; + auto middle{std::min(cone_degrees(Light.cos_hotspot), width)}; + if (ImGui::SliderFloat(STR_C("Width of the beam, degrees"), &width, 1.f, 89.f, "%.0f")) + { + Light.cos_falloff = std::cos(glm::radians(width)); + Light.cos_hotspot = std::cos(glm::radians(std::min(middle, width))); + changes = true; + } + if (ImGui::IsItemHovered()) + { + ImGui::SetTooltip("%s", STR_C("From the axis of the beam to its edge")); + } + if (ImGui::SliderFloat(STR_C("Bright middle, degrees"), &middle, 0.f, width, "%.0f")) + { + Light.cos_hotspot = std::cos(glm::radians(middle)); + changes = true; + } + if (ImGui::IsItemHovered()) + { + ImGui::SetTooltip("%s", STR_C("The middle of the beam lit fully; from there to the edge it fades")); + } + return changes; +} + +} // namespace + +void eu07m_model_panel::update(scene::basic_node *Selected, bool const Active) +{ + m_gizmoshown = false; + m_active = Active; + if ((m_pickedvehicle != nullptr) && (false == vehicle_exists(m_pickedvehicle))) + { + m_pickedvehicle = nullptr; + } + if ((m_target.vehicle != nullptr) && (false == vehicle_exists(m_target.vehicle))) + { + open(target{}); + } + // the time stands still in the editor: the held pantographs are moved here + if (m_target.vehicle != nullptr) + { + m_target.vehicle->step_held_pantographs(ImGui::GetIO().DeltaTime); + } + if (false == Active) + { + m_placing.reset(); + m_tookpress = false; + return; + } + if ((m_target.instance != nullptr) && (false == instance_exists(m_target.instance))) + { + open(target{}); + } + if (Selected != m_lastselected) + { + // a scenery model clicked is edited in place of the vehicle picked + m_lastselected = Selected; + if (dynamic_cast(Selected) != nullptr) + { + m_pickedvehicle = nullptr; + } + } + auto const next{wanted(Selected)}; + if (next == m_target) + { + m_kept.reset(); + } + else if (false == m_dirty) + { + open(next); + } + else if ((false == m_kept.has_value()) || (*m_kept != next)) + { + m_pending = next; + } + render_unsaved_popup(); + if (m_placing && ImGui::IsKeyPressed(ImGuiKey_Escape, false)) + { + m_placing.reset(); + } + if ((m_source == nullptr) || m_path.empty()) + { + return; + } + // the model as it is between the presses and the drags: a change made by the next one takes it back to this + if ((false == ImGui::IsAnyItemActive()) && (false == ImGuizmo::IsUsing())) + { + m_before = take(false); + m_changing = false; + } + render_view(); +} + +eu07m_model_panel::target eu07m_model_panel::wanted(scene::basic_node *Selected) const +{ + target result; + if (m_pickedvehicle != nullptr) + { + result.vehicle = m_pickedvehicle; + } + else if (auto *instance{dynamic_cast(Selected)}; instance != nullptr) + { + result.instance = instance; + return result; + } + else if (simulation::Train != nullptr) + { + result.vehicle = simulation::Train->Dynamic(); + } + // the cab isn't loaded while the driver is outside + if ((result.vehicle != nullptr) && (m_part == 1) && (result.vehicle->mdKabina != nullptr)) + { + result.part = 1; + } + return result; +} + +void eu07m_model_panel::release_holds() const +{ + if ((m_target.vehicle != nullptr) && vehicle_exists(m_target.vehicle)) + { + m_target.vehicle->release_holds(); + } +} + +void eu07m_model_panel::open(target const &Target) +{ + // the vehicle shown before has its parts and pantographs back: a hold is only for the vehicle in the panel + if (Target.vehicle != m_target.vehicle) + { + release_holds(); + } + m_target = Target; + m_pending.reset(); + m_kept.reset(); + m_undo.clear(); + m_redo.clear(); + m_placing.reset(); + m_source = nullptr; + m_path.clear(); + m_problem.clear(); + m_importable = false; + m_model = eu07m::model{}; + m_submodels.clear(); + m_boxes.clear(); + m_selected = -1; + m_dirty = false; + m_message.clear(); + auto *source{Target.instance != nullptr ? Target.instance->pModel : vehicle_model(Target.vehicle, Target.part)}; + if (source != nullptr) + { + load(*source); + } +} + +bool eu07m_model_panel::load(TModel3d &Model) +{ + m_source = &Model; + if (false == Global.modelformat_eu07m) + { + m_problem = STR("The models of the EU07M format are turned off (modelformat in eu07.ini)"); + return false; + } + auto const path{FileCased(Model.NameGet() + ".ng3d")}; + if (path.empty()) + { + // one is made of the model as the game loaded it: for a vehicle, its body or its cab, that is what the game writes to the + // .e3d it makes of a .t3d (convertmodels) + m_importable = (false == FileCased(Model.NameGet() + ".e3d").empty()) || (false == FileCased(Model.NameGet() + ".t3d").empty()); + m_problem = m_importable ? STR("This model has no EU07M file yet. Import it to change its lights and parts.") + : STR("This model has no EU07M file, so it can't be edited here. The command eu07 -eu07m convert makes one of its E3D or T3D file"); + return false; + } + std::ifstream file{path, std::ios::binary | std::ios::ate}; + std::vector data(file.good() ? static_cast(file.tellg()) : 0); + file.seekg(0); + file.read(reinterpret_cast(data.data()), static_cast(data.size())); + eu07m::read_options options; + options.blocks = eu07m::store_source(eu07m::family_store(path)); + if (auto const result{eu07m::read(data, m_model, options)}; false == result.ok) + { + m_problem = std::vformat(STR("The EU07M file of the model can't be read: {}"), std::make_format_args(result.error)); + return false; + } + m_path = path; + // the submodels of the nodes, when the model the game has is the one of the file + collect_submodels(Model.GetSMRoot(), m_submodels); + if (m_submodels.size() != m_model.nodes.size()) + { + m_submodels.clear(); + } + for (std::uint32_t idx = 0; idx < m_model.nodes.size(); ++idx) + { + m_boxes.push_back(node_box(m_model, idx)); + } + m_cliptimes.assign(m_model.clips.size(), 0.f); + m_channels.clear(); + for (auto const &channel : Model.channels()) + { + m_channels.push_back(channel.initial); + } + m_before = take(false); + return true; +} + +void eu07m_model_panel::render_unsaved_popup() +{ + auto const title{std::string{STR_C("Changes not saved")} + "###eu07munsaved"}; + if (m_pending && (false == ImGui::IsPopupOpen(title.c_str()))) + { + ImGui::OpenPopup(title.c_str()); + } + if (false == ImGui::BeginPopupModal(title.c_str(), nullptr, ImGuiWindowFlags_AlwaysAutoResize)) + { + return; + } + auto const name{std::filesystem::path{m_path}.filename().string()}; + ImGui::TextUnformatted(std::vformat(STR("The model {} has changes which aren't saved."), std::make_format_args(name)).c_str()); + if (ImGui::Button(STR_C("Save them"))) + { + save(); + if (m_pending && (false == m_dirty)) + { + open(*m_pending); + } + else + { + // not saved: the message says why, the model stays + m_kept = m_pending; + m_pending.reset(); + } + ImGui::CloseCurrentPopup(); + } + ImGui::SameLine(); + if (ImGui::Button(STR_C("Throw them away"))) + { + // the model the game has is taken back to the file too + while (undo()) + { + // down to the model as the file has it + } + if (m_pending) + { + open(*m_pending); + } + ImGui::CloseCurrentPopup(); + } + ImGui::SameLine(); + if (ImGui::Button(STR_C("Go on with this one"))) + { + m_kept = m_pending; + m_pending.reset(); + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); +} + +void eu07m_model_panel::render_bank() +{ + ImGui::SeparatorText(STR_C("Edited model")); + if (m_source == nullptr) + { + ImGui::TextWrapped("%s", STR_C("Nothing picked yet.")); + } + else + { + auto const name{m_target.vehicle != nullptr ? m_target.vehicle->name() : m_target.instance->name()}; + ImGui::TextUnformatted(name.empty() ? STR_C("(no name)") : name.c_str()); + if (m_target.vehicle != nullptr) + { + render_vehicle_part(); + } + ImGui::TextDisabled("%s", m_path.empty() ? m_source->NameGet().c_str() : std::filesystem::path{m_path}.filename().string().c_str()); + } + ImGui::SeparatorText(STR_C("A model of the scenery")); + ImGui::TextWrapped("%s", STR_C("Click a model in the view to edit it.")); + render_insert(); + if (auto const *instance{dynamic_cast(m_lastselected)}; (instance != nullptr) && (m_pickedvehicle != nullptr)) + { + auto const &name{instance->name()}; + auto const label{std::vformat(STR("Back to {}"), std::make_format_args(name))}; + if (ImGui::Button(label.c_str())) + { + m_pickedvehicle = nullptr; + } + } + ImGui::SeparatorText(STR_C("Vehicles")); + if ((place_vehicle != nullptr) && ImGui::Button(STR_C("Put a vehicle on a track..."))) + { + place_vehicle(); + } + if (ImGui::IsItemHovered()) + { + ImGui::SetTooltip("%s", STR_C("The Trainset tool of the tracks: click a track, pick the vehicle and Place it; F7 brings you back here")); + } + auto const &vehicles{simulation::Vehicles.sequence()}; + if (vehicles.empty()) + { + ImGui::TextDisabled("%s", STR_C("The scenery has no vehicles.")); + return; + } + ImGui::TextDisabled("%s", STR_C("A click picks the vehicle and takes the camera to it")); + if (false == ImGui::BeginChild("##eu07mvehicles", ImVec2(0.f, 0.f), ImGuiChildFlags_Borders)) + { + ImGui::EndChild(); + return; + } + auto const *driven{simulation::Train != nullptr ? simulation::Train->Dynamic() : nullptr}; + ImGuiListClipper clipper; + clipper.Begin(static_cast(vehicles.size())); + while (clipper.Step()) + { + for (auto idx = clipper.DisplayStart; idx < clipper.DisplayEnd; ++idx) + { + auto *vehicle{vehicles[static_cast(idx)]}; + auto label{vehicle->name()}; + if (vehicle == driven) + { + label += std::string{" "} + STR_C("(driven)"); + } + label += "##vehicle" + std::to_string(idx); + if (ImGui::Selectable(label.c_str(), vehicle == m_target.vehicle)) + { + m_pickedvehicle = vehicle; + fly_to_vehicle(*vehicle); + } + } + } + ImGui::EndChild(); +} + +void eu07m_model_panel::render_vehicle_part() +{ + auto *vehicle{m_target.vehicle}; + auto const cab{(vehicle->mdKabina != nullptr) && (vehicle->mdKabina != vehicle->mdModel)}; + if (false == cab) + { + // the cab is loaded only by getting in: the button does what the game does then + if (ImGui::Button(STR_C("Get in the cab"))) + { + open_cab(); + } + if (ImGui::IsItemHovered()) + { + ImGui::SetTooltip("%s", STR_C("Loads the cab of the vehicle as the game does when you get in, and puts the camera in the seat of the driver")); + } + return; + } + std::array const parts{STR_C("Body"), STR_C("Cab")}; + if (auto const clicked{choice_buttons("##part", static_cast(m_target.part), parts)}) + { + // the other part is shown in the next frame; from the cab the camera goes out to look at the body + m_part = static_cast(*clicked); + if ((m_part == 1) && (enter_cab != nullptr)) + { + enter_cab(*vehicle); + } + else if (m_part == 0) + { + fly_to_vehicle(*vehicle); + } + } +} + +bool eu07m_model_panel::open_cab() +{ + auto *vehicle{m_target.vehicle != nullptr ? m_target.vehicle : m_pickedvehicle}; + if ((vehicle == nullptr) || (enter_cab == nullptr)) + { + return false; + } + m_pickedvehicle = vehicle; + if (false == enter_cab(*vehicle)) + { + m_message = STR("The vehicle has no cab of its own to get in"); + return false; + } + m_part = 1; + return true; +} + +void eu07m_model_panel::render_insert() +{ + if ((place_model == nullptr) || (false == ImGui::TreeNode(STR_C("Put a model in the scenery")))) + { + return; + } + auto searched{false}; + if (false == m_scanned) + { + // the folder of the models looked through once, when the list is first opened + m_scanned = true; + searched = true; + std::error_code error; + for (std::filesystem::recursive_directory_iterator entry{"models", std::filesystem::directory_options::skip_permission_denied, error}, end; entry != end; entry.increment(error)) + { + std::error_code status; + auto const extension{ToLower(entry->path().extension().string())}; + if ((false == entry->is_regular_file(status)) || ((extension != ".e3d") && (extension != ".t3d"))) + { + continue; + } + m_files.push_back(std::filesystem::relative(entry->path(), "models", status).generic_string()); + } + std::ranges::sort(m_files); + } + std::array buffer{}; + std::memcpy(buffer.data(), m_filesearch.data(), std::min(m_filesearch.size(), buffer.size() - 1)); + ImGui::SetNextItemWidth(-1.f); + if (ImGui::InputTextWithHint("##modelsearch", STR_C("Look for a model by its name, e.g. latarnia"), buffer.data(), buffer.size())) + { + m_filesearch = buffer.data(); + searched = true; + } + if (searched) + { + auto const wanted_text{lowered(m_filesearch)}; + m_found.clear(); + for (std::size_t idx = 0; idx < m_files.size(); ++idx) + { + if (lowered(m_files[idx]).find(wanted_text) != std::string::npos) + { + m_found.push_back(idx); + } + } + } + ImGui::TextDisabled("%s", STR_C("A click puts the model in front of the camera; then Whole model in the toolbar moves it")); + if (ImGui::BeginChild("##eu07mfiles", ImVec2(0.f, ImGui::GetTextLineHeightWithSpacing() * 8.f), ImGuiChildFlags_Borders)) + { + ImGuiListClipper clipper; + clipper.Begin(static_cast(m_found.size())); + while (clipper.Step()) + { + for (auto idx = clipper.DisplayStart; idx < clipper.DisplayEnd; ++idx) + { + auto const &file{m_files[m_found[static_cast(idx)]]}; + if (ImGui::Selectable((file + "##file" + std::to_string(idx)).c_str())) + { + place_model(file); + } + } + } + } + ImGui::EndChild(); + ImGui::TreePop(); +} + +bool eu07m_model_panel::import_model() +{ + if ((false == m_importable) || (m_source == nullptr)) + { + return false; + } + std::string error; + auto const written{eu07m::import_model(*m_source, error)}; + if (written.empty()) + { + m_message = std::vformat(STR("Not imported: {}"), std::make_format_args(error)); + return false; + } + open(m_target); + auto const name{std::filesystem::path{written}.filename().string()}; + m_message = std::vformat(STR("Imported to {}. Its lights and parts can be changed now"), std::make_format_args(name)); + return true; +} + +void eu07m_model_panel::render_tools() +{ + render_header(); + if (m_path.empty()) + { + return; + } + ImGui::PushItemWidth(-ImGui::GetFontSize() * label_width); + switch (m_tool) + { + case tool::lights: + render_lights_page(); + break; + case tool::parts: + render_parts_page(); + break; + case tool::elements: + render_elements_page(); + break; + case tool::animations: + render_animations_page(); + break; + } + ImGui::PopItemWidth(); +} + +void eu07m_model_panel::render_header() +{ + if (m_source == nullptr) + { + ImGui::TextWrapped("%s", STR_C("No model to edit. Click a model in the scenery, or pick a vehicle in the list on the left.")); + return; + } + if (false == m_problem.empty()) + { + ImGui::TextWrapped("%s", m_problem.c_str()); + if (m_importable && ImGui::Button(STR_C("Import to EU07M"))) + { + import_model(); + } + if (m_importable && ImGui::IsItemHovered()) + { + ImGui::SetTooltip("%s", STR_C("Writes an .ng3d file beside the model, made of the model as the game has it. From then on the game loads the model from it, in every scenery")); + } + // the game doesn't compare the .ng3d with the file it was made of: an update of that one is shadowed by it + if (m_importable) + { + ImGui::TextDisabled("%s", STR_C("While the .ng3d is there, a later update of the .e3d or .t3d doesn't reach the game: import it again, or delete the .ng3d")); + } + if (false == m_message.empty()) + { + ImGui::TextWrapped("%s", m_message.c_str()); + } + return; + } + ImGui::BeginDisabled(false == m_dirty); + if (ImGui::Button(STR_C("Save the changes"))) + { + save(); + } + ImGui::EndDisabled(); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + { + ImGui::SetTooltip("%s", STR_C("Writes the model to its file; until then nothing of it is changed on the disk")); + } + ImGui::SameLine(); + ImGui::BeginDisabled(m_undo.empty()); + if (ImGui::Button(STR_C("Undo"))) + { + undo(); + } + ImGui::EndDisabled(); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + { + ImGui::SetTooltip("%s", STR_C("Takes the last change of the model back (Ctrl+Z)")); + } + ImGui::SameLine(); + ImGui::BeginDisabled(m_redo.empty()); + if (ImGui::Button(STR_C("Redo"))) + { + redo(); + } + ImGui::EndDisabled(); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + { + ImGui::SetTooltip("%s", STR_C("Makes the change taken back again (Ctrl+Y)")); + } + if (m_dirty) + { + ImGui::SameLine(); + ImGui::TextColored(ImVec4(1.f, 0.7f, 0.3f, 1.f), "%s", STR_C("Not saved")); + } + if (m_submodels.empty()) + { + ImGui::TextWrapped("%s", STR_C("The model in the game differs from the file: the changes show once the game loads the model again")); + } + if (false == m_message.empty()) + { + ImGui::TextWrapped("%s", m_message.c_str()); + } + render_guide(); +} + +void eu07m_model_panel::render_guide() const +{ + if (false == ImGui::CollapsingHeader(STR_C("How it works"))) + { + return; + } + ImGui::Indent(); + ImGui::TextWrapped("%s", STR_C("1. Pick the model: click it in the scenery, or pick a vehicle in the list on the left.")); + ImGui::TextWrapped("%s", STR_C("2. Click a part of the model in the view. Its settings come up in the inspector.")); + ImGui::TextWrapped("%s", STR_C("3. Drag the arrows in the view to move the part picked, or the rings to turn it: Move and Turn are in the toolbar.")); + ImGui::TextWrapped("%s", STR_C("4. Ctrl+Z takes a change back. Nothing goes into the file until Save the changes.")); + ImGui::Unindent(); +} + +void eu07m_model_panel::render_lights_page() +{ + ImGui::TextWrapped("%s", STR_C("The light sources of the model. Click one to change it in the inspector; its round mark in the view does the same.")); + if (m_placing) + { + ImGui::TextColored(ImVec4(1.f, 0.85f, 0.3f, 1.f), "%s", STR_C("Click the model where the light is to be. Esc gives it up.")); + if (ImGui::Button(STR_C("Give it up"))) + { + m_placing.reset(); + } + } + else + { + ImGui::BeginDisabled(m_submodels.empty()); + if (ImGui::Button(STR_C("+ Add a bulb"))) + { + m_placing = false; + } + if (ImGui::IsItemHovered()) + { + ImGui::SetTooltip("%s", STR_C("A light which shines all around, as a bulb; then a click on the model puts it there")); + } + ImGui::SameLine(); + if (ImGui::Button(STR_C("+ Add a spot"))) + { + m_placing = true; + } + if (ImGui::IsItemHovered()) + { + ImGui::SetTooltip("%s", STR_C("A light which shines one way, as a headlamp; then a click on the model puts it there, shining towards the camera")); + } + ImGui::EndDisabled(); + } + ImGui::Checkbox(STR_C("Marks of the lights in the view"), &m_marks); + ImGui::SeparatorText(STR_C("Lights of the model")); + auto any{false}; + for (std::uint32_t idx = 0; idx < m_model.components.size(); ++idx) + { + auto const &record{m_model.components[idx]}; + if ((record.type != eu07m::component::light) || (record.kind != eu07m::target_kind::node) || (record.target >= m_model.nodes.size()) || + (std::size_t{record.data_offset} + sizeof(payload::light) > m_model.component_data.size())) + { + continue; + } + any = true; + payload::light light; + std::memcpy(&light, m_model.component_data.data() + record.data_offset, sizeof(light)); + ImGui::PushID(static_cast(idx)); + ImGui::ColorButton("##colour", ImVec4(light.color[0], light.color[1], light.color[2], 1.f), ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoPicker); + ImGui::SameLine(); + auto const kind{light.kind == payload::light_kind::spot ? STR_C("spot") : STR_C("bulb")}; + auto const label{std::format("{} ({})", part_name(record.target), kind)}; + if (ImGui::Selectable(label.c_str(), m_selected == static_cast(record.target), ImGuiSelectableFlags_AllowDoubleClick)) + { + select(record.target); + if (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) + { + fly_to(record.target); + } + } + ImGui::PopID(); + } + if (false == any) + { + ImGui::TextDisabled("%s", STR_C("The model has no light sources yet.")); + } +} + +void eu07m_model_panel::render_parts_page() const +{ + if ((m_target.vehicle == nullptr) || (m_target.part != 0)) + { + ImGui::TextWrapped("%s", STR_C("The parts of a vehicle are held on its body: pick the body on the left.")); + return; + } + auto &vehicle{*m_target.vehicle}; + ImGui::TextWrapped("%s", STR_C("The vehicle keeps a part as set here until As the vehicle has it is chosen. Nothing of it goes into the file.")); + if (vehicle.pantograph_count() > 0) + { + ImGui::SeparatorText(STR_C("Pantographs")); + if (ImGui::BeginTable("##pantographs", 2, ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_RowBg)) + { + for (int idx = 0; idx < vehicle.pantograph_count(); ++idx) + { + pantograph_hold_row(vehicle, idx); + } + ImGui::EndTable(); + } + } + part_group(vehicle, STR_C("Front lights"), true, [](std::string_view const Name) { return is_lamp(Name) && is_front(Name); }); + part_group(vehicle, STR_C("Rear lights"), true, [](std::string_view const Name) { return is_lamp(Name) && (false == is_front(Name)); }); + part_group(vehicle, STR_C("Couplers and hoses"), false, [](std::string_view const Name) { return false == is_lamp(Name); }); +} + +void eu07m_model_panel::render_elements_page() +{ + ImGui::TextWrapped("%s", STR_C("All the parts of the model, as they hang one on another. A click picks one, a double click takes the camera to it.")); + std::array buffer{}; + std::memcpy(buffer.data(), m_filter.data(), std::min(m_filter.size(), buffer.size() - 1)); + ImGui::SetNextItemWidth(-1.f); + if (ImGui::InputTextWithHint("##filter", STR_C("Look for a part by its name"), buffer.data(), buffer.size())) + { + m_filter = buffer.data(); + } + if (false == ImGui::BeginChild("##eu07mtree", ImVec2(0.f, 0.f), ImGuiChildFlags_Borders)) + { + ImGui::EndChild(); + return; + } + if (m_filter.empty()) + { + for (std::uint32_t idx = 0; idx < m_model.nodes.size(); idx = m_model.nodes[idx].subtree_end) + { + render_tree_node(idx); + } + ImGui::EndChild(); + return; + } + // what is looked for: the parts of the name, as a list + auto const wanted_text{lowered(m_filter)}; + for (std::uint32_t idx = 0; idx < m_model.nodes.size(); ++idx) + { + auto const name{part_name(idx)}; + if (lowered(name).find(wanted_text) == std::string::npos) + { + continue; + } + auto const label{name + "##found" + std::to_string(idx)}; + if (ImGui::Selectable(label.c_str(), m_selected == static_cast(idx), ImGuiSelectableFlags_AllowDoubleClick)) + { + select(idx); + if (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) + { + fly_to(idx); + } + } + } + ImGui::EndChild(); +} + +void eu07m_model_panel::render_tree_node(std::uint32_t const Index) +{ + auto const &node{m_model.nodes[Index]}; + auto const components{node_components(m_model, Index)}; + auto const label{node_label(m_model, Index, components) + "##node" + std::to_string(Index)}; + auto flags{ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_SpanAvailWidth}; + if (node.subtree_end == Index + 1) + { + flags |= ImGuiTreeNodeFlags_Leaf; + } + if (m_model.nodes.size() <= small_model) + { + flags |= ImGuiTreeNodeFlags_DefaultOpen; + } + if (m_selected == static_cast(Index)) + { + flags |= ImGuiTreeNodeFlags_Selected; + // picked in the view: the tree opens down to it + if (m_scrolltoselected) + { + ImGui::SetScrollHereY(); + m_scrolltoselected = false; + } + } + if (m_selected > static_cast(Index) && m_selected < static_cast(node.subtree_end) && m_scrolltoselected) + { + ImGui::SetNextItemOpen(true); + } + auto const opened{ImGui::TreeNodeEx(label.c_str(), flags)}; + if (ImGui::IsItemClicked(ImGuiMouseButton_Left) && (false == ImGui::IsItemToggledOpen())) + { + select(Index); + } + if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) + { + fly_to(Index); + } + if (false == opened) + { + return; + } + for (auto child = Index + 1; child < node.subtree_end; child = m_model.nodes[child].subtree_end) + { + render_tree_node(child); + } + ImGui::TreePop(); +} + +void eu07m_model_panel::render_animations_page() +{ + auto *instance{m_target.instance}; + if (instance == nullptr) + { + ImGui::TextWrapped("%s", STR_C("The animations are tried on a model of the scenery.")); + return; + } + ImGui::TextWrapped("%s", STR_C("The animations of the model, tried on it in the view. Looped and Plays on its own go into the file.")); + render_clips(*instance); + render_channels(*instance); +} + +void eu07m_model_panel::render_selection() +{ + if (m_path.empty()) + { + ImGui::TextWrapped("%s", m_problem.empty() ? STR_C("Pick a model first: click it in the view, or pick a vehicle in the list on the left.") : m_problem.c_str()); + return; + } + if ((m_selected < 0) || (m_selected >= static_cast(m_model.nodes.size()))) + { + ImGui::TextWrapped("%s", STR_C("Click a part of the model in the view, or pick one in the tool options, to change it here.")); + return; + } + auto const index{static_cast(m_selected)}; + auto const light{light_of(index)}; + ImGui::PushItemWidth(-ImGui::GetFontSize() * label_width); + ImGui::SeparatorText(part_name(index).c_str()); + if (light) + { + ImGui::TextDisabled("%s", STR_C("A light source")); + } + else + { + ImGui::TextDisabled("%s", m_model.nodes[index].mesh >= 0 ? STR_C("A part of the model") : STR_C("A point of the model, with nothing to see")); + } + if (ImGui::Button(STR_C("Show it in the view"))) + { + fly_to(index); + } + // the part of the vehicle it is in + auto const *target{submodel(index)}; + if ((m_target.vehicle != nullptr) && (m_target.part == 0) && (target != nullptr)) + { + auto const part{m_target.vehicle->part_of(target)}; + auto const pantograph{m_target.vehicle->pantograph_of(target)}; + if (((part < TDynamicObject::held_part_total) || (pantograph >= 0)) && ImGui::BeginTable("##hold", 2, ImGuiTableFlags_SizingFixedFit)) + { + if (part < TDynamicObject::held_part_total) + { + part_hold_row(*m_target.vehicle, part); + } + if (pantograph >= 0) + { + pantograph_hold_row(*m_target.vehicle, pantograph); + } + ImGui::EndTable(); + } + } + if (light) + { + render_light_settings(*light); + } + render_place(index); + if (render_remove(index, light.has_value())) + { + ImGui::PopItemWidth(); + return; + } + render_advanced(index); + ImGui::PopItemWidth(); +} + +bool eu07m_model_panel::render_remove(std::uint32_t const Index, bool const Light) +{ + auto const *target{submodel(Index)}; + auto const removable{(target != nullptr) && (target->Parent != nullptr) && eu07m::node_removable(m_model, Index)}; + ImGui::Separator(); + ImGui::BeginDisabled(false == removable); + auto const clicked{ImGui::Button(Light ? STR_C("Remove this light (Del)") : STR_C("Remove this part (Del)"))}; + ImGui::EndDisabled(); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + { + ImGui::SetTooltip("%s", removable ? STR_C("Takes it out of the model, with what it draws; Ctrl+Z brings it back") + : STR_C("This part can't be taken out: it has parts under it, or something else in the model points at it (an animation, a light slot, a skin)")); + } + return clicked && remove_selected(); +} + +void eu07m_model_panel::render_light_settings(std::uint32_t const Component) +{ + auto const &record{m_model.components[Component]}; + if ((record.data_size < sizeof(payload::light)) || (std::size_t{record.data_offset} + sizeof(payload::light) > m_model.component_data.size())) + { + return; + } + payload::light light; + std::memcpy(&light, m_model.component_data.data() + record.data_offset, sizeof(light)); + auto changes{false}; + ImGui::SeparatorText(STR_C("Light")); + auto const spot{light.kind == payload::light_kind::spot}; + std::array const kinds{STR_C("Bulb: shines all around"), STR_C("Spot: shines one way")}; + if (auto const clicked{choice_buttons("##kind", spot ? 1 : 0, kinds)}; clicked && ((*clicked == 1) != spot)) + { + set_light_kind(light, *clicked == 1 ? payload::light_kind::spot : payload::light_kind::point); + changes = true; + } + changes |= ImGui::ColorEdit3(STR_C("Colour"), light.color.data()); + for (auto const &preset : colour_presets) + { + ImGui::PushID(preset.name); + if (ImGui::ColorButton(STR_C(preset.name), ImVec4(preset.colour[0], preset.colour[1], preset.colour[2], 1.f))) + { + std::ranges::copy(preset.colour, light.color.begin()); + changes = true; + } + ImGui::PopID(); + ImGui::SameLine(0.f, ImGui::GetStyle().ItemInnerSpacing.x); + } + ImGui::NewLine(); + changes |= ImGui::SliderFloat(STR_C("Brightness"), &light.hotspot_power, 0.f, 10.f, "%.2f"); + if (ImGui::IsItemHovered()) + { + ImGui::SetTooltip("%s", STR_C("How strongly it lights what is around it. Ctrl+click types a value")); + } + changes |= ImGui::SliderFloat(STR_C("Glowing spot, m"), &light.radius, 0.f, 1.f, "%.2f"); + if (ImGui::IsItemHovered()) + { + ImGui::SetTooltip("%s", STR_C("The size of the glowing ball seen where the light is; 0 shows none")); + } + if (light.kind == payload::light_kind::spot) + { + changes |= edit_beam(light); + } + auto shadows{(light.flags & payload::light_flags::no_shadows) == 0}; + if (ImGui::Checkbox(STR_C("Casts shadows"), &shadows)) + { + // the box says it casts them, the flag that it doesn't + light.flags ^= payload::light_flags::no_shadows; + changes = true; + } + changes |= edit_flag(STR_C("Soft edge"), light.flags, payload::light_flags::soft_falloff); + changes |= edit_flag(STR_C("Lights this model too"), light.flags, payload::light_flags::shade_self); + if (false == changes) + { + return; + } + std::memcpy(m_model.component_data.data() + record.data_offset, &light, sizeof(light)); + changed(); + show_change(Component); +} + +void eu07m_model_panel::render_place(std::uint32_t const Index) +{ + auto &node{m_model.nodes[Index]}; + ImGui::SeparatorText(STR_C("Place")); + if ((node.flags & eu07m::node_flags::matrix) != 0) + { + ImGui::TextDisabled("%s", STR_C("This part is placed in a way this window doesn't change")); + } + else + { + ImGui::TextWrapped("%s", STR_C("Drag the arrows in the view to move it, or the rings to turn it.")); + std::array const modes{STR_C("Move"), STR_C("Turn")}; + if (auto const clicked{choice_buttons("##gizmo", m_gizmo == gizmo::turn ? 1 : 0, modes)}) + { + set_turning(*clicked == 1); + } + if (ImGui::TreeNode(STR_C("Exact values"))) + { + if (edit_place(node)) + { + moved(Index); + } + ImGui::TreePop(); + } + } + ImGui::SeparatorText(STR_C("Seen from")); + if (edit_range(node)) + { + changed(); + if (auto *target{submodel(Index)}; target != nullptr) + { + m_source->SetEditorRange(*target, node.range_min_sq, node.range_max_sq); + } + } +} + +void eu07m_model_panel::render_advanced(std::uint32_t const Index) +{ + if (false == ImGui::CollapsingHeader(STR_C("Advanced: the data of the file"))) + { + return; + } + ImGui::TextDisabled("%s", STR_C("For those who know the EU07M format")); + if (ImGui::Button(STR_C("Add a light to this part"))) + { + add_light(Index, glm::vec3{0.f}, glm::quat{1.f, 0.f, 0.f, 0.f}, false); + } + for (auto const component : node_components(m_model, Index)) + { + render_component(component); + } +} + +void eu07m_model_panel::render_component(std::uint32_t const Index) +{ + auto const &record{m_model.components[Index]}; + auto const label{std::format("{} ({}) #{}##component{}", component_name(record.type), fourcc_text(record.type), Index, Index)}; + if (false == ImGui::TreeNode(label.c_str())) + { + return; + } + ImGui::PushID(static_cast(Index)); + if (edit_component(m_model, Index)) + { + changed(); + show_change(Index); + } + ImGui::PopID(); + ImGui::TreePop(); +} + +void eu07m_model_panel::choose_tool(tool const Tool) +{ + m_tool = Tool; + m_placing.reset(); +} + +bool eu07m_model_panel::has_animations() const +{ + auto const *instance{m_target.instance}; + return (instance != nullptr) && ((false == m_model.clips.empty()) || ((instance->pModel != nullptr) && (false == instance->pModel->channels().empty()))); +} + +bool eu07m_model_panel::editable(scene::basic_node const *Node) const +{ + auto const *instance{dynamic_cast(Node)}; + return Global.modelformat_eu07m && (instance != nullptr) && (instance->pModel != nullptr) && (false == FileCased(instance->pModel->NameGet() + ".ng3d").empty()); +} + +bool eu07m_model_panel::pick_vehicle(std::string_view const Name, int const Part) +{ + auto const &vehicles{simulation::Vehicles.sequence()}; + auto const wanted_name{lowered(Name)}; + auto const found{std::ranges::find_if(vehicles, [&wanted_name](TDynamicObject const *Vehicle) { return lowered(Vehicle->name()) == wanted_name; })}; + if (found == vehicles.end()) + { + return false; + } + m_pickedvehicle = *found; + m_part = Part; + if (Part == 1) + { + return (enter_cab != nullptr) && enter_cab(**found); + } + fly_to_vehicle(**found); + return true; +} + +bool eu07m_model_panel::save_model() +{ + if (m_path.empty()) + { + return false; + } + save(); + return false == m_dirty; +} + +bool eu07m_model_panel::set_brightness(float const Brightness) +{ + auto const light{m_selected >= 0 ? light_of(static_cast(m_selected)) : std::nullopt}; + if (false == light.has_value()) + { + return false; + } + auto const &record{m_model.components[*light]}; + if (std::size_t{record.data_offset} + sizeof(payload::light) > m_model.component_data.size()) + { + return false; + } + payload::light value; + std::memcpy(&value, m_model.component_data.data() + record.data_offset, sizeof(value)); + value.hotspot_power = Brightness; + std::memcpy(m_model.component_data.data() + record.data_offset, &value, sizeof(value)); + changed(); + show_change(*light); + return true; +} + +bool eu07m_model_panel::select_node(std::string_view const Name) +{ + auto const nodes{eu07m::find_nodes(m_model, Name)}; + if (nodes.empty()) + { + return false; + } + select(nodes.front()); + m_scrolltoselected = true; + return true; +} + +bool eu07m_model_panel::add_test_light(bool const Spot) +{ + // in the middle of the geometry of the part picked, as a click there would put it + auto const where{placement()}; + // the first part when none is picked + auto const part{m_model.nodes.empty() ? std::nullopt : std::optional{static_cast(std::max(m_selected, 0))}}; + auto const *target{part ? submodel(*part) : nullptr}; + if ((false == where.has_value()) || (target == nullptr)) + { + return false; + } + auto const &bounds{m_boxes[*part]}; + auto const middle{bounds ? glm::dvec3{(bounds->first + bounds->second) * 0.5f} : glm::dvec3{0.0}}; + auto const count{m_model.nodes.size()}; + m_placing = Spot; + place_light(point_of(*where * model_space(*target), middle), part); + return m_model.nodes.size() > count; +} + +void eu07m_model_panel::select(std::uint32_t const Node) +{ + m_selected = Node; +} + +TSubModel *eu07m_model_panel::submodel(std::uint32_t const Node) const +{ + return Node < m_submodels.size() ? m_submodels[Node] : nullptr; +} + +std::optional eu07m_model_panel::placement() const +{ + if (m_target.vehicle != nullptr) + { + return glm::translate(glm::dmat4{1.0}, m_target.vehicle->GetPosition()) * m_target.vehicle->mMatrix; + } + auto const *instance{m_target.instance}; + if (instance == nullptr) + { + return std::nullopt; + } + // turned about y, then x, then z, and scaled, the way the instance is drawn + auto const angles{glm::radians(glm::dvec3{instance->Angles()})}; + auto matrix{glm::translate(glm::dmat4{1.0}, instance->location())}; + matrix = glm::rotate(matrix, angles.y, glm::dvec3{0.0, 1.0, 0.0}); + matrix = glm::rotate(matrix, angles.x, glm::dvec3{1.0, 0.0, 0.0}); + matrix = glm::rotate(matrix, angles.z, glm::dvec3{0.0, 0.0, 1.0}); + return glm::scale(matrix, glm::dvec3{instance->Scale()}); +} + +std::optional eu07m_model_panel::node_at(glm::dvec3 const &Point) const +{ + auto const where{placement()}; + if (false == where.has_value()) + { + return std::nullopt; + } + std::optional best; + auto bestvolume{std::numeric_limits::max()}; + for (std::uint32_t idx = 0; (idx < m_boxes.size()) && (idx < m_submodels.size()); ++idx) + { + auto const &bounds{m_boxes[idx]}; + auto const *target{m_submodels[idx]}; + // a part hidden now, such as a lamp off, isn't what was clicked + if ((false == bounds.has_value()) || (target == nullptr) || (target->iVisible == 0)) + { + continue; + } + if (false == inside(*bounds, point_of(glm::inverse(*where * model_space(*target)), Point), pick_margin)) + { + continue; + } + auto const size{glm::dvec3{bounds->second - bounds->first} + 2.0 * pick_margin}; + if (auto const volume{size.x * size.y * size.z}; volume < bestvolume) + { + best = idx; + bestvolume = volume; + } + } + return best; +} + +std::optional eu07m_model_panel::light_of(std::uint32_t const Node) const +{ + for (std::uint32_t idx = 0; idx < m_model.components.size(); ++idx) + { + auto const &record{m_model.components[idx]}; + if ((record.type == eu07m::component::light) && (record.kind == eu07m::target_kind::node) && (record.target == Node)) + { + return idx; + } + } + return std::nullopt; +} + +std::string eu07m_model_panel::part_name(std::uint32_t const Node) const +{ + auto const name{m_model.string(m_model.nodes[Node].name)}; + std::string own{name.empty() ? std::string{STR_C("(no name)")} : std::string{name}}; + auto const *target{submodel(Node)}; + if ((m_target.vehicle == nullptr) || (m_target.part != 0) || (target == nullptr)) + { + return own; + } + if (auto const part{m_target.vehicle->part_of(target)}; part < TDynamicObject::held_part_total) + { + return std::format("{} ({})", part_text(TDynamicObject::held_part_name(part)), own); + } + if (auto const pantograph{m_target.vehicle->pantograph_of(target)}; pantograph >= 0) + { + auto const number{pantograph + 1}; + return std::format("{} ({})", std::vformat(STR("Pantograph {}"), std::make_format_args(number)), own); + } + return own; +} + +void eu07m_model_panel::render_view() +{ + auto const where{placement()}; + if ((false == where.has_value()) || m_submodels.empty()) + { + return; + } + screen_projection const projection; + auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + auto const clicked{ImGui::IsMouseClicked(ImGuiMouseButton_Left) && (false == ImGui::GetIO().WantCaptureMouse)}; + if (clicked) + { + m_tookpress = false; + } + // what a click is to do now, by the cursor + if (m_placing && (false == ImGui::GetIO().WantCaptureMouse)) + { + auto const mouse{ImGui::GetMousePos()}; + ImGui::GetForegroundDrawList()->AddText(ImVec2(mouse.x + 18.f, mouse.y + 4.f), IM_COL32(255, 220, 90, 255), STR_C("Click the model where the light is to be")); + } + if (m_marks) + { + render_marks(*where, clicked && (false == m_placing.has_value())); + } + // the part picked: its frame and its axes, and the gizmo to move it + auto const *target{m_selected >= 0 ? submodel(static_cast(m_selected)) : nullptr}; + if (target == nullptr) + { + return; + } + auto const space{*where * model_space(*target)}; + if (auto const &bounds{m_boxes[static_cast(m_selected)]}; bounds.has_value()) + { + draw_box(drawlist, projection, space, *bounds, overlay_color::selected); + } + draw_axes(drawlist, projection, space, 0.3); + render_gizmo(*where, GfxRenderer->Camera_Position()); +} + +void eu07m_model_panel::render_marks(glm::dmat4 const &Placement, bool const Clicked) +{ + screen_projection const projection; + auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + auto const mouse{ImGui::GetMousePos()}; + for (auto const &record : m_model.components) + { + if ((record.type != eu07m::component::light) || (record.kind != eu07m::target_kind::node) || (submodel(record.target) == nullptr) || + (std::size_t{record.data_offset} + sizeof(payload::light) > m_model.component_data.size())) + { + continue; + } + payload::light light; + std::memcpy(&light, m_model.component_data.data() + record.data_offset, sizeof(light)); + auto const space{Placement * model_space(*submodel(record.target))}; + ImVec2 centre; + if (false == projection.project(point_of(space, glm::dvec3{0.0}), centre)) + { + continue; + } + if (light.kind == payload::light_kind::spot) + { + // the axis of a spot is the -z of its node + projection.line(drawlist, point_of(space, glm::dvec3{0.0}), point_of(space, glm::dvec3{0.0, 0.0, -0.6}), light_colour(light, 255), 2.f); + } + auto const picked{m_selected == static_cast(record.target)}; + drawlist->AddCircleFilled(centre, mark_radius, light_colour(light, 220)); + drawlist->AddCircle(centre, mark_radius + 1.f, picked ? overlay_color::selected : IM_COL32(0, 0, 0, 200), 0, picked ? 3.f : 1.5f); + auto const dx{mouse.x - centre.x}; + auto const dy{mouse.y - centre.y}; + if (Clicked && (dx * dx + dy * dy <= (mark_radius + 3.f) * (mark_radius + 3.f))) + { + select(record.target); + m_scrolltoselected = true; + m_tookpress = true; + } + } +} + +void eu07m_model_panel::render_gizmo(glm::dmat4 const &Placement, glm::dvec3 const &Camera) +{ + auto const index{static_cast(m_selected)}; + auto *target{submodel(index)}; + if (m_placing || moves_whole() || (target == nullptr) || ((m_model.nodes[index].flags & eu07m::node_flags::matrix) != 0)) + { + return; + } + m_gizmoshown = true; + ImGuizmo::BeginFrame(); + ImGuizmo::SetOrthographic(Global.EditorOrtho); + ImGuiIO const &io{ImGui::GetIO()}; + ImGuizmo::SetRect(0.f, 0.f, io.DisplaySize.x, io.DisplaySize.y); + auto const view{GfxRenderer->Camera_View_Matrix()}; + auto const projection{editor_mode::projection_matrix(io.DisplaySize.y > 0.f ? io.DisplaySize.x / io.DisplaySize.y : 1.f)}; + // the model in the space of the camera, its position taken off, as the gizmo of the editor works + auto const model{glm::translate(glm::dmat4{1.0}, -Camera) * Placement}; + auto matrix{glm::mat4{model * model_space(*target)}}; + auto const operation{m_gizmo == gizmo::turn ? ImGuizmo::ROTATE : ImGuizmo::TRANSLATE}; + ImGuizmo::Manipulate(glm::value_ptr(view), glm::value_ptr(projection), operation, ImGuizmo::LOCAL, glm::value_ptr(matrix)); + if (ImGui::IsMouseClicked(ImGuiMouseButton_Left) && ImGuizmo::IsOver()) + { + m_tookpress = true; + } + if (false == ImGuizmo::IsUsing()) + { + return; + } + // back to the space of the parent of the node + auto const parent{target->Parent != nullptr ? model_space(*target->Parent) : glm::dmat4{1.0}}; + auto const local{glm::mat4{glm::inverse(model * parent) * glm::dmat4{matrix}}}; + if (eu07m::set_transform(m_model.nodes[index], local, 1e-3f)) + { + moved(index); + } +} + +void eu07m_model_panel::moved(std::uint32_t const Node) +{ + m_model.nodes[Node].flags &= ~eu07m::node_flags::no_transform; + changed(); + if (auto *target{submodel(Node)}; target != nullptr) + { + m_source->SetEditorTransform(*target, eu07m::local_transform(m_model, Node)); + } +} + +void eu07m_model_panel::show_change(std::uint32_t const Index) const +{ + auto const &record{m_model.components[Index]}; + if ((m_source == nullptr) || (record.type != eu07m::component::light) || (record.kind != eu07m::target_kind::node) || (record.data_size < sizeof(payload::light)) || + (std::size_t{record.data_offset} + sizeof(payload::light) > m_model.component_data.size())) + { + return; + } + auto *target{submodel(record.target)}; + if ((target == nullptr) || (target->eType != TP_FREESPOTLIGHT)) + { + return; + } + payload::light light; + std::memcpy(&light, m_model.component_data.data() + record.data_offset, sizeof(light)); + TModel3d::ApplyEU07MLight(*target, light); + m_source->state_changed(); +} + +void eu07m_model_panel::changed() +{ + m_dirty = true; + // one change for a press, a drag or a typing: the model as it was before it + if (m_changing) + { + return; + } + m_changing = true; + push_change(m_before); +} + +eu07m_model_panel::snapshot eu07m_model_panel::take(bool const Whole) const +{ + snapshot result; + result.nodes = m_model.nodes; + result.components = m_model.components; + result.component_data = m_model.component_data; + result.clips = m_model.clips; + if (Whole) + { + result.whole = m_model; + } + return result; +} + +void eu07m_model_panel::restore(snapshot const &Snapshot) +{ + auto const before{m_model.nodes}; + if (Snapshot.whole) + { + m_model = *Snapshot.whole; + } + else + { + m_model.nodes = Snapshot.nodes; + m_model.components = Snapshot.components; + m_model.component_data = Snapshot.component_data; + m_model.clips = Snapshot.clips; + } + // the places and the ranges changed shown on the model the game has; a change of the tree changes nothing else + if ((before.size() == m_model.nodes.size()) && (m_source != nullptr)) + { + for (std::uint32_t idx = 0; idx < before.size(); ++idx) + { + auto *target{submodel(idx)}; + if ((target == nullptr) || same_place(before[idx], m_model.nodes[idx])) + { + continue; + } + if ((m_model.nodes[idx].flags & eu07m::node_flags::matrix) == 0) + { + m_source->SetEditorTransform(*target, eu07m::local_transform(m_model, idx)); + } + m_source->SetEditorRange(*target, m_model.nodes[idx].range_min_sq, m_model.nodes[idx].range_max_sq); + } + } +} + +void eu07m_model_panel::apply_tree(tree_change const &Change, bool const Forward) +{ + if ((Change.what == tree_change::kind::none) || (Change.submodel == nullptr) || (m_source == nullptr) || m_submodels.empty()) + { + return; + } + // a light added is taken out again when the change is taken back, one taken out is put back + if ((Change.what == tree_change::kind::added) == Forward) + { + if ((Change.parent == nullptr) || (Change.index > m_submodels.size())) + { + return; + } + m_source->LinkEditorSubmodel(*Change.submodel, *Change.parent, Change.previous); + m_submodels.insert(m_submodels.begin() + Change.index, Change.submodel); + m_boxes.insert(m_boxes.begin() + Change.index, node_box(m_model, Change.index)); + // the part back is picked again, as it was when it was taken out + m_pick_after = Change.index; + return; + } + if (Change.index >= m_submodels.size()) + { + return; + } + m_source->UnlinkEditorSubmodel(*Change.submodel); + m_submodels.erase(m_submodels.begin() + Change.index); + m_boxes.erase(m_boxes.begin() + Change.index); + if (m_selected == static_cast(Change.index)) + { + m_selected = -1; + } +} + +void eu07m_model_panel::push_change(snapshot Snapshot) +{ + m_undo.push_back(std::move(Snapshot)); + if (m_undo.size() > undo_depth) + { + m_undo.erase(m_undo.begin()); + } + m_redo.clear(); + m_dirty = true; +} + +bool eu07m_model_panel::undo() +{ + if (m_undo.empty()) + { + return false; + } + auto entry{std::move(m_undo.back())}; + m_undo.pop_back(); + auto again{take(entry.whole.has_value())}; + again.change = entry.change; + restore(entry); + apply_tree(entry.change, false); + m_redo.push_back(std::move(again)); + settled(); + return true; +} + +bool eu07m_model_panel::redo() +{ + if (m_redo.empty()) + { + return false; + } + auto entry{std::move(m_redo.back())}; + m_redo.pop_back(); + auto back{take(entry.whole.has_value())}; + back.change = entry.change; + restore(entry); + apply_tree(entry.change, true); + m_undo.push_back(std::move(back)); + settled(); + return true; +} + +void eu07m_model_panel::settled() +{ + m_dirty = true; + m_message.clear(); + m_placing.reset(); + m_before = take(false); + m_changing = false; + // the lights as they are now + for (std::uint32_t idx = 0; idx < m_model.components.size(); ++idx) + { + show_change(idx); + } + if (m_selected >= static_cast(m_model.nodes.size())) + { + m_selected = -1; + } + if (auto const part{std::exchange(m_pick_after, std::nullopt)}; part && (*part < m_model.nodes.size())) + { + select(*part); + m_scrolltoselected = true; + } +} + +void eu07m_model_panel::add_light(std::uint32_t const Parent, glm::vec3 const &Position, glm::quat const &Rotation, bool const Spot) +{ + auto *parent{submodel(Parent)}; + if ((parent == nullptr) || (m_source == nullptr)) + { + return; + } + auto before{take(true)}; + // a name the model doesn't have yet + std::string name; + for (int number = 1; name.empty() || (false == eu07m::find_nodes(m_model, name).empty()); ++number) + { + name = std::format("light_{}", number); + } + eu07m::node_record node; + node.name = m_model.intern(name); + node.legacy_flags = light_node_flags; + node.translation = {Position.x, Position.y, Position.z}; + node.rotation = {Rotation.x, Rotation.y, Rotation.z, Rotation.w}; + auto const index{eu07m::insert_node(m_model, static_cast(Parent), node)}; + payload::light light; + light.color = {1.f, 0.9f, 0.7f, 1.f}; + // without a cone yet: a spot gets the one it's given to start with + light.cos_falloff = -1.f; + set_light_kind(light, Spot ? payload::light_kind::spot : payload::light_kind::point); + std::vector data(sizeof(light)); + std::memcpy(data.data(), &light, sizeof(light)); + eu07m::add_component(m_model, eu07m::component::light, eu07m::target_kind::node, index, data); + // on the model the game has, the last child of the parent as in the file + auto *previous{parent->Child}; + while ((previous != nullptr) && (previous->Next != nullptr)) + { + previous = previous->Next; + } + auto &added{m_source->AddEditorLight(*parent, name, eu07m::local_transform(m_model, index), light_node_flags, light)}; + m_submodels.insert(m_submodels.begin() + index, &added); + m_boxes.insert(m_boxes.begin() + index, std::nullopt); + before.change = {tree_change::kind::added, index, &added, parent, previous}; + push_change(std::move(before)); + m_before = take(false); + // the new light is picked, to be moved with the gizmo + select(index); + m_scrolltoselected = true; + m_message = std::vformat(STR("Added the light {}. Drag the arrows in the view to move it"), std::make_format_args(name)); +} + +void eu07m_model_panel::place_light(glm::dvec3 const &Point, std::optional const Part) +{ + auto const spot{m_placing.value_or(false)}; + m_placing.reset(); + // on the part clicked; a light clicked gets one beside it rather than under it + auto parent{Part.value_or(0u)}; + if (light_of(parent) && (m_model.nodes[parent].parent >= 0)) + { + parent = static_cast(m_model.nodes[parent].parent); + } + auto const *target{submodel(parent)}; + auto const where{placement()}; + if ((target == nullptr) || (false == where.has_value())) + { + return; + } + auto const inverse{glm::inverse(*where * model_space(*target))}; + glm::vec3 const position{point_of(inverse, Point)}; + // a spot shines back where it was clicked from + auto const towards{glm::dvec3{inverse * glm::dvec4{glm::dvec3{Global.pCamera.Pos} - Point, 0.0}}}; + auto const rotation{glm::length(towards) > 1e-6 ? aim(glm::normalize(glm::vec3{towards})) : glm::quat{1.f, 0.f, 0.f, 0.f}}; + add_light(parent, position, rotation, spot); +} + +bool eu07m_model_panel::pick(scene::basic_node const *Picked) +{ + if ((false == m_active) || m_submodels.empty() || (false == placement().has_value()) || (moves_whole() && (false == m_placing.has_value()))) + { + return false; + } + // a vehicle isn't a node of the scenery: a click on it hits none + auto const ours{m_target.instance != nullptr ? Picked == m_target.instance : Picked == nullptr}; + if (false == ours) + { + return false; + } + if (false == GfxRenderer->Mouse_Hit()) + { + return m_target.instance != nullptr; + } + auto const point{glm::dvec3{Global.pCamera.Pos} + GfxRenderer->Mouse_Position()}; + auto const part{node_at(point)}; + if ((m_target.vehicle != nullptr) && (false == part.has_value())) + { + return false; + } + if (m_placing) + { + place_light(point, part); + return true; + } + if (part) + { + select(*part); + m_scrolltoselected = true; + } + return true; +} + +bool eu07m_model_panel::remove_selected() +{ + if ((false == m_active) || (m_selected < 0) || (m_selected >= static_cast(m_model.nodes.size()))) + { + return false; + } + auto const index{static_cast(m_selected)}; + auto *target{submodel(index)}; + if ((target == nullptr) || (target->Parent == nullptr) || (false == eu07m::node_removable(m_model, index))) + { + return false; + } + auto before{take(true)}; + auto *parent{target->Parent}; + auto const name{part_name(index)}; + auto const light{light_of(index).has_value()}; + if (false == eu07m::remove_node(m_model, index)) + { + return false; + } + auto *previous{m_source->UnlinkEditorSubmodel(*target)}; + m_submodels.erase(m_submodels.begin() + index); + m_boxes.erase(m_boxes.begin() + index); + before.change = {tree_change::kind::removed, index, target, parent, previous}; + push_change(std::move(before)); + m_before = take(false); + m_selected = -1; + m_message = light ? std::vformat(STR("Removed the light {}. Ctrl+Z brings it back"), std::make_format_args(name)) + : std::vformat(STR("Removed {}. Ctrl+Z brings it back"), std::make_format_args(name)); + return true; +} + +void eu07m_model_panel::fly_to(std::uint32_t const Node) const +{ + auto const where{placement()}; + auto const *target{submodel(Node)}; + if ((focus == nullptr) || (target == nullptr) || (false == where.has_value())) + { + return; + } + // the node in the model, or the middle of its geometry when it has no offset of its own + focus(point_of(*where, glm::dvec3{target->offset(0.01f)}), node_focus_radius); +} + +void eu07m_model_panel::fly_to_vehicle(TDynamicObject const &Vehicle) const +{ + if (focus != nullptr) + { + focus(Vehicle.GetPosition(), std::max(5.0, Vehicle.GetLength() * vehicle_focus)); + } +} + +void eu07m_model_panel::render_clips(TAnimModel &Instance) +{ + if (m_model.clips.empty()) + { + return; + } + ImGui::SeparatorText(STR_C("Animation clips")); + for (std::size_t idx = 0; idx < m_model.clips.size(); ++idx) + { + auto &clip{m_model.clips[idx]}; + ImGui::PushID(static_cast(idx)); + auto const name{std::string{m_model.string(clip.name)}}; + ImGui::TextUnformatted(name.c_str()); + auto looped{(clip.flags & eu07m::clip_flags::loop) != 0}; + auto autoplay{(clip.flags & eu07m::clip_flags::autoplay) != 0}; + if (ImGui::Checkbox(STR_C("Looped"), &looped) | ImGui::Checkbox(STR_C("Plays on its own"), &autoplay)) + { + clip.flags = (looped ? eu07m::clip_flags::loop : 0u) | (autoplay ? eu07m::clip_flags::autoplay : 0u); + changed(); + } + // the editor stops the time: the clip is held at the time picked + if (ImGui::SliderFloat(STR_C("Time, s"), &m_cliptimes[idx], 0.f, std::max(clip.duration, 0.001f), "%.2f")) + { + Instance.play_clip(name, 1.f, m_cliptimes[idx]); + } + ImGui::PopID(); + } + if (ImGui::Button(STR_C("Stop the clips"))) + { + Instance.stop_clips(); + } +} + +void eu07m_model_panel::render_channels(TAnimModel &Instance) +{ + if ((Instance.pModel == nullptr) || Instance.pModel->channels().empty()) + { + return; + } + ImGui::SeparatorText(STR_C("Channels")); + auto const &channels{Instance.pModel->channels()}; + m_channels.resize(channels.size(), 0.f); + for (std::size_t idx = 0; idx < channels.size(); ++idx) + { + auto const &channel{channels[idx]}; + ImGui::PushID(static_cast(idx)); + if (ImGui::SliderFloat(channel.name.c_str(), &m_channels[idx], std::min(channel.minimum, channel.maximum), std::max(channel.minimum, channel.maximum), "%.3f")) + { + Instance.set_channel(channel.name, m_channels[idx]); + } + ImGui::PopID(); + } + ImGui::TextDisabled("%s", STR_C("The channels and the clips are tried on the instance; the model as the file had it when it was loaded")); +} + +void eu07m_model_panel::save() +{ + if (auto const faults{eu07m::validate(m_model, 1)}; false == faults.empty()) + { + m_message = std::vformat(STR("Not saved: {}"), std::make_format_args(faults.front())); + return; + } + auto const data{eu07m::write(m_model)}; + auto const temporary{m_path + ".tmp"}; + std::ofstream file{temporary, std::ios::binary | std::ios::trunc}; + file.write(reinterpret_cast(data.data()), static_cast(data.size())); + // closed before the check: the buffer is written out there, and a fault of it (a full disk) is seen + file.close(); + std::error_code error; + if (false == file.fail()) + { + std::filesystem::rename(temporary, m_path, error); + } + if (file.fail() || error) + { + // the model stays as it was, the file cut short goes + std::filesystem::remove(temporary, error); + m_message = STR("Not saved: the file can't be written"); + return; + } + m_dirty = false; + m_message = STR("Saved. The game uses the change once it loads the model again"); +} diff --git a/application/editoruimodel.h b/application/editoruimodel.h new file mode 100644 index 000000000..dfa220ee7 --- /dev/null +++ b/application/editoruimodel.h @@ -0,0 +1,252 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include "model/eu07m/eu07m_model.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +class TAnimModel; +class TDynamicObject; +class TModel3d; +class TSubModel; +namespace scene +{ +class basic_node; +} + +// the field of work of the models in the editor: an EU07M model of a scenery model or of a vehicle, edited by someone who doesn't +// know the format. the window of the node bank says what is edited and lets a vehicle be picked, the tool options hold the page of +// the tool chosen in the toolbar (the lights, the parts of the vehicle, all the parts of the model, the animations), the inspector +// the settings of the part picked. a click on the model picks its part, a light is put where the model is clicked, and the part +// picked is moved with a gizmo in the 3d view. what is edited shows on the model at once and is taken back with Ctrl+Z; the file +// is written on Save. the geometry, the mapping and the materials aren't edited here +class eu07m_model_panel +{ + public: + enum class tool : int + { + lights, + parts, + elements, + animations + }; + + // once a frame, after the windows: the model of the scenery node selected, of the vehicle picked or of the vehicle driven. Active: + // the field of work of the models is the one in use; only then is the model shown changed, and the 3d view drawn over + void update(scene::basic_node *Selected, bool Active); + // what is edited, and the vehicles to pick from: in the window of the node bank + void render_bank(); + // the page of the tool chosen: in the tool options window + void render_tools(); + // the settings of the part picked: in the inspector + void render_selection(); + // the left button in the 3d view came down on Picked (none: nothing of the scenery, or a vehicle). true when the press picked a + // part of the model shown or put a light on it, then it doesn't select anything in the scenery + bool pick(scene::basic_node const *Picked); + // the last change of the model taken back, or made again; false when there's none + bool undo(); + bool redo(); + // the part picked taken out with what it draws, when it can be (Del) + bool remove_selected(); + // a scenery model has a file of the format to edit + bool editable(scene::basic_node const *Node) const; + + tool current_tool() const { return m_tool; } + void choose_tool(tool Tool); + bool has_vehicle() const { return m_target.vehicle != nullptr; } + // the parts and the pantographs held on the vehicle shown let go of: the editor is left, and the simulation goes on with the + // vehicle as it sets them itself + void release_holds() const; + bool has_animations() const; + bool marks_shown() const { return m_marks; } + void show_marks(bool Shown) { m_marks = Shown; } + bool turning() const { return m_gizmo == gizmo::turn; } + void set_turning(bool Turning) { m_gizmo = Turning ? gizmo::turn : gizmo::move; } + + // moves the camera to look at a point of the world, framing a sphere of the radius given + std::function focus; + // puts a model of the file (relative to the folder of the models) in the scenery, in front of the camera, and selects it + std::function place_model; + // takes the editor to the tool which puts a vehicle on a track + std::function place_vehicle; + // loads the cab of the vehicle the way the game does when someone gets in, and puts the camera in the seat of the driver; + // false when the vehicle has no cab of its own + std::function enter_cab; + // the cab of the vehicle shown is edited: the editor draws it, the camera may be in it + bool shows_cab() const { return m_active && (m_target.vehicle != nullptr) && (m_target.part == 1); } + TDynamicObject *vehicle() const { return m_target.vehicle; } + // the model as a whole is moved with the gizmo of the editor, in place of its part picked + bool moves_whole() const { return m_whole && (m_target.instance != nullptr); } + void set_whole(bool Whole) { m_whole = Whole; } + // the gizmo of the part picked is shown in the 3d view, in place of the one of the editor + bool gizmo_shown() const { return m_gizmoshown; } + // the last press of the left button in the 3d view went to the gizmo or to a mark of a light, not to picking a node + bool took_press() const { return m_tookpress; } + // picks the first node of the name in the model shown; false when it has none (the self-test of the editor) + bool select_node(std::string_view Name); + // a light added in the middle of the part picked, as a click there adds it (the self-test of the editor) + bool add_test_light(bool Spot); + // the model shown, without a file of the format, given one made of it as the game has it; false when it can't be + bool import_model(); + // the vehicle of the name picked, its body (0) or its cab (1), as a click in the list picks it (the self-test of the editor) + bool pick_vehicle(std::string_view Name, int Part); + // the cab of the vehicle shown, loaded when it isn't yet, as the button does + bool open_cab(); + // the model written to its file, as Save the changes does; false when it isn't (the self-test of the editor) + bool save_model(); + // the brightness of the light source picked, as its slider sets it; false when no light is picked (the self-test of the editor) + bool set_brightness(float Brightness); + + private: + enum class gizmo : int + { + move, + turn + }; + using box = std::pair; + // what is edited: a scenery model, or the body or the cab of a vehicle + struct target + { + TAnimModel *instance{nullptr}; + TDynamicObject *vehicle{nullptr}; + int part{0}; // of the vehicle: 0 the body, 1 the cab + bool operator==(target const &) const = default; + }; + // a change of the tree of the nodes: a light added or taken out, as the model the game has is to follow it + struct tree_change + { + enum class kind : int + { + none, + added, + removed + }; + kind what{kind::none}; + std::uint32_t index{0}; // of the node + TSubModel *submodel{nullptr}; + TSubModel *parent{nullptr}; + TSubModel *previous{nullptr}; // the child of the parent before it, none when it's the first + }; + // the model as it was before a change: the nodes and the components, or the whole of it when the tree changed + struct snapshot + { + std::vector nodes; + std::vector components; + std::vector component_data; + std::vector clips; + std::optional whole; + tree_change change; + }; + + target wanted(scene::basic_node *Selected) const; + void open(target const &Target); + bool load(TModel3d &Model); + void render_unsaved_popup(); + // the body or the cab of the vehicle, or the button which gets in its cab + void render_vehicle_part(); + // the models of the folder of the models to put in the scenery + void render_insert(); + void render_header(); + void render_guide() const; + void render_lights_page(); + void render_parts_page() const; + void render_elements_page(); + void render_tree_node(std::uint32_t Index); + void render_animations_page(); + void render_clips(TAnimModel &Instance); + void render_channels(TAnimModel &Instance); + void render_light_settings(std::uint32_t Component); + void render_place(std::uint32_t Index); + // the button which takes the part out, greyed with the reason when it can't be; true when it was taken out + bool render_remove(std::uint32_t Index, bool Light); + void render_advanced(std::uint32_t Index); + void render_component(std::uint32_t Index); + // over the 3d view: the frame of the part picked, the marks of the light sources and the gizmo + void render_view(); + // the marks of the light sources; a click on one picks its node + void render_marks(glm::dmat4 const &Placement, bool Clicked); + void render_gizmo(glm::dmat4 const &Placement, glm::dvec3 const &Camera); + void select(std::uint32_t Node); + // the submodel of the node in the model the game has, or none when that model doesn't match the file + TSubModel *submodel(std::uint32_t Node) const; + // where the model is drawn: its space in the world + std::optional placement() const; + // the part of the model at the point of the world: the smallest box of geometry holding it + std::optional node_at(glm::dvec3 const &Point) const; + // the light source of the node, the first one when it has more + std::optional light_of(std::uint32_t Node) const; + // the name of the part in words: the part of the vehicle it is, or the name of its node + std::string part_name(std::uint32_t Node) const; + // the change of a component shown on the model the game has + void show_change(std::uint32_t Index) const; + void moved(std::uint32_t Node); + // a change made: the model before it kept to be taken back, once a press of the mouse or a drag + void changed(); + snapshot take(bool Whole) const; + void restore(snapshot const &Snapshot); + void apply_tree(tree_change const &Change, bool Forward); + void push_change(snapshot Snapshot); + // after a change taken back or made again: the lights shown as they are, the next change kept from here + void settled(); + void add_light(std::uint32_t Parent, glm::vec3 const &Position, glm::quat const &Rotation, bool Spot); + void place_light(glm::dvec3 const &Point, std::optional Part); + void fly_to(std::uint32_t Node) const; + void fly_to_vehicle(TDynamicObject const &Vehicle) const; + void save(); + + bool m_active{false}; + target m_target; // shown + std::optional m_pending; // asked for while the one shown has changes not saved + std::optional m_kept; // the one shown kept although another was asked for: it isn't asked again until another one is + TDynamicObject *m_pickedvehicle{nullptr}; // in the window of the node bank + int m_part{0}; // of a vehicle, the one wanted: 0 the body, 1 the cab + scene::basic_node *m_lastselected{nullptr}; + TModel3d *m_source{nullptr}; // the model shown, as the game has it + std::string m_path; // of the .ng3d file, empty when the model has none + std::string m_problem; // why the model shown can't be edited + eu07m::model m_model; + std::vector m_submodels; // of the nodes of the file, in the model the game has; empty when they don't match + std::vector> m_boxes; // of the geometry of the nodes, each in its space + bool m_dirty{false}; + std::string m_message; + std::int64_t m_selected{-1}; // the node picked + bool m_scrolltoselected{false}; + tool m_tool{tool::lights}; + gizmo m_gizmo{gizmo::move}; + bool m_marks{true}; // the light sources marked in the 3d view + bool m_gizmoshown{false}; + bool m_tookpress{false}; + std::optional m_placing; // a light to be put where the model is clicked: a spot or a point light + std::vector m_undo; + std::vector m_redo; + snapshot m_before; // the model when no press or drag was going on + bool m_changing{false}; // the press or the drag going on has changed the model, its change is kept + std::optional m_pick_after; // the part put back by the change taken back or made again, to be picked + std::string m_filter; // of the parts in the list of all of them + bool m_importable{false}; // the model shown has no file of the format, one can be made of it + bool m_whole{false}; + bool m_scanned{false}; // the folder of the models was looked through + std::vector m_files; // of the models, relative to their folder + std::vector m_found; // those of them the search takes + std::string m_filesearch; + std::vector m_cliptimes; // the times the clips are held at, seconds + std::vector m_channels; // the values the channels were set to +}; diff --git a/docs/eu07m-format.md b/docs/eu07m-format.md index 79990b5e9..661bc87b1 100644 --- a/docs/eu07m-format.md +++ b/docs/eu07m-format.md @@ -292,9 +292,73 @@ With `modelformat ng3d` in `eu07.ini`, a model with an `.ng3d` file beside its ` - The code of the game which reads the vertices of a model (pantograph, bounds, picking, the editor) gets them as `gfx::basic_vertex`, made from the streams the first time they are read. - The stars (`STAR`) keep their colour in the normal, so they go as `gfx::basic_vertex` in Vulkan too. +- A `LGHT` node without an `LMAT` (a light made in the editor or exported anew) shines whenever its node is shown: its threshold of + self-illumination is that of `selfillum: true` of a `.t3d`. Before, such a light never lit anything. The converter gives every + light of E3D an `LMAT` with the threshold it had, so the converted models don't change. - A node with `range_max_sq` 0 has no distance limit; before, such a node (of a model made anew, not converted from E3D) wasn't drawn at all. +### In the editor + +The models are a field of work of the editor of their own, "Models" (F7), beside the surroundings, the tracks, the roads, the +terrain and the catenary (`application/editoruimodel.cpp`). It is made for someone who doesn't know the format: the parts are +called by what they are (a part of a vehicle by its name, such as "Left headlamp, front"), and the fields of the format are kept +under "Advanced". The model edited is the scenery model selected, a vehicle picked in the list of the vehicles, or with neither, +the vehicle driven (its body or its cab), so a vehicle can be driven, the editor opened with F11, a light changed and looked at +from the cab again after F11. "Edit this model (F7)" in the inspector of a scenery model loaded from an `.ng3d` file opens it +there. A model without an `.ng3d` file, or one which can't be read, says so and isn't edited. + +The cab of a vehicle is loaded only by getting in. When it isn't loaded yet, "Get in the cab" does what the simulation does then: it +makes the train of the vehicle (`TTrain::Init`, which loads the cab, its controls and its sounds) and makes it the vehicle driven, +and puts the camera in the seat of the driver. While the cab is edited the editor draws it as from the seat of the driver +(`FreeFlyModeFlag` off, the vehicle the owner of the camera, which moves in the cab with the vehicle); with the body picked, or +in another field of work, the view is free again. + +- **A model without a file of the format.** "Import to EU07M" writes `.ng3d` beside its `.e3d` (or its `.t3d`), made of + the model as the game loaded it, as `eu07 -eu07m convert` makes it (`eu07m::import_model`); for a vehicle, its body or its cab, + that is what the game writes to the `.e3d` it makes of a `.t3d`. From then on the game loads the model from it, in every + scenery. So a model of the data whose lights aren't set, such as a lamp post or a cab with its one default light, gets its light + sources here. +- **Models and vehicles in the scenery loaded.** "Put a model in the scenery" lists the `.e3d` and `.t3d` files of the folder of + the models; a click puts one in front of the camera, selected (a change of the scenery, taken back with Ctrl+Z and saved with + it). "Whole model" in the toolbar hands the gizmo of the editor the scenery model shown, to move or turn it in the scenery. + "Put a vehicle on a track..." opens the Trainset tool of the tracks. +- **The windows.** The window of the node bank says what is edited and lists the vehicles (a click picks one and takes the camera + to it). The tool options hold the page of the tool chosen in the toolbar, with "Save the changes", "Undo" and "Redo" and a short + "How it works". The inspector holds the settings of the part picked. +- **The tools.** "Lights" lists the light sources of the model; "+ Add a bulb" and "+ Add a spot" put one where the model is + clicked next, a spot shining towards the camera, as the last child of the part clicked (`light_`, a `LGHT` point or spot + light; the references to the nodes after it move on, `eu07m::insert_node`). "Parts of the vehicle" holds the pantographs of the + vehicle up or down, and its lamps, coupler hooks and hoses (`headlamp11`, `coupler1`, `cpneumatic1` and the like) in the `_on`, + `_off` or `_xon` state of their submodels, whatever the vehicle does with them, until "As the vehicle has it"; a held pantograph + moves at its own pace, in the editor too, up to the wire above it when there is one (1.6 m over its rest without one). Nothing + of these holds goes into the file. "All parts" is the tree of the nodes with a search by name. "Animations" holds the clips of a + scenery model, with their flags and a time to hold the instance at (the time stands still in the editor), and its channels, + tried on the instance without changing the file. "Move", "Turn" and "Marks of the lights" set the gizmo and the marks. +- **The 3d view.** A click on the model picks its part: the smallest box of geometry of a part shown holding the point clicked. A + click on another scenery model edits that one; a click on anything else changes nothing. The part picked is framed and shows its + axes and a gizmo, which moves or turns it. The light sources are marked with their colour (a spot with its axis, the -z of its + node), and a click on a mark picks its light. A press on the gizmo or on a mark doesn't pick a scenery node. +- **The settings of a part.** A light: a bulb or a spot, its colour (with a few common ones), its brightness, its glowing spot, + the width of the beam and its bright middle (in degrees from its axis), and whether it casts shadows, has a soft edge and lights + its own model. The place: the gizmo, and under "Exact values" the position, the rotation (in degrees) and the scale, unless a + matrix of `XFRM` places the node; and the distances it is seen from and up to. A part without parts under it, which nothing else + points at (an animation, a light slot, a skin), is taken out with "Remove this part" ("Remove this light" for a light) or Del, + with what it draws: its components, its transform and its own mesh, whose vertices and indices leave the streams where no other + primitive shares them; the primitives and the references to the geometry store after them move back (`eu07m::remove_node`). So + the flat glowing patch under a lamp post of E3D (`placek`) is taken out and a real light source put in the lamp instead. "Advanced" holds the fields of the common components (`SOCK`, `JOIN`, + `CHNL` with its bindings, `LGHT`, `LSLT`, `EMIT`, `COLL`, `MREF`; the others are shown by their size, strings are edited by their + text) and "Add a light to this part". +- **Changes.** A change shows at once on the model the game has (on every instance of it), when that model is the one of the file. + Ctrl+Z and Ctrl+Y take the changes of the model back and make them again, a light added or taken out among them, and then those + of the scenery (a model put in or moved as a whole); with "Whole model" chosen, those of the scenery. Del doesn't delete scenery + nodes in this field of work. "Save the changes" checks the model and writes the + file again (the store of the family is kept); the game uses the change once it loads the model again. Another model asked for + while the one edited has changes not saved asks first whether to save them, throw them away (the model the game has goes back + to the file) or go on with the one edited. + +The geometry, the mapping and the materials aren't edited there; that is the work of the exporter. + ### Animation clips A clip (`ACLP`) is a set of tracks (`ATRK`), each of which sets one part of the TRS of a node: translation, rotation or scale. The diff --git a/editor/editorIcons.hpp b/editor/editorIcons.hpp index 7118b470f..01c55cbd2 100644 --- a/editor/editorIcons.hpp +++ b/editor/editorIcons.hpp @@ -70,6 +70,12 @@ enum class icon work_catenary, gantry, wires, + // the models, after the catenary for the same reason + work_models, + light, + pantograph, + parts_tree, + animation, count }; diff --git a/editor/icons/editor_icons.png b/editor/icons/editor_icons.png index f1305097c..57da9f95f 100644 Binary files a/editor/icons/editor_icons.png and b/editor/icons/editor_icons.png differ diff --git a/editor/icons/editor_icons.py b/editor/icons/editor_icons.py index f18774a38..a6d2ab2c3 100644 --- a/editor/icons/editor_icons.py +++ b/editor/icons/editor_icons.py @@ -476,12 +476,50 @@ def wires(d): line(d, [(4, 48), (60, 48)], W - 4) +def work_models(d): + # a box seen from a corner: the outline and the three edges meeting in the near corner + poly(d, [(32, 4), (58, 18), (58, 46), (32, 60), (6, 46), (6, 18)], outline=True, width=W - 6) + line(d, [(6, 18), (32, 32), (58, 18)], W - 6) + line(d, [(32, 32), (32, 60)], W - 6) + + +def light(d): + # a bulb: the glass, the neck and the cap + circle(d, 32, 24, 18) + rect(d, 24, 40, 40, 48) + rect(d, 27, 51, 37, 58, radius=2) + + +def pantograph(d): + # the roof, the crossed arms of the frame and the head on top + line(d, [(8, 58), (56, 58)], W - 6) + line(d, [(18, 58), (42, 34), (24, 12)], W - 8) + line(d, [(46, 58), (22, 34), (40, 12)], W - 8) + line(d, [(8, 10), (56, 10)], W - 4) + + +def parts_tree(d): + # a part and the parts under it, as a tree + rect(d, 6, 6, 24, 20, radius=2) + line(d, [(14, 20), (14, 50)], W - 10) + line(d, [(14, 32), (30, 32)], W - 10) + line(d, [(14, 50), (30, 50)], W - 10) + rect(d, 32, 25, 58, 39, radius=2) + rect(d, 32, 43, 58, 57, radius=2) + + +def animation(d): + # play in a ring + circle(d, 32, 32, 26, outline=True, width=W - 6) + poly(d, [(25, 19), (25, 45), (47, 32)]) + + ICONS = [select, insert, brush, area_fill, copy_to_bank, translate, rotate, scale, local_space, ortho, perspective, sculpt, smooth, chunks, orthophoto, road, place, lanes, lay_track, switch, straight, curve, signal, objects, vehicle, profile, speed, joints, infra, gauge, turntable, parallel, station, kilometrage, more, work_surroundings, work_tracks, work_roads, work_terrain, station_signals, line_block, hole, grass, catenary, - work_catenary, gantry, wires] + work_catenary, gantry, wires, work_models, light, pantograph, parts_tree, animation] def cutouts(name, d): diff --git a/lang/editor_pl.po b/lang/editor_pl.po index 2abe0652d..4fa78b916 100644 --- a/lang/editor_pl.po +++ b/lang/editor_pl.po @@ -16339,3 +16339,759 @@ msgstr "Nie udało się zapisać terenu: %s. Pliki sieci trakcyjnej są już zap msgid "Files of the terrain or of the catenary may be written already, the scenery files aren't: save again once it's fixed" msgstr "Pliki terenu lub sieci trakcyjnej mogą być już zapisane, pliki scenerii nie: zapisz ponownie po usunięciu przyczyny" + +msgid "The data of the component is cut short" +msgstr "Dane komponentu są ucięte" + +msgid "Role" +msgstr "Rola" + +msgid "End of the vehicle" +msgstr "Koniec pojazdu" + +msgid "front" +msgstr "przód" + +msgid "rear" +msgstr "tył" + +msgid "Index" +msgstr "Indeks" + +msgid "Position" +msgstr "Położenie" + +msgid "hinge" +msgstr "zawias" + +msgid "ball" +msgstr "kulisty" + +msgid "slider" +msgstr "przesuw" + +msgid "screw" +msgstr "śruba" + +msgid "Limited" +msgstr "Ograniczony" + +msgid "Axis" +msgstr "Oś" + +msgid "Minimum" +msgstr "Minimum" + +msgid "Maximum" +msgstr "Maksimum" + +msgid "Rest" +msgstr "Spoczynek" + +msgid "Pitch, m a turn" +msgstr "Skok, m na obrót" + +msgid "Initial value" +msgstr "Wartość początkowa" + +msgid "Bound to" +msgstr "Powiązany z" + +msgid "joint" +msgstr "joint" + +msgid "clip" +msgstr "klip" + +msgid "variants" +msgstr "warianty" + +msgid "light slot" +msgstr "slot światła" + +msgid "Target (component or clip, -1 none)" +msgstr "Cel (komponent albo klip, -1 brak)" + +msgid "Offset" +msgstr "Przesunięcie" + +msgid "point" +msgstr "punkt" + +msgid "spot" +msgstr "reflektor" + +msgid "Lights itself" +msgstr "Oświetla siebie" + +msgid "No shadows" +msgstr "Bez cieni" + +msgid "Soft falloff" +msgstr "Miękkie wygaszanie" + +msgid "Light only" +msgstr "Tylko oświetlenie" + +msgid "Colour" +msgstr "Kolor" + +msgid "Intensity" +msgstr "Natężenie" + +msgid "Slot" +msgstr "Slot" + +msgid "Initial state" +msgstr "Stan początkowy" + +msgid "Colour (negative: of the sources)" +msgstr "Kolor (ujemny: kolor źródeł)" + +msgid "smoke" +msgstr "dym" + +msgid "steam" +msgstr "para" + +msgid "sparks" +msgstr "iskry" + +msgid "Direction" +msgstr "Kierunek" + +msgid "Shape" +msgstr "Kształt" + +msgid "box" +msgstr "prostopadłościan" + +msgid "sphere" +msgstr "kula" + +msgid "capsule" +msgstr "kapsuła" + +msgid "Centre" +msgstr "Środek" + +msgid "Half extents" +msgstr "Połowy wymiarów" + +msgid "Model path" +msgstr "Ścieżka modelu" + +msgid "{} bytes, not edited here" +msgstr "{} B, nie edytowane tutaj" + +msgid "Binding {}" +msgstr "Powiązanie {}" + +msgid "Animation clips" +msgstr "Klipy animacji" + +msgid "Looped" +msgstr "Zapętlony" + +msgid "Plays on its own" +msgstr "Gra sam" + +msgid "Time, s" +msgstr "Czas, s" + +msgid "Stop the clips" +msgstr "Zatrzymaj klipy" + +msgid "Channels" +msgstr "Kanały" + +msgid "The channels and the clips are tried on the instance; the model as the file had it when it was loaded" +msgstr "Kanały i klipy są próbowane na egzemplarzu, w modelu takim, jaki plik miał przy wczytaniu" + +msgid "Not saved: {}" +msgstr "Nie zapisano: {}" + +msgid "Not saved: the file can't be written" +msgstr "Nie zapisano: nie można zapisać pliku" + +msgid "Saved. The game uses the change once it loads the model again" +msgstr "Zapisano. Gra użyje zmiany, gdy wczyta model ponownie" + +msgid "Body" +msgstr "Pudło" + +msgid "Cab" +msgstr "Kabina" + +msgid "Automatic" +msgstr "Automatycznie" + +msgid "Pantograph {}" +msgstr "Pantograf {}" + +msgid "Parts of the vehicle" +msgstr "Części pojazdu" + +msgid "Properties" +msgstr "Właściwości" + +msgid "Socket" +msgstr "Gniazdo" + +msgid "Joint" +msgstr "Przegub" + +msgid "Spring" +msgstr "Sprężyna" + +msgid "Chain" +msgstr "Łańcuch" + +msgid "Variants" +msgstr "Warianty" + +msgid "Channel" +msgstr "Kanał" + +msgid "Light slot" +msgstr "Slot światła" + +msgid "Light source" +msgstr "Źródło światła" + +msgid "Emitter" +msgstr "Emiter" + +msgid "Attached model" +msgstr "Dołączony model" + +msgid "Collision shape" +msgstr "Bryła kolizji" + +msgid "Animation (E3D)" +msgstr "Animacja (E3D)" + +msgid "Text (E3D)" +msgstr "Tekst (E3D)" + +msgid "Stars (E3D)" +msgstr "Gwiazdy (E3D)" + +msgid "Material (E3D)" +msgstr "Materiał (E3D)" + +msgid "Component" +msgstr "Komponent" + +msgid "Upper headlamp, front" +msgstr "Reflektor górny, przód" + +msgid "Right headlamp, front" +msgstr "Reflektor prawy, przód" + +msgid "Left headlamp, front" +msgstr "Reflektor lewy, przód" + +msgid "Right high beam, front" +msgstr "Światło drogowe prawe, przód" + +msgid "Left high beam, front" +msgstr "Światło drogowe lewe, przód" + +msgid "Right signal lamp, front" +msgstr "Lampa sygnałowa prawa, przód" + +msgid "Left signal lamp, front" +msgstr "Lampa sygnałowa lewa, przód" + +msgid "Upper headlamp, rear" +msgstr "Reflektor górny, tył" + +msgid "Right headlamp, rear" +msgstr "Reflektor prawy, tył" + +msgid "Left headlamp, rear" +msgstr "Reflektor lewy, tył" + +msgid "Right high beam, rear" +msgstr "Światło drogowe prawe, tył" + +msgid "Left high beam, rear" +msgstr "Światło drogowe lewe, tył" + +msgid "Right signal lamp, rear" +msgstr "Lampa sygnałowa prawa, tył" + +msgid "Left signal lamp, rear" +msgstr "Lampa sygnałowa lewa, tył" + +msgid "Coupler hook, front" +msgstr "Hak sprzęgu, przód" + +msgid "Coupler hook, rear" +msgstr "Hak sprzęgu, tył" + +msgid "Brake hose, front" +msgstr "Wąż hamulcowy, przód" + +msgid "Brake hose, front, other side" +msgstr "Wąż hamulcowy, przód, druga strona" + +msgid "Brake hose, rear" +msgstr "Wąż hamulcowy, tył" + +msgid "Brake hose, rear, other side" +msgstr "Wąż hamulcowy, tył, druga strona" + +msgid "Supply hose, front" +msgstr "Wąż zasilający, przód" + +msgid "Supply hose, front, other side" +msgstr "Wąż zasilający, przód, druga strona" + +msgid "Supply hose, rear" +msgstr "Wąż zasilający, tył" + +msgid "Supply hose, rear, other side" +msgstr "Wąż zasilający, tył, druga strona" + +msgid "Disconnected" +msgstr "Rozłączony" + +msgid "Connected" +msgstr "Połączony" + +msgid "Other position" +msgstr "Inne położenie" + +msgid "Pantographs" +msgstr "Pantografy" + +msgid "Front lights" +msgstr "Światła przednie" + +msgid "Rear lights" +msgstr "Światła tylne" + +msgid "Couplers and hoses" +msgstr "Sprzęgi i węże" + +msgid "Position, m" +msgstr "Położenie, m" + +msgid "Rotation, degrees" +msgstr "Obrót, stopnie" + +msgid "Visible from, m" +msgstr "Widoczny od, m" + +msgid "Visible up to, m (0: no limit)" +msgstr "Widoczny do, m (0: bez limitu)" + +msgid "The model in the game differs from the file: the changes show once the game loads the model again" +msgstr "Model w grze różni się od pliku: zmiany będą widoczne po ponownym wczytaniu modelu" + +msgid "Glowing sphere radius, m" +msgstr "Promień świecącej kuli, m" + +msgid "Cone, half angle in degrees" +msgstr "Stożek, połowa kąta w stopniach" + +msgid "Hotspot, half angle in degrees" +msgstr "Plama, połowa kąta w stopniach" + +msgid "Model" +msgstr "Model" + +msgid "Move" +msgstr "Przesuwaj" + +msgid "Turn" +msgstr "Obracaj" + +msgid "Lit" +msgstr "Zapalona" + +msgid "Dimmed" +msgstr "Przyciemniona" + +msgid "As the vehicle has it" +msgstr "Jak w pojeździe" + +msgid "Light them all" +msgstr "Zapal wszystkie" + +msgid "Connect them all" +msgstr "Podłącz wszystkie" + +msgid "Put them all out" +msgstr "Zgaś wszystkie" + +msgid "Disconnect them all" +msgstr "Odłącz wszystkie" + +msgid "All as the vehicle has them" +msgstr "Wszystkie jak w pojeździe" + +msgid "The models of the EU07M format are turned off (modelformat in eu07.ini)" +msgstr "Modele w formacie EU07M są wyłączone (modelformat w eu07.ini)" + +msgid "This model has no EU07M file, so it can't be edited here. The command eu07 -eu07m convert makes one of its E3D or T3D file" +msgstr "Ten model nie ma pliku EU07M, więc nie da się go tu zmieniać. Polecenie eu07 -eu07m convert zrobi go z pliku E3D albo T3D" + +msgid "The EU07M file of the model can't be read: {}" +msgstr "Nie da się odczytać pliku EU07M tego modelu: {}" + +msgid "Changes not saved" +msgstr "Niezapisane zmiany" + +msgid "The model {} has changes which aren't saved." +msgstr "Model {} ma zmiany, które nie są zapisane." + +msgid "Save them" +msgstr "Zapisz je" + +msgid "Throw them away" +msgstr "Odrzuć je" + +msgid "Go on with this one" +msgstr "Zostań przy tym modelu" + +msgid "Edited model" +msgstr "Edytowany model" + +msgid "Nothing picked yet." +msgstr "Jeszcze nic nie wybrano." + +msgid "A model of the scenery" +msgstr "Model ze scenerii" + +msgid "Click a model in the view to edit it." +msgstr "Kliknij model w widoku, żeby go edytować." + +msgid "Back to {}" +msgstr "Wróć do {}" + +msgid "Vehicles" +msgstr "Pojazdy" + +msgid "The scenery has no vehicles." +msgstr "W scenerii nie ma pojazdów." + +msgid "A click picks the vehicle and takes the camera to it" +msgstr "Kliknięcie wybiera pojazd i przenosi do niego kamerę" + +msgid "(driven)" +msgstr "(prowadzony)" + +msgid "No model to edit. Click a model in the scenery, or pick a vehicle in the list on the left." +msgstr "Nie ma modelu do edycji. Kliknij model w scenerii albo wybierz pojazd z listy po lewej." + +msgid "Save the changes" +msgstr "Zapisz zmiany" + +msgid "Writes the model to its file; until then nothing of it is changed on the disk" +msgstr "Zapisuje model do jego pliku; do tego czasu nic nie zmienia się na dysku" + +msgid "Takes the last change of the model back (Ctrl+Z)" +msgstr "Cofa ostatnią zmianę modelu (Ctrl+Z)" + +msgid "Makes the change taken back again (Ctrl+Y)" +msgstr "Przywraca cofniętą zmianę (Ctrl+Y)" + +msgid "Not saved" +msgstr "Niezapisane" + +msgid "How it works" +msgstr "Jak to działa" + +msgid "1. Pick the model: click it in the scenery, or pick a vehicle in the list on the left." +msgstr "1. Wybierz model: kliknij go w scenerii albo wybierz pojazd z listy po lewej." + +msgid "2. Click a part of the model in the view. Its settings come up in the inspector." +msgstr "2. Kliknij część modelu w widoku. Jej ustawienia pojawią się w inspektorze." + +msgid "3. Drag the arrows in the view to move the part picked, or the rings to turn it: Move and Turn are in the toolbar." +msgstr "3. Przeciągnij strzałki w widoku, żeby przesunąć wybraną część, albo pierścienie, żeby ją obrócić: Przesuwaj i Obracaj są na pasku narzędzi." + +msgid "4. Ctrl+Z takes a change back. Nothing goes into the file until Save the changes." +msgstr "4. Ctrl+Z cofa zmianę. Nic nie trafia do pliku przed kliknięciem Zapisz zmiany." + +msgid "The light sources of the model. Click one to change it in the inspector; its round mark in the view does the same." +msgstr "Źródła światła modelu. Kliknij jedno, żeby zmienić je w inspektorze; to samo robi kliknięcie jego kółka w widoku." + +msgid "Click the model where the light is to be. Esc gives it up." +msgstr "Kliknij model w miejscu, gdzie ma być światło. Esc rezygnuje." + +msgid "Give it up" +msgstr "Zrezygnuj" + +msgid "+ Add a bulb" +msgstr "+ Dodaj żarówkę" + +msgid "A light which shines all around, as a bulb; then a click on the model puts it there" +msgstr "Światło świecące dookoła, jak żarówka; potem kliknięcie modelu stawia je w tym miejscu" + +msgid "+ Add a spot" +msgstr "+ Dodaj reflektor" + +msgid "A light which shines one way, as a headlamp; then a click on the model puts it there, shining towards the camera" +msgstr "Światło świecące w jedną stronę, jak reflektor; potem kliknięcie modelu stawia je w tym miejscu, świecące w stronę kamery" + +msgid "Marks of the lights in the view" +msgstr "Kółka świateł w widoku" + +msgid "Lights of the model" +msgstr "Światła modelu" + +msgid "bulb" +msgstr "żarówka" + +msgid "The model has no light sources yet." +msgstr "Model nie ma jeszcze źródeł światła." + +msgid "The parts of a vehicle are held on its body: pick the body on the left." +msgstr "Części pojazdu ustawia się na nadwoziu: wybierz nadwozie po lewej." + +msgid "The vehicle keeps a part as set here until As the vehicle has it is chosen. Nothing of it goes into the file." +msgstr "Pojazd trzyma część tak, jak ją tu ustawisz, dopóki nie wybierzesz Jak w pojeździe. Nic z tego nie trafia do pliku." + +msgid "All the parts of the model, as they hang one on another. A click picks one, a double click takes the camera to it." +msgstr "Wszystkie części modelu, tak jak jedna wisi na drugiej. Kliknięcie wybiera część, dwuklik przenosi do niej kamerę." + +msgid "Look for a part by its name" +msgstr "Szukaj części po nazwie" + +msgid "The animations are tried on a model of the scenery." +msgstr "Animacje sprawdza się na modelu ze scenerii." + +msgid "The animations of the model, tried on it in the view. Looped and Plays on its own go into the file." +msgstr "Animacje modelu, sprawdzane na nim w widoku. Zapętlony i Gra sam trafiają do pliku." + +msgid "Pick a model first: click it in the view, or pick a vehicle in the list on the left." +msgstr "Najpierw wybierz model: kliknij go w widoku albo wybierz pojazd z listy po lewej." + +msgid "Click a part of the model in the view, or pick one in the tool options, to change it here." +msgstr "Kliknij część modelu w widoku albo wybierz ją w opcjach narzędzia, żeby ją tu zmienić." + +msgid "A light source" +msgstr "Źródło światła" + +msgid "A part of the model" +msgstr "Część modelu" + +msgid "A point of the model, with nothing to see" +msgstr "Punkt modelu, bez niczego do zobaczenia" + +msgid "Show it in the view" +msgstr "Pokaż w widoku" + +msgid "Remove this light (Del)" +msgstr "Usuń to światło (Del)" + +msgid "Light" +msgstr "Światło" + +msgid "Bulb: shines all around" +msgstr "Żarówka: świeci dookoła" + +msgid "Spot: shines one way" +msgstr "Reflektor: świeci w jedną stronę" + +msgid "Brightness" +msgstr "Jasność" + +msgid "How strongly it lights what is around it. Ctrl+click types a value" +msgstr "Jak mocno oświetla otoczenie. Ctrl+klik pozwala wpisać wartość" + +msgid "Glowing spot, m" +msgstr "Świecąca plamka, m" + +msgid "The size of the glowing ball seen where the light is; 0 shows none" +msgstr "Wielkość świecącej kuli widocznej w miejscu światła; 0 – bez kuli" + +msgid "Width of the beam, degrees" +msgstr "Szerokość snopu, stopnie" + +msgid "From the axis of the beam to its edge" +msgstr "Od osi snopu do jego krawędzi" + +msgid "Bright middle, degrees" +msgstr "Jasny środek, stopnie" + +msgid "The middle of the beam lit fully; from there to the edge it fades" +msgstr "Środek snopu świeci w pełni; dalej do krawędzi światło słabnie" + +msgid "Casts shadows" +msgstr "Rzuca cienie" + +msgid "Soft edge" +msgstr "Miękka krawędź" + +msgid "Lights this model too" +msgstr "Oświetla też ten model" + +msgid "This part is placed in a way this window doesn't change" +msgstr "Ta część jest ustawiona w sposób, którego to okno nie zmienia" + +msgid "Drag the arrows in the view to move it, or the rings to turn it." +msgstr "Przeciągnij strzałki w widoku, żeby ją przesunąć, albo pierścienie, żeby ją obrócić." + +msgid "Seen from" +msgstr "Widoczność" + +msgid "Advanced: the data of the file" +msgstr "Zaawansowane: dane pliku" + +msgid "For those who know the EU07M format" +msgstr "Dla znających format EU07M" + +msgid "Add a light to this part" +msgstr "Dodaj światło do tej części" + +msgid "Click the model where the light is to be" +msgstr "Kliknij model w miejscu, gdzie ma być światło" + +msgid "Added the light {}. Drag the arrows in the view to move it" +msgstr "Dodano światło {}. Przeciągnij strzałki w widoku, żeby je przesunąć" + +msgid "Removed the light {}. Ctrl+Z brings it back" +msgstr "Usunięto światło {}. Ctrl+Z je przywróci" + +msgid "Models" +msgstr "Modele" + +msgid "The models of the vehicles and of the scenery: their lights, the parts of a vehicle, moving and turning their parts" +msgstr "Modele pojazdów i scenerii: ich światła, części pojazdu, przesuwanie i obracanie ich części" + +msgid "The light sources of the model: change them, add them by a click on the model" +msgstr "Źródła światła modelu: zmieniaj je i dodawaj kliknięciem w model" + +msgid "Pantographs up or down, lamps lit or off, couplers and hoses connected or not" +msgstr "Pantografy w górze lub w dole, lampy zapalone lub zgaszone, sprzęgi i węże podłączone lub nie" + +msgid "All parts" +msgstr "Wszystkie części" + +msgid "All the parts of the model as a tree, with a search by name" +msgstr "Wszystkie części modelu jako drzewo, z wyszukiwaniem po nazwie" + +msgid "Animations" +msgstr "Animacje" + +msgid "The animations of the model, tried in the view" +msgstr "Animacje modelu, sprawdzane w widoku" + +msgid "The arrows in the view move the part picked" +msgstr "Strzałki w widoku przesuwają wybraną część" + +msgid "The rings in the view turn the part picked" +msgstr "Pierścienie w widoku obracają wybraną część" + +msgid "Marks of the lights" +msgstr "Kółka świateł" + +msgid "The round marks of the light sources in the view; a click on one picks the light" +msgstr "Okrągłe znaczniki źródeł światła w widoku; kliknięcie znacznika wybiera światło" + +msgid "Edit this model (F7)" +msgstr "Edytuj ten model (F7)" + +msgid "Warm white" +msgstr "Ciepła biel" + +msgid "White" +msgstr "Biel" + +msgid "Cold white" +msgstr "Zimna biel" + +msgid "Red" +msgstr "Czerwony" + +msgid "Yellow" +msgstr "Żółty" + +msgid "Green" +msgstr "Zielony" + +msgid "Blue" +msgstr "Niebieski" + +msgid "This model has no EU07M file yet. Import it to change its lights and parts." +msgstr "Ten model nie ma jeszcze pliku EU07M. Zaimportuj go, żeby zmieniać jego światła i części." + +msgid "Put a vehicle on a track..." +msgstr "Postaw pojazd na torze..." + +msgid "The Trainset tool of the tracks: click a track, pick the vehicle and Place it; F7 brings you back here" +msgstr "Narzędzie Skład w torach: kliknij tor, wybierz pojazd i postaw go; F7 wraca tutaj" + +msgid "Put a model in the scenery" +msgstr "Wstaw model do scenerii" + +msgid "Look for a model by its name, e.g. latarnia" +msgstr "Szukaj modelu po nazwie, np. latarnia" + +msgid "A click puts the model in front of the camera; then Whole model in the toolbar moves it" +msgstr "Kliknięcie stawia model przed kamerą; potem Cały model na pasku narzędzi pozwala go przestawić" + +msgid "Not imported: {}" +msgstr "Nie zaimportowano: {}" + +msgid "Imported to {}. Its lights and parts can be changed now" +msgstr "Zaimportowano do {}. Teraz można zmieniać jego światła i części" + +msgid "Import to EU07M" +msgstr "Importuj do EU07M" + +msgid "Writes an .ng3d file beside the model, made of the model as the game has it. From then on the game loads the model from it, in every scenery" +msgstr "Zapisuje plik .ng3d obok modelu, zrobiony z modelu wczytanego w grze. Od tej chwili gra wczytuje model z tego pliku, w każdej scenerii" + +msgid "Click a track, pick the vehicle and Place it; F7 goes back to the models" +msgstr "Kliknij tor, wybierz pojazd i postaw go; F7 wraca do modeli" + +msgid "The model %s couldn't be put in, the log says why" +msgstr "Nie udało się wstawić modelu %s, powód jest w logu" + +msgid "%s stands in the scenery; Whole model in the toolbar moves it" +msgstr "%s stoi w scenerii; Cały model na pasku narzędzi pozwala go przestawić" + +msgid "Whole model" +msgstr "Cały model" + +msgid "The gizmo moves or turns the whole model in the scenery, not its part; the change is one of the scenery, saved with it" +msgstr "Uchwyt przesuwa albo obraca cały model w scenerii, a nie jego część; to zmiana scenerii, zapisywana razem z nią" + +msgid "Get in the cab" +msgstr "Wejdź do kabiny" + +msgid "Loads the cab of the vehicle as the game does when you get in, and puts the camera in the seat of the driver" +msgstr "Wczytuje kabinę pojazdu tak jak gra, gdy do niego wsiadasz, i stawia kamerę na miejscu maszynisty" + +msgid "The vehicle has no cab of its own to get in" +msgstr "Pojazd nie ma własnej kabiny, do której można wejść" + +msgid "The cab of %s couldn't be loaded, the log says why" +msgstr "Nie udało się wczytać kabiny %s, powód jest w logu" + +msgid "In the cab of %s; the editor draws it while the cab is edited" +msgstr "W kabinie %s; edytor rysuje ją, dopóki edytujesz kabinę" + +msgid "Remove this part (Del)" +msgstr "Usuń tę część (Del)" + +msgid "Takes it out of the model, with what it draws; Ctrl+Z brings it back" +msgstr "Usuwa ją z modelu razem z tym, co rysuje; Ctrl+Z ją przywraca" + +msgid "This part can't be taken out: it has parts under it, or something else in the model points at it (an animation, a light slot, a skin)" +msgstr "Tej części nie da się usunąć: ma pod sobą inne części albo coś innego w modelu na nią wskazuje (animacja, slot świateł, skóra)" + +msgid "Removed {}. Ctrl+Z brings it back" +msgstr "Usunięto {}. Ctrl+Z ją przywróci" + +msgid "While the .ng3d is there, a later update of the .e3d or .t3d doesn't reach the game: import it again, or delete the .ng3d" +msgstr "Dopóki jest plik .ng3d, późniejsza aktualizacja pliku .e3d lub .t3d nie dociera do gry: zaimportuj model ponownie albo usuń plik .ng3d" + +msgid "The model %s can't be put in: a scenery doesn't take a space in the name of a file" +msgstr "Nie można wstawić modelu %s: sceneria nie przyjmuje spacji w nazwie pliku" diff --git a/model/AnimModel.cpp b/model/AnimModel.cpp index 5670c7339..428b595a4 100644 --- a/model/AnimModel.cpp +++ b/model/AnimModel.cpp @@ -820,7 +820,7 @@ void TAnimModel::light_parts_shown( int const Light, bool &Lit, bool &Dark ) con } } -bool TAnimModel::play_clip( std::string_view const Name, float const Speed ) { +bool TAnimModel::play_clip( std::string_view const Name, float const Speed, float const From ) { if( pModel == nullptr ) { return false; } auto const &clips { pModel->clips() }; @@ -832,7 +832,10 @@ bool TAnimModel::play_clip( std::string_view const Name, float const Speed ) { if( found == clips.end() ) { return false; } auto const index { static_cast( std::distance( clips.begin(), found ) ) }; std::erase_if( m_clips, [ index ]( clip_playing const &Playing ) { return Playing.clip == index; } ); - m_clips.push_back( { index, Timer::GetTime(), Speed } ); + // started as long before now as From takes at the pace; a pace of 0 holds the clip at its start and a negative one runs it + // backwards, as before, From counted only for a clip going forwards + auto const ahead { Speed > 0.f ? static_cast( From / Speed ) : 0.0 }; + m_clips.push_back( { index, Timer::GetTime() - ahead, Speed } ); m_autoplaystarted = true; return true; } diff --git a/model/AnimModel.h b/model/AnimModel.h index 46ef49f80..254dc8083 100644 --- a/model/AnimModel.h +++ b/model/AnimModel.h @@ -202,9 +202,10 @@ public: // rotation and scale of the instance as a matrix: rotate y * rotate x * rotate z * scale glm::mat4 const &rotation_scale(); void RaAnimate( unsigned int const Framestamp ); // przeliczenie animacji egzemplarza - // starts the animation clip of the model (EU07M) with the name from its beginning, at Speed times its pace; a clip already playing - // starts over. false when the model has no clip of the name - bool play_clip( std::string_view Name, float Speed = 1.f ); + // starts the animation clip of the model (EU07M) with the name at From seconds of it (its beginning by default), at Speed times its + // pace; a clip already playing starts over. with the time stopped (the editor) it holds the pose of From. From is counted only for + // a positive Speed: 0 holds the clip at its start, a negative Speed runs it backwards. false when the model has no clip of the name + bool play_clip( std::string_view Name, float Speed = 1.f, float From = 0.f ); // stops the clips playing: each is held at the moment it was stopped, so the nodes stay where they were put, till a clip // started on them or an animation event of the scenery moves them void stop_clips(); diff --git a/model/Model3d.h b/model/Model3d.h index 50aa56bfa..e2cd39f2a 100644 --- a/model/Model3d.h +++ b/model/Model3d.h @@ -16,7 +16,9 @@ http://mozilla.org/MPL/2.0/. #include "model/skinning.h" #include "model/clip.h" +#include #include +#include #define EU07_USE_GEOMETRYINDEXING @@ -57,6 +59,9 @@ class TModel3d; namespace eu07m { struct model; } +namespace eu07m::payload { +struct light; +} using nameoffset_sequence = std::vector>; class TSubModel @@ -343,6 +348,10 @@ private: void bounds_from_nodes(); // the geometry bank of an EU07M model made streamed, the bounds of the nodes kept (model/eu07m/eu07m_load.cpp) void stream_geometry( std::string const &FileName, eu07m::model const &Model, std::uint64_t const Hash ); + // the flags of the submodel tree worked out again after the editor changed it, and the renderer told + void submodels_changed(); + std::vector> m_editorsubmodels; // added by the editor, linked into the tree + std::vector> m_editormatrices; // given by the editor to submodels which had none public: // the geometry of the model may be streamed (modelstreaming): set by who asks for the model before it's loaded @@ -389,6 +398,20 @@ public: // the model from an EU07M file (model/eu07m/eu07m_load.cpp), as LoadFromBinFile builds it from E3D. returns false, with the reason // in the log and nothing loaded, when the file can't be read or isn't valid bool LoadFromEU07M(std::string const &FileName, bool dynamic); + // the light of the submodel as the loading of an EU07M model sets it from Light (model/eu07m/eu07m_load.cpp) + static void ApplyEU07MLight(TSubModel &Submodel, eu07m::payload::light const &Light); + // for the editor, which shows a change of an EU07M file on the model at once. a new submodel of a light, the last child of + // Parent, placed by Local in its space and kept by the model + TSubModel &AddEditorLight(TSubModel &Parent, std::string const &Name, glm::mat4 const &Local, std::uint32_t Flags, eu07m::payload::light const &Light); + // the transform of the submodel in the space of its parent; a submodel without one of its own gets one, kept by the model + void SetEditorTransform(TSubModel &Submodel, glm::mat4 const &Local); + // the squared distances from which and up to which the submodel is drawn; 0 as the upper one is the default of a submodel + void SetEditorRange(TSubModel &Submodel, float MinSq, float MaxSq); + // for the editor: the submodel taken out of the children of its parent, where it's no longer drawn; it stays where it's kept. + // returns the child before it, none when it was the first one or has no parent (then it isn't taken out) + TSubModel *UnlinkEditorSubmodel(TSubModel &Submodel); + // for the editor: the submodel put back among the children of Parent, after Previous, or as the first child when Previous is none + void LinkEditorSubmodel(TSubModel &Submodel, TSubModel &Parent, TSubModel *Previous); bool LoadFromFile(std::string const &FileName, bool dynamic); TSubModel *AppendChildFromGeometry(const std::string &name, const std::string &parent, const gfx::vertex_array &vertices, const gfx::index_array &indices); void SaveToBinFile(std::string const &FileName); diff --git a/model/eu07m/eu07m_build.cpp b/model/eu07m/eu07m_build.cpp index b282c0652..2dab0498d 100644 --- a/model/eu07m/eu07m_build.cpp +++ b/model/eu07m/eu07m_build.cpp @@ -10,14 +10,17 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "model/eu07m/eu07m_build.h" +#include "model/eu07m/eu07m_store.h" #include #include #include #include +#include #include #include +#include #include namespace eu07m { @@ -314,4 +317,498 @@ void compute_bounds(model &Model) { Model.bounds.push_back(to_bounds(whole, whole.empty() ? 0.f : glm::length(whole.max - whole.centre()))); } +namespace { + +// how the indices of the nodes change: after a node put in at At, those from At on move one place on; after the node At taken +// out, those after it move one place back and At itself is gone +struct node_shift { + std::uint32_t at{0}; + bool removal{false}; + + void operator()(std::uint32_t &Node) const { + if (Node == no_index) + return; + if (false == removal) { + if (Node >= at) + ++Node; + return; + } + if (Node == at) + Node = no_index; + else if (Node > at) + --Node; + } +}; + +template bool read_at(std::span const Data, std::size_t const Offset, Type_ &Value) { + if (Offset + sizeof(Type_) > Data.size()) + return false; + std::memcpy(&Value, Data.data() + Offset, sizeof(Type_)); + return true; +} + +template void write_at(std::span const Data, std::size_t const Offset, Type_ const &Value) { + std::memcpy(Data.data() + Offset, &Value, sizeof(Type_)); +} + +// Count indices from Offset of the data, each given to Visit, which may change it +template void visit_index_list(std::span const Data, std::size_t const Offset, std::size_t const Count, Visit_ const &Visit) { + for (std::size_t idx = 0; idx < Count; ++idx) { + auto const offset{Offset + idx * sizeof(std::uint32_t)}; + std::uint32_t index{0}; + if (false == read_at(Data, offset, index)) + return; + Visit(index); + write_at(Data, offset, index); + } +} + +// the values of the properties of the type (a node, a component), each given to Visit, which may change it +template void visit_properties(std::span const Data, payload::value_type const Type, Visit_ const &Visit) { + std::uint32_t count{0}; + if (false == read_at(Data, 0, count)) + return; + for (std::uint32_t idx = 0; idx < count; ++idx) { + auto const offset{sizeof(std::uint32_t) + idx * sizeof(payload::property)}; + payload::property property; + if (false == read_at(Data, offset, property)) + return; + if (property.type != Type) + continue; + Visit(property.value[0]); + write_at(Data, offset, property); + } +} + +template void visit_spring(std::span const Data, Visit_ const &Visit) { + payload::spring spring; + if (false == read_at(Data, 0, spring)) + return; + Visit(spring.anchor_a); + Visit(spring.anchor_b); + write_at(Data, 0, spring); +} + +template void visit_chain(std::span const Data, Visit_ const &Visit) { + if (payload::chain chain; read_at(Data, 0, chain)) + visit_index_list(Data, sizeof(chain), chain.joint_count, Visit); +} + +template void visit_variants(std::span const Data, Visit_ const &Visit) { + payload::variants variants; + if (false == read_at(Data, 0, variants)) + return; + std::size_t listsize{0}; + for (std::uint32_t idx = 0; idx < variants.state_count; ++idx) { + if (payload::variant_state state; read_at(Data, sizeof(variants) + idx * sizeof(state), state)) + listsize = std::max(listsize, std::size_t{state.node_first} + state.node_count); + } + visit_index_list(Data, sizeof(variants) + variants.state_count * sizeof(payload::variant_state), listsize, Visit); +} + +template void visit_light_slot(std::span const Data, Visit_ const &Visit) { + if (payload::light_slot slot; read_at(Data, 0, slot)) + visit_index_list(Data, sizeof(slot), std::size_t{slot.on_count} + slot.off_count, Visit); +} + +// the data of the component, none when it runs past the data of the model +std::span payload_of(model &Model, component_record const &Record) { + if (std::size_t{Record.data_offset} + Record.data_size > Model.component_data.size()) + return {}; + return {Model.component_data.data() + Record.data_offset, Record.data_size}; +} + +// the nodes in the data of the component, each given to Visit, which may change it +template void visit_payload_nodes(model &Model, component_record const &Record, Visit_ const &Visit) { + auto const data{payload_of(Model, Record)}; + switch (Record.type) { + case component::properties: visit_properties(data, payload::value_type::node, Visit); break; + case component::spring: visit_spring(data, Visit); break; + case component::chain: visit_chain(data, Visit); break; + case component::variants: visit_variants(data, Visit); break; + case component::light_slot: visit_light_slot(data, Visit); break; + default: break; + } +} + +// the light sources of a light slot +template void visit_slot_lights(std::span const Data, Visit_ const &Visit) { + if (payload::light_slot slot; read_at(Data, 0, slot)) + visit_index_list(Data, sizeof(slot) + (std::size_t{slot.on_count} + slot.off_count) * sizeof(std::uint32_t), slot.light_count, Visit); +} + +// the sockets of the two ends of a spring +template void visit_spring_sockets(std::span const Data, Visit_ const &Visit) { + payload::spring spring; + if (false == read_at(Data, 0, spring)) + return; + Visit(spring.socket_a); + Visit(spring.socket_b); + write_at(Data, 0, spring); +} + +// the sockets of the two ends of a chain +template void visit_chain_ends(std::span const Data, Visit_ const &Visit) { + payload::chain chain; + if (false == read_at(Data, 0, chain)) + return; + Visit(chain.end_a); + Visit(chain.end_b); + write_at(Data, 0, chain); +} + +// the socket a model reference is put in at +template void visit_reference_socket(std::span const Data, Visit_ const &Visit) { + payload::model_reference reference; + if (false == read_at(Data, 0, reference)) + return; + Visit(reference.socket); + write_at(Data, 0, reference); +} + +// the targets of the bindings of a channel, those of the clips aside +template void visit_channel_targets(std::span const Data, Visit_ const &Visit) { + payload::channel channel; + if (false == read_at(Data, 0, channel)) + return; + for (std::uint16_t idx = 0; idx < channel.binding_count; ++idx) { + auto const offset{sizeof(channel) + idx * sizeof(payload::channel_binding)}; + payload::channel_binding binding; + if (false == read_at(Data, offset, binding)) + return; + if (binding.kind == payload::binding_kind::clip) + continue; + Visit(binding.target); + write_at(Data, offset, binding); + } +} + +// the components the data of the component points at, each given to Visit, which may change it: the targets of the bindings of a +// channel other than clips, the light sources of a light slot, the sockets of a spring, of the ends of a chain and of a model +// reference, and the properties whose value is a component. no_index (none) is given too +template void visit_payload_components(model &Model, component_record const &Record, Visit_ const &Visit) { + auto const data{payload_of(Model, Record)}; + switch (Record.type) { + case component::light_slot: visit_slot_lights(data, Visit); break; + case component::channel: visit_channel_targets(data, Visit); break; + case component::spring: visit_spring_sockets(data, Visit); break; + case component::chain: visit_chain_ends(data, Visit); break; + case component::model_reference: visit_reference_socket(data, Visit); break; + case component::properties: visit_properties(data, payload::value_type::component, Visit); break; + default: break; + } +} + +// each place but the tree itself where the model points at a node, given to Visit, which may change it: the transforms, the +// primitives, the joints of the skins, the tracks of the clips, the targets of the components and the nodes in their data. the +// roots of the skins are signed, the callers see to them +template void visit_node_references(model &Model, Visit_ const &Visit) { + for (auto &transform : Model.transforms) + Visit(transform.node); + for (auto &primitive : Model.primitives) + Visit(primitive.node); + for (auto &joint : Model.skin_joints) + Visit(joint.node); + for (auto &track : Model.clip_tracks) + Visit(track.node); + for (auto &record : Model.components) { + if (record.kind == target_kind::node) + Visit(record.target); + visit_payload_nodes(Model, record, Visit); + } +} + +// the subtrees which end at At and hold Parent take the new node in; the others after it move on +void shift_subtrees(model &Model, std::int32_t const Parent, std::uint32_t const At) { + std::vector holding(Model.nodes.size(), false); + for (auto node{Parent}; node >= 0 && node < static_cast(Model.nodes.size()); node = Model.nodes[node].parent) + holding[node] = true; + for (std::uint32_t idx = 0; idx < Model.nodes.size(); ++idx) { + auto &node{Model.nodes[idx]}; + if (holding[idx] || node.subtree_end > At) + ++node.subtree_end; + if (node.parent >= static_cast(At)) + ++node.parent; + } +} + +// the mesh of the node, which no other node draws; none when it has none or shares it +std::optional own_mesh(model const &Model, std::uint32_t const Node) { + auto const mesh{Model.nodes[Node].mesh}; + if ((mesh < 0) || (static_cast(mesh) >= Model.meshes.size())) + return std::nullopt; + if (std::ranges::count(Model.nodes, mesh, &node_record::mesh) != 1) + return std::nullopt; + return static_cast(mesh); +} + +// the primitive is one of the mesh +bool in_mesh(model const &Model, std::optional const Mesh, std::uint32_t const Primitive) { + if (false == Mesh.has_value()) + return false; + auto const &mesh{Model.meshes[*Mesh]}; + return (Primitive >= mesh.primitive_first) && (std::size_t{Primitive} < std::size_t{mesh.primitive_first} + mesh.primitive_count); +} + +// something other than what goes with it points at the node: a primitive of another mesh, a skin, a clip, the data of a component, +// a vertex group of its mesh. its own transform, the primitives of its own mesh and its own components go with it +bool node_referenced(model &Model, std::uint32_t const Node) { + auto found{false}; + auto const check = [Node, &found](std::uint32_t const &Index) { found |= (Index == Node); }; + auto const mesh{own_mesh(Model, Node)}; + for (std::uint32_t idx = 0; idx < Model.primitives.size(); ++idx) { + if (false == in_mesh(Model, mesh, idx)) + check(Model.primitives[idx].node); + } + for (auto const &joint : Model.skin_joints) + check(joint.node); + for (auto const &track : Model.clip_tracks) + check(track.node); + for (auto const &record : Model.components) + visit_payload_nodes(Model, record, check); + found |= std::ranges::any_of(Model.skins, [Node](skin_record const &Skin) { return Skin.root == static_cast(Node); }); + if (mesh) + found |= std::ranges::any_of(Model.vertex_groups, [&mesh](vertex_group_record const &Group) { return Group.mesh == *mesh; }); + return found; +} + +// the data of a component other than those Leaving with it points at the component (visit_payload_components()) +bool component_referenced(model &Model, std::uint32_t const Component, std::span const Leaving) { + auto found{false}; + auto const check = [Component, &found](std::uint32_t const &Index) { found |= (Index == Component); }; + for (std::uint32_t idx = 0; idx < Model.components.size(); ++idx) { + if (std::ranges::find(Leaving, idx) == Leaving.end()) + visit_payload_components(Model, Model.components[idx], check); + } + return found; +} + +// a component aimed at the mesh: it would aim at another one once the mesh is taken out +bool mesh_targeted(model const &Model, std::uint32_t const Mesh) { + return std::ranges::any_of(Model.components, [Mesh](component_record const &Record) { return (Record.kind == target_kind::mesh) && (Record.target == Mesh); }); +} + +// the items of the vertex groups past the vertices taken out, Count from First, moved back over them: they are vertices of the +// streams of the file. the groups of the mesh the vertices were of go with it +void shift_vertex_groups(model &Model, std::size_t const First, std::size_t const Count) { + auto const end{First + Count}; + for (auto const &group : Model.vertex_groups) { + auto const ranges{(group.flags & vertex_group_flags::ranges) != 0}; + // an item of ranges is a pair (first, count) in two places: only its first vertex moves + auto const step{ranges ? std::size_t{2} : std::size_t{1}}; + auto const itemend{std::min(std::size_t{group.item_first} + std::size_t{group.item_count} * step, Model.vertex_group_items.size())}; + for (auto item{std::size_t{group.item_first}}; item < itemend; item += step) { + auto &vertex{Model.vertex_group_items[item]}; + if (vertex >= end) + vertex -= static_cast(Count); + } + } +} + +// a range of components after the component taken out of the table +void close_range(std::uint32_t &First, std::uint32_t &Count, std::uint32_t const Component) { + if (First > Component) + --First; + else if (std::size_t{Component} < std::size_t{First} + Count) + --Count; +} + +// the component taken out of the table: the ranges of the nodes and the vertex groups and the references in the data of the others +// close up. its data stays where it is, nothing points at it any more +void erase_component(model &Model, std::uint32_t const Component) { + Model.components.erase(Model.components.begin() + Component); + for (auto &node : Model.nodes) + close_range(node.component_first, node.component_count, Component); + for (auto &group : Model.vertex_groups) + close_range(group.component_first, group.component_count, Component); + auto const close = [Component](std::uint32_t &Index) { + if ((Index != no_index) && (Index > Component)) + --Index; + }; + for (auto const &record : Model.components) + visit_payload_components(Model, record, close); +} + +// the components aimed at the node +std::vector components_of(model const &Model, std::uint32_t const Node) { + std::vector components; + for (std::uint32_t idx = 0; idx < Model.components.size(); ++idx) { + if ((Model.components[idx].kind == target_kind::node) && (Model.components[idx].target == Node)) + components.push_back(idx); + } + return components; +} + +// the range of each vertex stream the model has, Count elements from First, taken out +void cut_vertices(model &Model, std::size_t const First, std::size_t const Count) { + auto const vertices{Model.vertex_count()}; + auto const cut = [vertices, First, Count](auto &Stream) { + if ((Stream.size() == vertices) && (First + Count <= Stream.size())) + Stream.erase(Stream.begin() + static_cast(First), Stream.begin() + static_cast(First + Count)); + }; + // the positions last: the others are checked against their count + cut(Model.vertex_attributes); + cut(Model.weights); + cut(Model.weights_wide); + cut(Model.vertex_userdata); + cut(Model.bindings); + cut(Model.positions); +} + +// the vertices and the indices of the primitive taken out of the streams, when they are its own, and the other primitives after them +// moved back over them; shared ones stay +void cut_geometry(model &Model, std::uint32_t const Primitive) { + if (false == shareable(Model, Primitive)) + return; + auto const removed{Model.primitives[Primitive]}; + auto const vertex_end{std::size_t{removed.base_vertex} + removed.vertex_count}; + auto const vertices{Model.vertex_count()}; + cut_vertices(Model, removed.base_vertex, removed.vertex_count); + if (Model.vertex_count() < vertices) + shift_vertex_groups(Model, removed.base_vertex, removed.vertex_count); + auto const indexed{(removed.flags & primitive_flags::indexed) != 0}; + auto const wide{(removed.flags & primitive_flags::index32) != 0}; + auto const index_end{std::size_t{removed.first_index} + removed.index_count}; + if (indexed && wide && (index_end <= Model.indices32.size())) + Model.indices32.erase(Model.indices32.begin() + removed.first_index, Model.indices32.begin() + static_cast(index_end)); + else if (indexed && (false == wide) && (index_end <= Model.indices16.size())) + Model.indices16.erase(Model.indices16.begin() + removed.first_index, Model.indices16.begin() + static_cast(index_end)); + for (std::uint32_t idx = 0; idx < Model.primitives.size(); ++idx) { + auto &primitive{Model.primitives[idx]}; + if (idx == Primitive) + continue; + if (primitive.base_vertex >= vertex_end) + primitive.base_vertex -= removed.vertex_count; + auto const same_indices{indexed && ((primitive.flags & primitive_flags::indexed) != 0) && (((primitive.flags & primitive_flags::index32) != 0) == wide)}; + if (same_indices && (primitive.first_index >= index_end)) + primitive.first_index -= removed.index_count; + } +} + +// the primitive taken out with its geometry; the meshes and the references to the store after it close up +void erase_primitive(model &Model, std::uint32_t const Primitive) { + cut_geometry(Model, Primitive); + std::erase_if(Model.geometry_references, [Primitive](geometry_reference_record const &Reference) { return Reference.primitive == Primitive; }); + for (auto &reference : Model.geometry_references) { + if (reference.primitive > Primitive) + --reference.primitive; + } + Model.primitives.erase(Model.primitives.begin() + Primitive); + for (auto &mesh : Model.meshes) + close_range(mesh.primitive_first, mesh.primitive_count, Primitive); +} + +// the mesh taken out with its primitives; the meshes after it move back by one +void erase_mesh(model &Model, std::uint32_t const Mesh) { + while (Model.meshes[Mesh].primitive_count > 0) + erase_primitive(Model, Model.meshes[Mesh].primitive_first + Model.meshes[Mesh].primitive_count - 1); + Model.meshes.erase(Model.meshes.begin() + Mesh); + for (auto &node : Model.nodes) { + if (node.mesh > static_cast(Mesh)) + --node.mesh; + } + for (auto &group : Model.vertex_groups) { + if (group.mesh > Mesh) + --group.mesh; + } + // a component aimed at a mesh after it moves back with it; none is aimed at this one (node_removable()) + for (auto &record : Model.components) { + if ((record.kind == target_kind::mesh) && (record.target > Mesh)) + --record.target; + } +} + +} // namespace + +std::uint32_t insert_node(model &Model, std::int32_t const Parent, node_record Node) { + auto const valid_parent{Parent >= 0 && Parent < static_cast(Model.nodes.size())}; + auto const at{valid_parent ? Model.nodes[Parent].subtree_end : static_cast(Model.nodes.size())}; + shift_subtrees(Model, valid_parent ? Parent : -1, at); + visit_node_references(Model, node_shift{at, false}); + for (auto &skin : Model.skins) { + if (skin.root >= static_cast(at)) + ++skin.root; + } + Node.parent = valid_parent ? Parent : -1; + Node.subtree_end = at + 1; + Model.nodes.insert(Model.nodes.begin() + at, Node); + if (false == Model.name_index.empty()) + build_name_index(Model); + if (false == Model.bounds.empty()) + compute_bounds(Model); + return at; +} + +bool node_removable(model &Model, std::uint32_t const Node) { + if ((Node >= Model.nodes.size()) || (Model.nodes[Node].subtree_end != Node + 1) || node_referenced(Model, Node)) + return false; + // geometry which another node draws too stays, and with it the node + if ((Model.nodes[Node].mesh >= 0) && (false == own_mesh(Model, Node).has_value())) + return false; + // so does a mesh a component is aimed at + if (auto const mesh{own_mesh(Model, Node)}; mesh && mesh_targeted(Model, *mesh)) + return false; + // its components go with it: what they point at among themselves doesn't keep it + auto const components{components_of(Model, Node)}; + return std::ranges::none_of(components, [&Model, &components](std::uint32_t const Component) { return component_referenced(Model, Component, components); }); +} + +bool remove_node(model &Model, std::uint32_t const Node) { + if (false == node_removable(Model, Node)) + return false; + // its components first, the last of them first so the indices of the others hold + auto const components{components_of(Model, Node)}; + for (auto component{components.rbegin()}; component != components.rend(); ++component) + erase_component(Model, *component); + // its own transform and its geometry go with it + std::erase_if(Model.transforms, [Node](transform_record const &Transform) { return Transform.node == Node; }); + if (auto const mesh{own_mesh(Model, Node)}) + erase_mesh(Model, *mesh); + Model.nodes[Node].mesh = -1; + visit_node_references(Model, node_shift{Node, true}); + for (auto &skin : Model.skins) { + if (skin.root > static_cast(Node)) + --skin.root; + } + // the subtrees which held it, and those after it, end one place sooner + for (auto &node : Model.nodes) { + if (node.subtree_end > Node) + --node.subtree_end; + if (node.parent > static_cast(Node)) + --node.parent; + } + Model.nodes.erase(Model.nodes.begin() + Node); + if (false == Model.name_index.empty()) + build_name_index(Model); + if (false == Model.bounds.empty()) + compute_bounds(Model); + return true; +} + +std::uint32_t add_component(model &Model, std::uint32_t const Type, target_kind const Kind, std::uint32_t const Target, std::span const Data) { + // the data of each component starts at a multiple of 4 + Model.component_data.resize((Model.component_data.size() + 3) & ~std::size_t{3}); + component_record record; + record.type = Type; + record.kind = Kind; + record.target = Target; + record.data_offset = static_cast(Model.component_data.size()); + record.data_size = static_cast(Data.size()); + Model.component_data.insert(Model.component_data.end(), Data.begin(), Data.end()); + auto const index{static_cast(Model.components.size())}; + Model.components.push_back(record); + auto const list = [index](std::uint32_t &First, std::uint32_t &Count) { + if (Count == 0) { + First = index; + Count = 1; + } + }; + if (Kind == target_kind::node && Target < Model.nodes.size()) + list(Model.nodes[Target].component_first, Model.nodes[Target].component_count); + if (Kind == target_kind::vertex_group && Target < Model.vertex_groups.size()) + list(Model.vertex_groups[Target].component_first, Model.vertex_groups[Target].component_count); + return index; +} + + } // namespace eu07m diff --git a/model/eu07m/eu07m_build.h b/model/eu07m/eu07m_build.h index 1a4e27435..5ed6add15 100644 --- a/model/eu07m/eu07m_build.h +++ b/model/eu07m/eu07m_build.h @@ -16,6 +16,8 @@ http://mozilla.org/MPL/2.0/. #include +#include + namespace eu07m { struct tangent_frame { @@ -51,4 +53,22 @@ std::vector find_nodes(model const &Model, std::string_view Name) // the bounds of every node (its own geometry, in its space) and of the whole model, and the spheres of the primitives void compute_bounds(model &Model); +// puts Node in as the last child of Parent (-1: as the last root) and moves each reference to the nodes after it: the parents and +// the subtrees, the transforms, the primitives, the skins, the tracks of the clips, the targets of the components and the nodes +// in their data. the index of the names and the bounds, where the model has them, are built again. returns the index of the node +std::uint32_t insert_node(model &Model, std::int32_t Parent, node_record Node); +// the node can be taken out: a leaf which nothing points at but what goes with it (its components, its transform, its own mesh), whose +// mesh no other node draws, has no vertex groups and no component aimed at it, and whose components aren't pointed at by the data of +// others (the bindings of a channel, the light sources of a light slot, the sockets of a spring, a chain or a model reference, a +// property whose value is a component) +bool node_removable(model &Model, std::uint32_t Node); +// takes out the node, which node_removable() allows, with its components, its transform and its mesh with the primitives; their +// vertices and indices, where no other primitive shares them, leave the streams. each reference to the nodes, the meshes, the +// primitives, the components and the vertices after them moves back; the data of the components taken out stays unreferenced. the +// index of the names and the bounds, where the model has them, are built again. false, and nothing changed, when it can't be +bool remove_node(model &Model, std::uint32_t Node); +// appends a component of the type aimed at the target, with its data; returns its index. a node or a vertex group without +// components lists it as its range +std::uint32_t add_component(model &Model, std::uint32_t Type, target_kind Kind, std::uint32_t Target, std::span Data); + } // namespace eu07m diff --git a/model/eu07m/eu07m_convert.cpp b/model/eu07m/eu07m_convert.cpp index e1b4ffdbc..40500e0cd 100644 --- a/model/eu07m/eu07m_convert.cpp +++ b/model/eu07m/eu07m_convert.cpp @@ -27,6 +27,9 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include +#include +#include #include #include #include @@ -574,6 +577,47 @@ model convert(TModel3d &Source, std::vector &Faults) { return converter{Source, Faults}.run(); } +std::string import_model(TModel3d &Source, std::string &Error) { + auto const stem{Source.NameGet()}; + auto input{FileCased(stem + ".e3d")}; + if (input.empty()) + input = FileCased(stem + ".t3d"); + if (input.empty()) { + Error = "the model has no .e3d or .t3d file"; + return {}; + } + std::vector faults; + auto converted{convert(Source, faults)}; + if (false == faults.empty()) { + Error = faults.front(); + return {}; + } + auto const file{read_whole_file(input)}; + converted.source_hash = hash_bytes(std::as_bytes(std::span{file.data.get(), file.size})); + converted.edit.push_back({converted.intern(input), converted.intern("editor import"), {}}); + if (auto const problems{validate(converted)}; false == problems.empty()) { + Error = problems.front(); + return {}; + } + auto const output{stem + ".ng3d"}; + auto const temporary{output + ".tmp"}; + auto const bytes{write(converted)}; + std::ofstream stream{temporary, std::ios::binary | std::ios::trunc}; + stream.write(reinterpret_cast(bytes.data()), static_cast(bytes.size())); + // closed before the check: the buffer is written out there, and a fault of it (a full disk) is seen + stream.close(); + std::error_code error; + if (false == stream.fail()) + std::filesystem::rename(temporary, output, error); + if (stream.fail() || error) { + std::filesystem::remove(temporary, error); + Error = std::format("can't write \"{}\"", output); + return {}; + } + WriteLog(std::format("EU07M: {} imported to {}, {} nodes", input, output, converted.nodes.size())); + return output; +} + int run_command_line(int const Argc, char *Argv[]) { std::string_view const command{Argc > 2 ? Argv[2] : ""}; if (command == "convert") diff --git a/model/eu07m/eu07m_convert.h b/model/eu07m/eu07m_convert.h index 904bc8372..6f44147ef 100644 --- a/model/eu07m/eu07m_convert.h +++ b/model/eu07m/eu07m_convert.h @@ -25,6 +25,10 @@ namespace eu07m { // leave the result invalid, are added to Faults, each naming its submodel model convert(TModel3d &Source, std::vector &Faults); +// the EU07M file of the loaded model written beside the file it was loaded from (its .e3d, or else its .t3d), as the convert +// command writes it. returns the path of the file written, or empty with Error saying why +std::string import_model(TModel3d &Source, std::string &Error); + // the -eu07m commands: convert, dump, validate. returns the exit code of the program int run_command_line(int Argc, char *Argv[]); diff --git a/model/eu07m/eu07m_load.cpp b/model/eu07m/eu07m_load.cpp index f30576f54..0e0a86c34 100644 --- a/model/eu07m/eu07m_load.cpp +++ b/model/eu07m/eu07m_load.cpp @@ -47,6 +47,9 @@ static_assert(sizeof(eu07m::attributes) == sizeof(gfx::compact_attributes)); static_assert(offsetof(eu07m::attributes, qtangent) == offsetof(gfx::compact_attributes, qtangent)); static_assert(offsetof(eu07m::attributes, uv) == offsetof(gfx::compact_attributes, texture)); +// the threshold of the self-illumination of a light source without the material of E3D: always lit, as "selfillum: true" of a .t3d +constexpr float light_always_lit{2.f}; + // what E3D keeps in the submodel and EU07M in the components of the node struct legacy_parts { std::optional light; @@ -115,12 +118,12 @@ class submodel_builder { void build(std::uint32_t Index, TSubModel &Submodel); // the vertices and the indices of all the submodels, on several threads for a big model void fill_geometry(); + static void light(eu07m::payload::light const &Light, TSubModel &Submodel); private: void links(std::uint32_t Index, TSubModel &Submodel) const; void transform(std::uint32_t Index, TSubModel &Submodel); void material(std::uint32_t Material, TSubModel &Submodel); - static void light(eu07m::payload::light const &Light, TSubModel &Submodel); void geometry(eu07m::primitive_record const &Primitive, legacy_parts const &Parts, TSubModel &Submodel); void fill(geometry_job const &Job) const; void indices(eu07m::primitive_record const &Primitive, TSubModel &Submodel) const; @@ -166,6 +169,10 @@ void submodel_builder::build(std::uint32_t const Index, TSubModel &Submodel) { if (parts.light) { Submodel.eType = TP_FREESPOTLIGHT; light(*parts.light, Submodel); + // a light source without the material of E3D (made in the editor or exported anew) shines whenever its node is shown, as a + // light of a .t3d with "selfillum: true"; the converter gives every light of E3D its material, with the threshold it had + if (parts.material == eu07m::no_index) + Submodel.fLight = light_always_lit; } if (node.mesh >= 0) { auto const &mesh{m_model.meshes[node.mesh]}; @@ -726,3 +733,85 @@ void TModel3d::stream_geometry(std::string const &FileName, eu07m::model const & GfxRenderer->Stream_Bank(m_geometrybank, std::make_shared(FileName, Hash, std::move(types))); m_streamed = true; } + +void TModel3d::ApplyEU07MLight(TSubModel &Submodel, eu07m::payload::light const &Light) { + submodel_builder::light(Light, Submodel); +} + +TSubModel &TModel3d::AddEditorLight(TSubModel &Parent, std::string const &Name, glm::mat4 const &Local, std::uint32_t const Flags, eu07m::payload::light const &Light) { + auto &submodel{*m_editorsubmodels.emplace_back(std::make_unique())}; + submodel.eType = TP_FREESPOTLIGHT; + submodel.iFlags = Flags; + submodel.pName = Name; + submodel_builder::light(Light, submodel); + // it has no material of E3D: it shines whenever its node is shown, as the loader has it + submodel.fLight = light_always_lit; + submodel.Parent = &Parent; + // the last child, as the node is the last child of its parent in the file + if (Parent.Child == nullptr) { + Parent.Child = &submodel; + } + else { + auto *last{Parent.Child}; + while (last->Next != nullptr) + last = last->Next; + last->Next = &submodel; + } + SetEditorTransform(submodel, Local); + return submodel; +} + +void TModel3d::SetEditorTransform(TSubModel &Submodel, glm::mat4 const &Local) { + if (Submodel.fMatrix == nullptr) + Submodel.fMatrix = m_editormatrices.emplace_back(std::make_unique()).get(); + *Submodel.fMatrix = float4x4(glm::value_ptr(Local)); + Submodel.iFlags |= 0x8000; + submodels_changed(); +} + +void TModel3d::SetEditorRange(TSubModel &Submodel, float const MinSq, float const MaxSq) { + Submodel.fSquareMinDist = MinSq; + Submodel.fSquareMaxDist = MaxSq > 0.f ? MaxSq : TSubModel{}.fSquareMaxDist; + submodels_changed(); +} + +TSubModel *TModel3d::UnlinkEditorSubmodel(TSubModel &Submodel) { + auto *parent{Submodel.Parent}; + if (parent == nullptr) + return nullptr; + TSubModel *previous{nullptr}; + auto *child{parent->Child}; + while ((child != nullptr) && (child != &Submodel)) { + previous = child; + child = child->Next; + } + if (child == nullptr) + return nullptr; + if (previous == nullptr) + parent->Child = Submodel.Next; + else + previous->Next = Submodel.Next; + Submodel.Next = nullptr; + submodels_changed(); + return previous; +} + +void TModel3d::LinkEditorSubmodel(TSubModel &Submodel, TSubModel &Parent, TSubModel *Previous) { + Submodel.Parent = &Parent; + if (Previous == nullptr) { + Submodel.Next = Parent.Child; + Parent.Child = &Submodel; + } + else { + Submodel.Next = Previous->Next; + Previous->Next = &Submodel; + } + submodels_changed(); +} + +void TModel3d::submodels_changed() { + if (Root != nullptr) + iFlags |= Root->FlagsCheck(); + m_lodboundsfound = false; + state_changed(); +} diff --git a/tests/unit/test_eu07m_edit.cpp b/tests/unit/test_eu07m_edit.cpp new file mode 100644 index 000000000..59693bb4c --- /dev/null +++ b/tests/unit/test_eu07m_edit.cpp @@ -0,0 +1,308 @@ +#include "stdafx.h" + +#include "doctest.h" + +#include "model/eu07m/eu07m_build.h" +#include "model/eu07m/eu07m_io.h" + +#include +#include + +namespace { + +// root (0) { lamp (1), door (2) }, rear (3); a light slot of the root lists the door and the rear node, a joint is aimed at the +// rear node and a clip moves it +eu07m::model lamp_model() { + eu07m::model model; + auto const node = [&model](std::string_view const Name, std::int32_t const Parent, std::uint32_t const End) { + eu07m::node_record record; + record.name = model.intern(Name); + record.parent = Parent; + record.subtree_end = End; + model.nodes.push_back(record); + }; + node("root", -1, 3); + node("lamp", 0, 2); + node("door", 0, 3); + node("rear", -1, 4); + eu07m::payload::light_slot slot; + slot.on_count = 1; + slot.off_count = 1; + std::vector data(sizeof(slot) + 2 * sizeof(std::uint32_t)); + std::memcpy(data.data(), &slot, sizeof(slot)); + std::uint32_t const lit{2}; + std::uint32_t const dark{3}; + std::memcpy(data.data() + sizeof(slot), &lit, sizeof(lit)); + std::memcpy(data.data() + sizeof(slot) + sizeof(lit), &dark, sizeof(dark)); + eu07m::add_component(model, eu07m::component::light_slot, eu07m::target_kind::node, 0, data); + eu07m::payload::joint joint; + std::vector jointdata(sizeof(joint)); + std::memcpy(jointdata.data(), &joint, sizeof(joint)); + eu07m::add_component(model, eu07m::component::joint, eu07m::target_kind::node, 3, jointdata); + eu07m::clip_record clip; + clip.name = model.intern("open"); + clip.track_first = 0; + clip.track_count = 1; + model.clips.push_back(clip); + eu07m::track_record track; + track.node = 3; + track.key_count = 1; + model.clip_tracks.push_back(track); + model.key_times.push_back(0.f); + model.key_vectors.push_back({0.f, 0.f, 0.f}); + eu07m::build_name_index(model); + return model; +} + +std::uint32_t listed_node(eu07m::model const &Model, std::uint32_t const Component, std::size_t const Item) { + std::uint32_t node{0}; + std::memcpy(&node, Model.component_data.data() + Model.components[Component].data_offset + sizeof(eu07m::payload::light_slot) + Item * sizeof(node), sizeof(node)); + return node; +} + +} // namespace + +TEST_CASE("eu07m: a node put in under a parent moves the references to the nodes after it") { + auto model{lamp_model()}; + REQUIRE(eu07m::validate(model).empty()); + eu07m::node_record light; + light.name = model.intern("light_1"); + auto const index{eu07m::insert_node(model, 0, light)}; + CHECK(index == 3); + REQUIRE(model.nodes.size() == 5); + // the root holds it, the lamp and the door keep their subtrees, the rear node moves on + CHECK(model.nodes[0].subtree_end == 4); + CHECK(model.nodes[1].subtree_end == 2); + CHECK(model.nodes[2].subtree_end == 3); + CHECK(model.nodes[3].parent == 0); + CHECK(model.nodes[3].subtree_end == 4); + CHECK(model.string(model.nodes[4].name) == "rear"); + CHECK(model.nodes[4].parent == -1); + CHECK(model.nodes[4].subtree_end == 5); + // the joint, the track and the light slot follow the rear node; the door stays + CHECK(model.components[1].target == 4); + CHECK(model.clip_tracks[0].node == 4); + CHECK(listed_node(model, 0, 0) == 2); + CHECK(listed_node(model, 0, 1) == 4); + CHECK(eu07m::find_nodes(model, "light_1") == std::vector{3}); + CHECK(eu07m::find_nodes(model, "rear") == std::vector{4}); + CHECK(eu07m::validate(model).empty()); +} + +TEST_CASE("eu07m: a node put in without a parent goes last, and a component added is listed by it") { + auto model{lamp_model()}; + eu07m::node_record light; + light.name = model.intern("light_2"); + auto const index{eu07m::insert_node(model, -1, light)}; + CHECK(index == 4); + CHECK(model.nodes[3].subtree_end == 4); + CHECK(model.nodes[4].subtree_end == 5); + eu07m::payload::light payload; + std::vector data(sizeof(payload)); + std::memcpy(data.data(), &payload, sizeof(payload)); + auto const component{eu07m::add_component(model, eu07m::component::light, eu07m::target_kind::node, index, data)}; + CHECK(model.nodes[index].component_first == component); + CHECK(model.nodes[index].component_count == 1); + CHECK(model.components[component].data_offset % 4 == 0); + CHECK(eu07m::validate(model).empty()); + // the file written and read again holds the same + eu07m::model read; + REQUIRE(eu07m::read(eu07m::write(model), read).ok); + CHECK(read.nodes.size() == 5); + CHECK(read.components.size() == 3); +} + +TEST_CASE("eu07m: a light put in and taken out again leaves the model as it was") { + auto model{lamp_model()}; + auto const before{model.nodes}; + eu07m::node_record light; + light.name = model.intern("light_3"); + auto const index{eu07m::insert_node(model, 0, light)}; + eu07m::payload::light payload; + std::vector data(sizeof(payload)); + std::memcpy(data.data(), &payload, sizeof(payload)); + eu07m::add_component(model, eu07m::component::light, eu07m::target_kind::node, index, data); + REQUIRE(eu07m::node_removable(model, index)); + REQUIRE(eu07m::remove_node(model, index)); + REQUIRE(model.nodes.size() == before.size()); + for (std::size_t idx = 0; idx < before.size(); ++idx) { + CHECK(model.nodes[idx].parent == before[idx].parent); + CHECK(model.nodes[idx].subtree_end == before[idx].subtree_end); + CHECK(model.nodes[idx].name == before[idx].name); + } + // the components of the light are gone, the others point where they did + REQUIRE(model.components.size() == 2); + CHECK(model.components[1].target == 3); + CHECK(model.clip_tracks[0].node == 3); + CHECK(listed_node(model, 0, 0) == 2); + CHECK(listed_node(model, 0, 1) == 3); + CHECK(eu07m::find_nodes(model, "rear") == std::vector{3}); + CHECK(eu07m::validate(model).empty()); +} + +TEST_CASE("eu07m: a node with children, or one something points at, isn't taken out") { + auto model{lamp_model()}; + auto const nodes{model.nodes.size()}; + // the root has children, the door is listed by the light slot, the rear node is moved by a clip + CHECK_FALSE(eu07m::remove_node(model, 0)); + CHECK_FALSE(eu07m::remove_node(model, 2)); + CHECK_FALSE(eu07m::remove_node(model, 3)); + CHECK_FALSE(eu07m::remove_node(model, 9)); + CHECK(model.nodes.size() == nodes); + // the lamp is a leaf nothing points at + CHECK(eu07m::remove_node(model, 1)); + CHECK(model.nodes.size() == nodes - 1); + CHECK(model.nodes[0].subtree_end == 2); + CHECK(listed_node(model, 0, 0) == 1); + CHECK(listed_node(model, 0, 1) == 2); + CHECK(eu07m::validate(model).empty()); +} + +namespace { + +// root (0) { decal (1), lamp (2) }: the decal and the lamp have a triangle of their own each, the lamp's after the decal's in the +// streams; a vertex has a position and its attributes +eu07m::model geometry_model() { + eu07m::model model; + auto const node = [&model](std::string_view const Name, std::int32_t const Parent, std::uint32_t const End, std::int32_t const Mesh) { + eu07m::node_record record; + record.name = model.intern(Name); + record.parent = Parent; + record.subtree_end = End; + record.mesh = Mesh; + model.nodes.push_back(record); + }; + node("root", -1, 3, -1); + node("decal", 0, 2, 0); + node("lamp", 0, 3, 1); + for (std::uint32_t mesh = 0; mesh < 2; ++mesh) { + eu07m::mesh_record record; + record.primitive_first = mesh; + record.primitive_count = 1; + model.meshes.push_back(record); + eu07m::primitive_record primitive; + primitive.first_index = mesh * 3; + primitive.index_count = 3; + primitive.base_vertex = mesh * 3; + primitive.vertex_count = 3; + primitive.node = mesh + 1; + primitive.flags = static_cast(eu07m::topology::triangles) | eu07m::primitive_flags::indexed | eu07m::primitive_flags::opaque; + model.primitives.push_back(primitive); + for (std::uint16_t vertex = 0; vertex < 3; ++vertex) { + model.positions.push_back({static_cast(mesh), static_cast(vertex), 0.f}); + model.vertex_attributes.emplace_back(); + model.indices16.push_back(vertex); + } + } + eu07m::build_name_index(model); + return model; +} + +} // namespace + +TEST_CASE("eu07m: a part taken out takes its geometry, and the parts after it move into its place") { + auto model{geometry_model()}; + REQUIRE(eu07m::validate(model).empty()); + REQUIRE(eu07m::node_removable(model, 1)); + REQUIRE(eu07m::remove_node(model, 1)); + REQUIRE(model.nodes.size() == 2); + CHECK(model.string(model.nodes[1].name) == "lamp"); + CHECK(model.nodes[0].subtree_end == 2); + REQUIRE(model.meshes.size() == 1); + CHECK(model.nodes[1].mesh == 0); + REQUIRE(model.primitives.size() == 1); + CHECK(model.meshes[0].primitive_first == 0); + CHECK(model.primitives[0].base_vertex == 0); + CHECK(model.primitives[0].first_index == 0); + CHECK(model.primitives[0].node == 1); + // the lamp's vertices are the ones left + REQUIRE(model.positions.size() == 3); + CHECK(model.positions[0][0] == 1.f); + CHECK(model.vertex_attributes.size() == 3); + CHECK(model.indices16.size() == 3); + CHECK(eu07m::validate(model).empty()); + eu07m::model read; + REQUIRE(eu07m::read(eu07m::write(model), read).ok); + CHECK(read.primitives.size() == 1); +} + +TEST_CASE("eu07m: a part whose mesh another part draws too isn't taken out") { + auto model{geometry_model()}; + model.nodes[2].mesh = 0; + CHECK_FALSE(eu07m::node_removable(model, 1)); + CHECK_FALSE(eu07m::remove_node(model, 1)); + CHECK(model.primitives.size() == 2); +} + +TEST_CASE("eu07m: the vertex groups of a mesh after a part taken out follow its vertices") { + auto model{geometry_model()}; + // two groups of the lamp's mesh: vertices 3 and 5, and the range of its three vertices from 3 + model.vertex_group_items = {3, 5, 3, 3}; + model.vertex_groups.push_back({model.intern("tip"), 1, 0, 2, 0, 0, 0, 0}); + model.vertex_groups.push_back({model.intern("whole"), 1, 2, 1, eu07m::vertex_group_flags::ranges, 0, 0, 0}); + REQUIRE(eu07m::validate(model).empty()); + REQUIRE(eu07m::remove_node(model, 1)); + REQUIRE(model.positions.size() == 3); + CHECK(model.vertex_groups[0].mesh == 0); + CHECK(model.vertex_group_items == std::vector{0, 2, 0, 3}); + CHECK(eu07m::validate(model).empty()); +} + +TEST_CASE("eu07m: a component aimed at a mesh keeps its mesh, and keeps it from being taken out") { + auto model{geometry_model()}; + auto const collision{eu07m::add_component(model, eu07m::component::collision, eu07m::target_kind::mesh, 1, eu07m::payload_writer{}.put(eu07m::payload::collision{}).data())}; + // the lamp's mesh is aimed at: the lamp stays + CHECK_FALSE(eu07m::node_removable(model, 2)); + // the decal's mesh goes, the one aimed at moves back into its place + REQUIRE(eu07m::remove_node(model, 1)); + CHECK(model.components[collision].target == 0); + CHECK(model.nodes[1].mesh == 0); + CHECK(eu07m::validate(model).empty()); +} + +TEST_CASE("eu07m: the sockets the data of the components points at follow a component taken out before them") { + auto model{geometry_model()}; + // the decal has a light (component 0), the lamp a socket (1); a spring, a chain, a model reference and a property of the root + // point at the socket + eu07m::add_component(model, eu07m::component::light, eu07m::target_kind::node, 1, eu07m::payload_writer{}.put(eu07m::payload::light{}).data()); + auto const socket{eu07m::add_component(model, eu07m::component::socket, eu07m::target_kind::node, 2, eu07m::payload_writer{}.put(eu07m::payload::socket{}).data())}; + REQUIRE(socket == 1); + eu07m::payload::spring spring; + spring.anchor_a = 0; + spring.socket_a = socket; + spring.anchor_b = 0; + auto const springs{eu07m::add_component(model, eu07m::component::spring, eu07m::target_kind::node, 0, eu07m::payload_writer{}.put(spring).data())}; + eu07m::payload::chain chain; + chain.end_b = socket; + auto const chains{eu07m::add_component(model, eu07m::component::chain, eu07m::target_kind::model, 0, eu07m::payload_writer{}.put(chain).data())}; + eu07m::payload::model_reference reference; + reference.path = model.intern("dynamic/x/hose"); + reference.socket = socket; + auto const references{eu07m::add_component(model, eu07m::component::model_reference, eu07m::target_kind::model, 0, eu07m::payload_writer{}.put(reference).data())}; + eu07m::payload::property property; + property.key = model.intern("plug"); + property.type = eu07m::payload::value_type::component; + property.value[0] = socket; + auto const properties{eu07m::add_component(model, eu07m::component::properties, eu07m::target_kind::model, 0, eu07m::payload_writer{}.put(std::uint32_t{1}).put(property).data())}; + REQUIRE(eu07m::validate(model).empty()); + // the lamp's socket is pointed at: the lamp stays + CHECK_FALSE(eu07m::node_removable(model, 2)); + // the decal goes with its light: the socket is component 0 now, and so is what points at it + REQUIRE(eu07m::remove_node(model, 1)); + auto const read = [&model](std::uint32_t const Component, Payload_ &Payload) { + auto const &record{model.components[Component]}; + std::memcpy(&Payload, model.component_data.data() + record.data_offset, sizeof(Payload)); + }; + read(springs - 1, spring); + CHECK(spring.socket_a == 0); + CHECK(spring.socket_b == eu07m::no_index); + read(chains - 1, chain); + CHECK(chain.end_a == eu07m::no_index); + CHECK(chain.end_b == 0); + read(references - 1, reference); + CHECK(reference.socket == 0); + eu07m::payload::property moved; + std::memcpy(&moved, model.component_data.data() + model.components[properties - 1].data_offset + sizeof(std::uint32_t), sizeof(moved)); + CHECK(moved.value[0] == 0); + CHECK(eu07m::validate(model).empty()); +} diff --git a/vehicle/AirCoupler.h b/vehicle/AirCoupler.h index 2de380fad..1587935f2 100644 --- a/vehicle/AirCoupler.h +++ b/vehicle/AirCoupler.h @@ -31,6 +31,11 @@ public: ///Loads info about coupler. void Load(cParser *Parser, TModel3d *Model); int GetStatus() const; + // whether the submodel is one of those the coupler shows + bool is_part(TSubModel const *Submodel) const + { + return (Submodel != nullptr) && ((Submodel == ModelOn) || (Submodel == ModelOff) || (Submodel == ModelxOn)); + } inline void TurnOn() ///Turns on straight coupler. { On = true; diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index adf70bb18..6025868cd 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -906,6 +906,7 @@ public: TDimension const &Dimensions() const; double Speed() const; // along the vehicle, signed [m/s] int ActiveCab() const; // the cab the vehicle is driven from: 1 the front one, -1 the rear one, 0 none + int OccupiedCab() const; // the cab the crew is in: 1 the front one, -1 the rear one, 0 none float CompartmentLightIntensity() const; double CouplerAdapterHeight( VehicleEnd End ) const; double CouplerAdapterLength( VehicleEnd End ) const; @@ -991,6 +992,41 @@ public: void SetLightDimmings(); void RaLightsSet(int head, int rear); int LightList( VehicleEnd const Side ) const { return iInventory[ Side ]; } + // the hold of the editor on parts of the vehicle (the EU07M model window): the lamps, the coupler hooks and the hoses shown in + // a state of its choice, and the pantographs held up or down, whatever the vehicle does with them. nothing is held at first + enum class part_hold : std::uint8_t { none, off, on, xon }; + enum class pantograph_hold : std::uint8_t { none, down, up }; + static constexpr std::size_t held_part_total{ 24 }; + // the name of the part, as its submodels are named in the model (headlamp11 for headlamp11_on and the like) + static char const *held_part_name( std::size_t Part ); + // whether the model of the vehicle has the part + bool held_part_present( std::size_t Part ) const; + part_hold held_part( std::size_t Part ) const { return m_heldparts[ Part ]; } + void hold_part( std::size_t Part, part_hold Hold ) { m_heldparts[ Part ] = Hold; } + // the part the submodel is, or is in; held_part_total when it's none of them + std::size_t part_of( TSubModel const *Submodel ) const; + int pantograph_count() const; + pantograph_hold held_pantograph( int Pantograph ) const { return m_heldpantographs[ Pantograph ]; } + // held up or down, the pantograph goes there at its own pace, to the wire above it if there's one + void hold_pantograph( int Pantograph, pantograph_hold Hold ); + // moves the held pantographs on by the time, where the simulation stands still (the editor) + void step_held_pantographs( double Timedelta ); + // the pantograph the submodel is an arm of, or is in; -1 when it's none + int pantograph_of( TSubModel const *Submodel ) const; + // every hold let go of: the parts and the pantographs are the vehicle's own again (the editor closed, another vehicle picked) + void release_holds(); + private: + struct held_part_entry { + char const *name; + AirCoupler TDynamicObject::*part; + }; + static std::array const &held_part_table(); + // the parts held by the editor shown as it holds them, after the vehicle has set them; true when any is held + bool apply_held_parts(); + static void move_pantograph( TAnimPant &Pantograph, bool Up, double Timedelta ); + std::array m_heldparts {}; + std::array m_heldpantographs {}; + public: bool has_signal_pc1_on() const; bool has_signal_pc2_on() const; bool has_signal_pc5_on() const; diff --git a/vehicle/dynamic/lights.cpp b/vehicle/dynamic/lights.cpp index 0549ff63f..38e2097e0 100644 --- a/vehicle/dynamic/lights.cpp +++ b/vehicle/dynamic/lights.cpp @@ -263,6 +263,10 @@ int TDynamicObject::ActiveCab() const { return physics->CabActive; } +int TDynamicObject::OccupiedCab() const { + return physics->CabOccupied(); +} + float TDynamicObject::CompartmentLightIntensity() const { return physics->CompartmentLights.intensity; } diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp index 398fe1241..5b2e32e9c 100644 --- a/vehicle/dynamic/update.cpp +++ b/vehicle/dynamic/update.cpp @@ -776,6 +776,12 @@ void TDynamicObject::updatePantographVoltage( int const i, TAnimPant const *p, d // the arms of one pantograph raised by the pressure towards the wire, or lowered void TDynamicObject::updatePantographMotion( int const i, TAnimPant *p, double const PantDiff, double const dt1 ) { + // held by the editor, the pantograph goes where it was put, whatever the air and the switches + if( ( i < static_cast( m_heldpantographs.size() ) ) + && ( m_heldpantographs[ i ] != pantograph_hold::none ) ) { + move_pantograph( *p, m_heldpantographs[ i ] == pantograph_hold::up, dt1 ); + return; + } double k; // tymczasowy kąt if( physics->pantographAir.Pressure() > ( physics->TrainType() == train_type::emu ? diff --git a/vehicle/dynamic/visual.cpp b/vehicle/dynamic/visual.cpp index 7beef31e2..0ac5a45be 100644 --- a/vehicle/dynamic/visual.cpp +++ b/vehicle/dynamic/visual.cpp @@ -581,6 +581,10 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) else m_highbeam22.TurnOff(); } + // the parts the editor holds, over what the vehicle has set + if( apply_held_parts() ) { + btnOn = true; + } // interior light levels auto sectionlightcolor { glm::vec4( 1.f ) }; bool cabsection{ true }; @@ -786,3 +790,134 @@ TDynamicObject::shake_between( double const Fraction ) const { between( ShakeStateBefore.velocity, ShakeState.velocity, part ), between( ShakeStateBefore.offset, ShakeState.offset, part ) }; } + +std::array const &TDynamicObject::held_part_table() { + static std::array const table { { + { "coupler1", &TDynamicObject::btCoupler1 }, + { "coupler2", &TDynamicObject::btCoupler2 }, + { "cpneumatic1", &TDynamicObject::btCPneumatic1 }, + { "cpneumatic1r", &TDynamicObject::btCPneumatic1r }, + { "cpneumatic2", &TDynamicObject::btCPneumatic2 }, + { "cpneumatic2r", &TDynamicObject::btCPneumatic2r }, + { "pneumatic1", &TDynamicObject::btPneumatic1 }, + { "pneumatic1r", &TDynamicObject::btPneumatic1r }, + { "pneumatic2", &TDynamicObject::btPneumatic2 }, + { "pneumatic2r", &TDynamicObject::btPneumatic2r }, + { "headlamp11", &TDynamicObject::m_headlamp11 }, + { "headlamp12", &TDynamicObject::m_headlamp12 }, + { "headlamp13", &TDynamicObject::m_headlamp13 }, + { "highbeam12", &TDynamicObject::m_highbeam12 }, + { "highbeam13", &TDynamicObject::m_highbeam13 }, + { "headsignal12", &TDynamicObject::m_headsignal12 }, + { "headsignal13", &TDynamicObject::m_headsignal13 }, + { "headlamp21", &TDynamicObject::m_headlamp21 }, + { "headlamp22", &TDynamicObject::m_headlamp22 }, + { "headlamp23", &TDynamicObject::m_headlamp23 }, + { "highbeam22", &TDynamicObject::m_highbeam22 }, + { "highbeam23", &TDynamicObject::m_highbeam23 }, + { "headsignal22", &TDynamicObject::m_headsignal22 }, + { "headsignal23", &TDynamicObject::m_headsignal23 } } }; + return table; +} + +char const *TDynamicObject::held_part_name( std::size_t const Part ) { + return held_part_table()[ Part ].name; +} + +bool TDynamicObject::held_part_present( std::size_t const Part ) const { + return ( this->*( held_part_table()[ Part ].part ) ).Active(); +} + +std::size_t TDynamicObject::part_of( TSubModel const *Submodel ) const { + auto const &table { held_part_table() }; + for( auto const *submodel { Submodel }; submodel != nullptr; submodel = submodel->Parent ) { + auto const found { std::ranges::find_if( table, [ this, submodel ]( held_part_entry const &Entry ) { return ( this->*( Entry.part ) ).is_part( submodel ); } ) }; + if( found != table.end() ) { + return static_cast( std::distance( table.begin(), found ) ); + } + } + return held_part_total; +} + +bool TDynamicObject::apply_held_parts() { + auto held { false }; + auto const &table { held_part_table() }; + for( std::size_t idx = 0; idx < table.size(); ++idx ) { + auto &part { this->*( table[ idx ].part ) }; + switch( m_heldparts[ idx ] ) { + case part_hold::off: { part.TurnOff(); break; } + case part_hold::on: { part.TurnOn(); break; } + case part_hold::xon: { part.TurnxOn(); break; } + default: { continue; } + } + held = true; + } + return held; +} + +int TDynamicObject::pantograph_count() const { + return std::min( iAnimType[ ANIM_PANTS ], static_cast( m_heldpantographs.size() ) ); +} + +void TDynamicObject::hold_pantograph( int const Pantograph, pantograph_hold const Hold ) { + if( ( Pantograph < 0 ) || ( Pantograph >= pantograph_count() ) ) { + return; + } + m_heldpantographs[ Pantograph ] = Hold; +} + +void TDynamicObject::step_held_pantographs( double const Timedelta ) { + if( pants == nullptr ) { + return; + } + for( int idx = 0; idx < pantograph_count(); ++idx ) { + if( ( m_heldpantographs[ idx ] != pantograph_hold::none ) && ( pants[ idx ].fParamPants != nullptr ) ) { + move_pantograph( *pants[ idx ].fParamPants, m_heldpantographs[ idx ] == pantograph_hold::up, Timedelta ); + } + } +} + +int TDynamicObject::pantograph_of( TSubModel const *Submodel ) const { + if( pants == nullptr ) { + return -1; + } + for( auto const *submodel { Submodel }; submodel != nullptr; submodel = submodel->Parent ) { + for( int idx = 0; idx < pantograph_count(); ++idx ) { + auto const *arms { pants[ idx ].smElement }; + if( ( arms != nullptr ) && std::ranges::find( arms, arms + 5, submodel ) != arms + 5 ) { + return idx; + } + } + } + return -1; +} + +void TDynamicObject::move_pantograph( TAnimPant &Pantograph, bool const Up, double const Timedelta ) { + // the upper arm follows the lower one, and the height follows both, as the pantograph moves in Update() + auto const upper = [ &Pantograph ]( double const Lower ) { + return std::acos( std::clamp( ( Pantograph.fLenL1 * std::cos( Lower ) + Pantograph.fHoriz ) / Pantograph.fLenU1, -1.0, 1.0 ) ); }; + auto const height = [ &Pantograph, &upper ]( double const Lower ) { + return Pantograph.fLenL1 * std::sin( Lower ) + Pantograph.fLenU1 * std::sin( upper( Lower ) ) + Pantograph.fHeight; }; + // the angle of the lower arm it goes to: down at rest, up at the wire it has, or without one 1.6 m over its rest, and no + // further than the arms reach + auto target { Pantograph.fAngleL0 }; + if( Up ) { + auto const top { Pantograph.hvPowerWire != nullptr ? Pantograph.PantTraction : height( target ) + 1.6 }; + constexpr double step { 0.002 }; + while( ( height( target ) < top ) && ( target + step + upper( target + step ) < std::numbers::pi ) ) { + target += step; + } + } + // a few seconds from the rest to the wire, a little slower down, as the air moves it + auto const pace { ( Up ? 0.3 : 0.2 ) * std::max( 0.0, Timedelta ) }; + auto lower { Pantograph.fAngleL }; + lower = lower < target ? std::min( lower + pace, target ) : std::max( lower - pace, target ); + Pantograph.fAngleL = lower; + Pantograph.fAngleU = upper( lower ); + Pantograph.PantWys = height( lower ); +} + +void TDynamicObject::release_holds() { + m_heldparts.fill( part_hold::none ); + m_heldpantographs.fill( pantograph_hold::none ); +}