Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move ship view to python (partial) #899

Merged
merged 13 commits into from
Nov 1, 2024
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions engine/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ IF (UNIX)
${Vega_Strike_SOURCE_DIR}/src/damage
${Vega_Strike_SOURCE_DIR}/src/resource
${Vega_Strike_SOURCE_DIR}/src/components
${Vega_Strike_SOURCE_DIR}/src/python/base_computer
${Vega_Strike_SOURCE_DIR}/src/python/config
${Vega_Strike_BINARY_DIR}
${Vega_Strike_BINARY_DIR}/src
Expand All @@ -178,6 +179,7 @@ ELSE ()
${Vega_Strike_SOURCE_DIR}/src/damage
${Vega_Strike_SOURCE_DIR}/src/resource
${Vega_Strike_SOURCE_DIR}/src/components
${Vega_Strike_SOURCE_DIR}/src/python/base_computer
${Vega_Strike_SOURCE_DIR}/src/python/config
${Vega_Strike_BINARY_DIR}
${Vega_Strike_BINARY_DIR}/src
Expand Down Expand Up @@ -769,6 +771,8 @@ SET(LIBPYTHON_SOURCES
src/python/unit_method_defs.cpp
src/python/unit_wrapper.cpp
src/python/universe_util_export.cpp

src/python/base_computer/ship_view.cpp
)

SET(LIBSCRIPT_SOURCES
Expand Down
231 changes: 21 additions & 210 deletions engine/src/cmd/basecomputer.cpp

Large diffs are not rendered by default.

91 changes: 42 additions & 49 deletions engine/src/cmd/unit_csv.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
#include "resource/resource.h"
#include "unit_csv_factory.h"
#include "upgradeable_unit.h"
#include "resource/manifest.h"

extern int GetModeFromName(const char *input_buffer);
extern void pushMesh(std::vector<Mesh *> &mesh,
Expand Down Expand Up @@ -643,6 +644,13 @@ void Unit::LoadRow(std::string unit_identifier, string modification, bool saved_
string tmpstr;
csvRow = unit_identifier;

// Textual Descriptions
this->unit_key = unit_identifier;
this->unit_name = UnitCSVFactory::GetVariable(unit_key, "Name", std::string());
this->unit_description = Manifest::MPL().GetShipDescription(unit_identifier);

// This shadows the unit variable. It also doesn't support more than one ship.
// TODO: figure this out.
std::string unit_key = (saved_game ? "player_ship" : unit_identifier);

fullname = UnitCSVFactory::GetVariable(unit_key, "Name", std::string());
Expand Down Expand Up @@ -1095,42 +1103,32 @@ CSVRow GetUnitRow(string filename, bool subu, int faction, bool readlast, bool &
}

void Unit::WriteUnit(const char *modifications) {
const bool UNITTAB = configuration()->physics_config.unit_table;
if (UNITTAB) {
bool bad = false;
if (!modifications) {
bool bad = false;
if (!modifications) {
bad = true;
}
if (!bad) {
if (!strlen(modifications)) {
bad = true;
}
if (!bad) {
if (!strlen(modifications)) {
bad = true;
}
}
if (bad) {
VS_LOG(error,
(boost::format("Cannot Write out unit file %1% %2% that has no filename") % name.get().c_str()
% csvRow.get().c_str()));
return;
}
std::string savedir = modifications;
VSFileSystem::CreateDirectoryHome(VSFileSystem::savedunitpath + "/" + savedir);
VSFileSystem::VSFile f;
VSFileSystem::VSError err = f.OpenCreateWrite(savedir + "/" + name + ".csv", VSFileSystem::UnitFile);
if (err > VSFileSystem::Ok) {
VS_LOG(error, (boost::format("!!! ERROR : Writing saved unit file : %1%") % f.GetFullPath().c_str()));
return;
}
std::string towrite = WriteUnitString();
f.Write(towrite.c_str(), towrite.length());
f.Close();
} else {
if (pImage->unitwriter) {
pImage->unitwriter->Write(modifications);
}
for (un_iter ui = getSubUnits(); (*ui) != NULL; ++ui) {
(*ui)->WriteUnit(modifications);
}
}
if (bad) {
VS_LOG(error,
(boost::format("Cannot Write out unit file %1% %2% that has no filename") % name.get().c_str()
% csvRow.get().c_str()));
return;
}
std::string savedir = modifications;
VSFileSystem::CreateDirectoryHome(VSFileSystem::savedunitpath + "/" + savedir);
VSFileSystem::VSFile f;
VSFileSystem::VSError err = f.OpenCreateWrite(savedir + "/" + name + ".csv", VSFileSystem::UnitFile);
if (err > VSFileSystem::Ok) {
VS_LOG(error, (boost::format("!!! ERROR : Writing saved unit file : %1%") % f.GetFullPath().c_str()));
return;
}
std::string towrite = WriteUnitString();
f.Write(towrite.c_str(), towrite.length());
f.Close();
}

using XMLSupport::tostring;
Expand All @@ -1154,24 +1152,15 @@ static string tos(int val) {
return XMLSupport::tostring(val);
}

string Unit::WriteUnitString() {
const bool UNITTAB = configuration()->physics_config.unit_table;
string ret = "";
if (!UNITTAB) {
// Is this code doing something? Is it legacy?
// TODO: figure this out
if (pImage->unitwriter) {
ret = pImage->unitwriter->WriteString();
}
for (un_iter ui = getSubUnits(); (*ui) != NULL; ++ui) {
ret = ret + ((*ui)->WriteUnitString());
}
return ret;
}

std::map<std::string, std::string> Unit::UnitToMap() {
std::map<std::string, std::string> unit = UnitCSVFactory::GetUnit(name);
string val;

// Textual Descriptions
unit["Key"] = unit_key;
unit["Name"] = unit_name;
unit["Textual_Description"] = unit_description; // Used in ship view

//mutable things
unit["Equipment_Space"] = XMLSupport::tostring(equipment_volume);
unit["Hold_Volume"] = XMLSupport::tostring(CargoVolume);
Expand Down Expand Up @@ -1374,7 +1363,7 @@ string Unit::WriteUnitString() {
unit["Afterburner_Speed_Governor"] = tos(computer.max_combat_ab_speed / game_speed);
unit["ITTS"] = tos(computer.itts);
unit["Can_Lock"] = tos(computer.radar.canlock);
unit["Radar_Color"] = tos(computer.radar.capability);
unit["Radar_Color"] = std::to_string(computer.radar.capability);
unit["Radar_Range"] = tos(computer.radar.maxrange);
unit["Tracking_Cone"] = tos(acos(computer.radar.trackingcone) * 180. / VS_PI);
unit["Max_Cone"] = tos(acos(computer.radar.maxcone) * 180. / VS_PI);
Expand Down Expand Up @@ -1413,6 +1402,10 @@ string Unit::WriteUnitString() {
unit["Tractorability"] = trac;
}

return unit;
}
string Unit::WriteUnitString() {
std::map<std::string, std::string> unit = UnitToMap();
return writeCSV(unit);
}

Expand Down
5 changes: 0 additions & 5 deletions engine/src/cmd/unit_generic.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -424,11 +424,6 @@ void Unit::Init(const char *filename,
std::string unitModifications,
Flightgroup *flightgrp,
int fg_subnumber) {
// Deprecated UNITTAB and configuration()->physics_config.unit_table options.
// Game will always load units from the JSON or CSV files.
// The other option was not implemented wholly. It simply opened the file
// but didn't do anything with it. See VSFile f variable.

// TODO: something with the following line
this->Unit::Init();
graphicOptions.SubUnit = SubU ? 1 : 0;
Expand Down
12 changes: 12 additions & 0 deletions engine/src/cmd/unit_generic.h
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,16 @@ struct PlanetaryOrbitData;
// TODO: move Armed to subclasses
class Unit : public Armed, public Audible, public Drawable, public Damageable, public Energetic,
public Intelligent, public Movable, public JumpCapable, public Carrier, public UpgradeableUnit {
// We store relevant textual description here.
// We stop relying on manifest and units data once we create the unit.
// The unit description is always taken from the manifest and not saved.
// Note the game confusingly refers to units:
// - class (Llama) - should be model
// - model (stock) - should be variant, but only if actually different without upgrades
// TODO: name is duplicated down below in some memory saving measure (StringPool::Reference)
std::string unit_key;
std::string unit_name;
std::string unit_description;

protected:
//How many lists are referencing us
Expand Down Expand Up @@ -539,6 +549,8 @@ class Unit : public Armed, public Audible, public Drawable, public Damageable, p
public:
//tries to warp as close to un as possible abiding by the distances of various enemy ships...it might not make it all the way
void WriteUnit(const char *modificationname = "");

std::map<std::string, std::string> UnitToMap();
std::string WriteUnitString();
//Loads a unit from an xml file into a complete datastructure
void LoadXML(const char *filename, const char *unitModifications = "", std::string *xmlbuffer = NULL);
Expand Down
1 change: 0 additions & 1 deletion engine/src/configuration/configuration.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,6 @@ void Configuration::OverrideDefaultsWithUserConfiguration() {
physics_config.velocity_max = GetGameConfig().GetFloat("physics.velocity_max", physics_config.velocity_max);
physics_config.max_player_rotation_rate = GetGameConfig().GetFloat("physics.maxplayerrot", physics_config.max_player_rotation_rate);
physics_config.max_non_player_rotation_rate = GetGameConfig().GetFloat("physics.maxNPCrot", physics_config.max_non_player_rotation_rate);
physics_config.unit_table = GetGameConfig().GetBool("physics.UnitTable", physics_config.unit_table);
physics_config.capship_size = GetGameConfig().GetFloat("physics.capship_size", physics_config.capship_size);
physics_config.near_autotrack_cone = GetGameConfig().GetFloat("physics.near_autotrack_cone", physics_config.near_autotrack_cone);
physics_config.close_enough_to_autotrack = GetGameConfig().GetFloat("physics.close_enough_to_autotrack", physics_config.close_enough_to_autotrack);
Expand Down
1 change: 0 additions & 1 deletion engine/src/configuration/configuration.h
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,6 @@ struct PhysicsConfig {
float velocity_max{10000.0F};
float max_player_rotation_rate{24.0F};
float max_non_player_rotation_rate{360.0F};
bool unit_table{false};
float capship_size{500.0F};
float near_autotrack_cone{0.9F};
float close_enough_to_autotrack{4.0F};
Expand Down
78 changes: 78 additions & 0 deletions engine/src/python/base_computer/ship_view.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* ship_view.cpp
*
* Copyright (c) 2001-2002 Daniel Horn
* Copyright (c) 2002-2019 pyramid3d and other Vega Strike Contributors
* Copyright (c) 2019-2023 Stephen G. Tuggy, Benjamen R. Meyer, Roy Falk and other Vega Strike Contributors
*
* https://github.com/vegastrike/Vega-Strike-Engine-Source
*
* This file is part of Vega Strike.
*
* Vega Strike is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* Vega Strike is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Vega Strike. If not, see <https://www.gnu.org/licenses/>.
*/

// -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*-

#include "ship_view.h"
#include "vsfilesystem.h"

#include <Python.h>
#include <boost/python.hpp>
#include <boost/filesystem.hpp>

static const std::string module_name = "ship_view";

const std::string GetShipView(const std::map<std::string, std::string>ship_stats) {
if(!boost::filesystem::exists("python/base_computer/ship_view.py")) {
return "Error: ship description not found";
}

PyObject* module = PyImport_ImportModule(module_name.c_str());

if(!module) {
PyErr_Print();
return "Error: PyImport_ImportModule is null";
}

boost::python::dict dict;
for (auto const& pair : ship_stats) {
dict[pair.first] = pair.second;
}


PyObject* args = PyTuple_Pack(1, dict.ptr());
if(args == nullptr) {
PyErr_Print();
return "Error: PyTuple_Pack is null";
}

PyObject* function = PyObject_GetAttrString(module,"get_ship_description");
if(!function) {
PyErr_Print();
return "Error: PyObject_GetAttrString is null";
}


PyObject* pyResult = PyObject_CallObject(function, args);

if(!pyResult) {
PyErr_Print();
return "Error: PyObject_CallObject is null";
}

std::string result = PyUnicode_AsUTF8(pyResult);

return result;
}
36 changes: 36 additions & 0 deletions engine/src/python/base_computer/ship_view.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* ship_view.h
*
* Copyright (c) 2001-2002 Daniel Horn
* Copyright (c) 2002-2019 pyramid3d and other Vega Strike Contributors
* Copyright (c) 2019-2023 Stephen G. Tuggy, Benjamen R. Meyer, Roy Falk and other Vega Strike Contributors
*
* https://github.com/vegastrike/Vega-Strike-Engine-Source
*
* This file is part of Vega Strike.
*
* Vega Strike is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* Vega Strike is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Vega Strike. If not, see <https://www.gnu.org/licenses/>.
*/

// -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*-

#ifndef VEGA_STRIKE_ENGINE_PYTHON_BASE_COMPUTER_SHIP_VIEW_H
#define VEGA_STRIKE_ENGINE_PYTHON_BASE_COMPUTER_SHIP_VIEW_H

#include <string>
#include <map>

const std::string GetShipView(const std::map<std::string, std::string>ship_stats);
BenjamenMeyer marked this conversation as resolved.
Show resolved Hide resolved

#endif // VEGA_STRIKE_ENGINE_PYTHON_BASE_COMPUTER_SHIP_VIEW_H
11 changes: 11 additions & 0 deletions engine/src/python/init.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@
#include "python_compile.h"
#include "python_class.h"
#include "cmd/unit_generic.h"
#include "python/config/python_utils.h"

#if defined (_WIN32) && !defined (__CYGWIN__)
#include <direct.h>
#include <vega_py_run.h>
Expand Down Expand Up @@ -170,6 +172,15 @@ void Python::init() {
InitBase();
InitDirector();

// Add relevant paths to python path
const std::string python_path_string = GetPythonPath()
+ ":" + VSFileSystem::programdir
+ ":" + VSFileSystem::datadir + "/python/base_computer/";
const std::wstring python_path_wstring = std::wstring(python_path_string.begin(),
python_path_string.end());
const wchar_t* python_path = python_path_wstring.c_str();
Py_SetPath(python_path);

// Now we can do python things about them and initialize them
Py_Initialize();
initpaths();
Expand Down
10 changes: 10 additions & 0 deletions engine/src/resource/manifest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -164,3 +164,13 @@ Manifest Manifest::GetMissionManifest() {

return manifest;
}

const std::string Manifest::GetShipDescription(const std::string unit_key) {
for(const Cargo& cargo : _items) {
if(cargo.name == unit_key) {
return cargo.description;
}
}

return "";
}
2 changes: 2 additions & 0 deletions engine/src/resource/manifest.h
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ class Manifest {
std::vector<Cargo> getItems() { return _items; }
bool empty() { return _items.empty(); }
int size() { return _items.size(); }

const std::string GetShipDescription(const std::string unit_key);
};


Expand Down
Loading