26 # include <curl/curl.h>
27 # include <curl/easy.h>
31 #include "scriptany/scriptany.h"
32 #include "scriptarray/scriptarray.h"
33 #include "scripthelper/scripthelper.h"
34 #include "scriptmath/scriptmath.h"
35 #include "scriptstdstring/scriptstdstring.h"
67 #include <rapidjson/document.h>
68 #include <rapidjson/writer.h>
72 using namespace AngelScript;
86 void GameScript::logFormat(
const char*
format, ...)
88 char buffer[4000] = {};
89 sprintf(buffer,
"[RoR|Script] ");
90 char* buffer_pos = buffer + 13;
94 vsprintf(buffer_pos,
format, args);
100 void GameScript::activateAllVehicles()
105 void GameScript::setTrucksForcedAwake(
bool forceActive)
110 float GameScript::getTime()
115 void GameScript::setPersonPosition(
const Vector3& vec)
117 if (!this->HavePlayerAvatar(__FUNCTION__))
123 void GameScript::loadTerrain(
const String& terrain)
128 Vector3 GameScript::getPersonPosition()
130 Vector3 result(Vector3::ZERO);
136 void GameScript::movePerson(
const Vector3& vec)
138 if (!this->HavePlayerAvatar(__FUNCTION__))
144 void GameScript::setPersonRotation(
const Radian& rot)
146 if (!this->HavePlayerAvatar(__FUNCTION__))
152 Radian GameScript::getPersonRotation()
160 String GameScript::getCaelumTime()
172 void GameScript::setCaelumTime(
float value)
175 if (!this->HaveSimTerrain(__FUNCTION__))
182 bool GameScript::getCaelumAvailable()
192 void GameScript::stopTimer()
197 void GameScript::startTimer(
int id)
202 void GameScript::setTimeDiff(
float diff)
207 void GameScript::setBestLapTime(
float time)
212 void GameScript::setWaterHeight(
float value)
214 if (!this->HaveSimTerrain(__FUNCTION__))
225 float GameScript::getGroundHeight(Vector3& v)
227 float result = -1.0f;
233 float GameScript::getWaterHeight()
246 float GameScript::getGravity()
256 void GameScript::setGravity(
float value)
258 if (!this->HaveSimTerrain(__FUNCTION__))
269 int GameScript::getNumTrucksByFlag(
int flag)
274 if (!flag ||
static_cast<int>(actor->ar_state) == flag)
280 int GameScript::getCurrentTruckNumber()
286 ActorPtr GameScript::getTruckRemotelyReceivingCommands()
292 void GameScript::registerForEvent(
int eventValue)
304 void GameScript::unRegisterEvent(
int eventValue)
330 void GameScript::flashMessage(String& txt,
float time,
float charHeight)
335 void GameScript::message(String& txt, String& icon)
340 void GameScript::updateDirectionArrow(String& text, Vector3& vec)
345 int GameScript::getChatFontSize()
350 void GameScript::setChatFontSize(
int size)
355 void GameScript::showChooser(
const String& type,
const String&
instance,
const String& box)
359 if (type ==
"airplane")
367 if (type ==
"extension")
373 if (type ==
"trailer")
379 if (type ==
"vehicle")
389 void GameScript::repairVehicle(
const String&
instance,
const String& box,
bool keepPosition)
394 void GameScript::removeVehicle(
const String& event_source_instance_name,
const String& event_source_box_name)
403 AngelScript::CScriptArray* GameScript::getEditorObjects()
405 if (!this->HaveSimTerrain(__FUNCTION__))
412 std::string arraydecl =
fmt::format(
"array<{}>",
"TerrainEditorObjectClass@");
416 for (AngelScript::asUINT i = 0; i < arr->GetSize(); i++)
420 arr->SetValue(i, &ref);
427 void GameScript::destroyObject(
const String& instanceName)
429 if (!this->HaveSimTerrain(__FUNCTION__))
438 void GameScript::moveObjectVisuals(
const String& instanceName,
const Vector3& pos)
440 if (!this->HaveSimTerrain(__FUNCTION__))
449 void GameScript::spawnObject(
const String& objectName,
const String& instanceName,
const Vector3& pos,
const Vector3& rot,
const String& eventhandler,
bool uniquifyMaterials)
451 if (!this->HaveSimTerrain(__FUNCTION__))
456 this->logFormat(
"spawnObject(): Cannot spawn object, no terrain loaded!");
462 this->logFormat(
"spawnObject(): Cannot spawn object, no terrain script loaded!");
469 if (module ==
nullptr)
471 this->logFormat(
"spawnObject(): Failed to fetch/create script module");
475 int handler_func_id = -1;
476 if (!eventhandler.empty())
481 "spawnObject(): Specifying event handler function in `game.spawnObject()` (or .TOBJ file) is obsolete and only works with terrain scripts;"
482 " Use `eventCallbackEx()` with event `SE_EVENTBOX_ENTER` instead, it does the same job and works with any script."
483 " Just pass an empty string to the `game.spawnObject()` parameter.");
490 if (handler_func !=
nullptr)
492 handler_func_id = handler_func->GetId();
496 const String type =
"";
506 void GameScript::hideDirectionArrow()
511 bool GameScript::getScreenPosFromWorldPos(Ogre::Vector3
const& world_pos, Ogre::Vector2& out_screen)
513 ImVec2 screen_size = ImGui::GetIO().DisplaySize;
516 Ogre::Vector3 pos_xyz = world2screen.
Convert(world_pos);
519 out_screen.x = pos_xyz.x;
520 out_screen.y = pos_xyz.y;
526 Ogre::Vector2 GameScript::getDisplaySize()
528 ImVec2 size = ImGui::GetIO().DisplaySize;
529 return Vector2(size.x, size.y);
532 Ogre::Vector2 GameScript::getMouseScreenPosition()
534 ImVec2 pos = ImGui::GetIO().MousePos;
535 return Vector2(pos.x, pos.y);
538 int GameScript::setMaterialAmbient(
const String& materialName,
float red,
float green,
float blue)
542 MaterialPtr m = MaterialManager::getSingleton().getByName(materialName);
545 m->setAmbient(red, green, blue);
555 int GameScript::setMaterialDiffuse(
const String& materialName,
float red,
float green,
float blue,
float alpha)
559 MaterialPtr m = MaterialManager::getSingleton().getByName(materialName);
562 m->setDiffuse(red, green, blue, alpha);
572 int GameScript::setMaterialSpecular(
const String& materialName,
float red,
float green,
float blue,
float alpha)
576 MaterialPtr m = MaterialManager::getSingleton().getByName(materialName);
579 m->setSpecular(red, green, blue, alpha);
589 int GameScript::setMaterialEmissive(
const String& materialName,
float red,
float green,
float blue)
593 MaterialPtr m = MaterialManager::getSingleton().getByName(materialName);
596 m->setSelfIllumination(red, green, blue);
606 int GameScript::getTextureUnitState(TextureUnitState** tu,
const String materialName,
int techniqueNum,
int passNum,
int textureUnitNum)
611 MaterialPtr m = MaterialManager::getSingleton().getByName(materialName);
616 if (techniqueNum < 0 || techniqueNum > m->getNumTechniques())
618 Technique* t = m->getTechnique(techniqueNum);
623 if (passNum < 0 || passNum > t->getNumPasses())
625 Pass* p = t->getPass(passNum);
630 if (textureUnitNum < 0 || textureUnitNum > p->getNumTextureUnitStates())
632 TextureUnitState* tut = p->getTextureUnitState(textureUnitNum);
640 int GameScript::setMaterialTextureName(
const String& materialName,
int techniqueNum,
int passNum,
int textureUnitNum,
const String& textureName)
644 TextureUnitState* tu = 0;
645 int res = getTextureUnitState(&tu, materialName, techniqueNum, passNum, textureUnitNum);
646 if (res == 0 && tu != 0)
649 tu->setTextureName(textureName);
660 int GameScript::setMaterialTextureRotate(
const String& materialName,
int techniqueNum,
int passNum,
int textureUnitNum,
float rotation)
664 TextureUnitState* tu = 0;
665 int res = getTextureUnitState(&tu, materialName, techniqueNum, passNum, textureUnitNum);
666 if (res == 0 && tu != 0)
668 tu->setTextureRotate(Degree(rotation));
679 int GameScript::setMaterialTextureScroll(
const String& materialName,
int techniqueNum,
int passNum,
int textureUnitNum,
float sx,
float sy)
683 TextureUnitState* tu = 0;
684 int res = getTextureUnitState(&tu, materialName, techniqueNum, passNum, textureUnitNum);
685 if (res == 0 && tu != 0)
687 tu->setTextureScroll(sx, sy);
698 int GameScript::setMaterialTextureScale(
const String& materialName,
int techniqueNum,
int passNum,
int textureUnitNum,
float u,
float v)
702 TextureUnitState* tu = 0;
703 int res = getTextureUnitState(&tu, materialName, techniqueNum, passNum, textureUnitNum);
704 if (res == 0 && tu != 0)
706 tu->setTextureScale(u, v);
717 float GameScript::rangeRandom(
float from,
float to)
719 return Math::RangeRandom(from, to);
722 int GameScript::getLoadedTerrain(String& result)
724 String terrainName =
"";
729 result = terrainName;
732 return !terrainName.empty();
740 void GameScript::clearEventCache()
742 if (!this->HaveSimTerrain(__FUNCTION__))
747 this->logFormat(
"Cannot execute '%s', collisions not ready", __FUNCTION__);
754 void GameScript::setCameraPosition(
const Vector3& pos)
756 if (!this->HaveMainCamera(__FUNCTION__))
762 void GameScript::setCameraDirection(
const Vector3& rot)
764 if (!this->HaveMainCamera(__FUNCTION__))
770 void GameScript::setCameraOrientation(
const Quaternion& q)
772 if (!this->HaveMainCamera(__FUNCTION__))
778 void GameScript::setCameraYaw(
float rotX)
780 if (!this->HaveMainCamera(__FUNCTION__))
786 void GameScript::setCameraPitch(
float rotY)
788 if (!this->HaveMainCamera(__FUNCTION__))
794 void GameScript::setCameraRoll(
float rotZ)
796 if (!this->HaveMainCamera(__FUNCTION__))
802 Vector3 GameScript::getCameraPosition()
804 Vector3 result(Vector3::ZERO);
810 Vector3 GameScript::getCameraDirection()
812 Vector3 result(Vector3::ZERO);
821 Quaternion GameScript::getCameraOrientation()
823 Quaternion result(Quaternion::ZERO);
829 void GameScript::cameraLookAt(
const Vector3& pos)
831 if (!this->HaveMainCamera(__FUNCTION__))
837 int GameScript::useOnlineAPI(
const String& apiquery,
const AngelScript::CScriptDictionary& dict, String& result)
848 if (player_actor ==
nullptr)
854 std::string token = std::string(
"RoR-Api-User-Token: ") + hashtok;
861 rapidjson::Document j_doc;
864 j_doc.AddMember(
"user-name", rapidjson::StringRef(
App::mp_player_name->getStr().c_str()), j_doc.GetAllocator());
865 j_doc.AddMember(
"user-country", rapidjson::StringRef(
App::app_country->getStr().c_str()), j_doc.GetAllocator());
866 j_doc.AddMember(
"user-token", rapidjson::StringRef(hashtok.c_str()), j_doc.GetAllocator());
868 j_doc.AddMember(
"terrain-name", rapidjson::StringRef(terrain_name.c_str()), j_doc.GetAllocator());
869 j_doc.AddMember(
"terrain-filename", rapidjson::StringRef(
App::sim_terrain_name->getStr().c_str()), j_doc.GetAllocator());
871 j_doc.AddMember(
"script-name", rapidjson::StringRef(script_name.c_str()), j_doc.GetAllocator());
872 j_doc.AddMember(
"script-hash", rapidjson::StringRef(script_hash.c_str()), j_doc.GetAllocator());
874 j_doc.AddMember(
"actor-name", rapidjson::StringRef(player_actor->
ar_design_name.c_str()), j_doc.GetAllocator());
875 j_doc.AddMember(
"actor-filename", rapidjson::StringRef(player_actor->
ar_filename.c_str()), j_doc.GetAllocator());
876 j_doc.AddMember(
"actor-hash", rapidjson::StringRef(player_actor->
ar_filehash.c_str()), j_doc.GetAllocator());
878 rapidjson::Value j_linked_actors(rapidjson::kArrayType);
881 rapidjson::Value j_actor(rapidjson::kObjectType);
882 j_actor.AddMember(
"actor-name", rapidjson::StringRef(actor->
ar_design_name.c_str()), j_doc.GetAllocator());
883 j_actor.AddMember(
"actor-filename", rapidjson::StringRef(actor->
ar_filename.c_str()), j_doc.GetAllocator());
884 j_actor.AddMember(
"actor-hash", rapidjson::StringRef(actor->
ar_filehash.c_str()), j_doc.GetAllocator());
885 j_linked_actors.PushBack(j_actor, j_doc.GetAllocator());
887 j_doc.AddMember(
"linked-actors", j_linked_actors, j_doc.GetAllocator());
889 j_doc.AddMember(
"avg-fps", getAvgFPS(), j_doc.GetAllocator());
890 j_doc.AddMember(
"ror-version", rapidjson::StringRef(
ROR_VERSION_STRING), j_doc.GetAllocator());
892 for (
auto item : dict)
894 const std::string& key = item.GetKey();
895 const std::string* value = (std::string *)item.GetAddressOfValue();
896 j_doc.AddMember(rapidjson::StringRef(key.c_str()), rapidjson::StringRef(value->c_str()), j_doc.GetAllocator());
899 rapidjson::StringBuffer buffer;
900 rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
901 j_doc.Accept(writer);
902 std::string json = buffer.GetString();
906 _L(
"using Online API..."),
"information.png");
908 LOG(
"[RoR|GameScript] Submitting race results to '" + url +
"'");
910 std::thread([url, user, token, json]()
912 long response_code = 0;
914 struct curl_slist *slist = NULL;
915 slist = curl_slist_append(slist,
"Accept: application/json");
916 slist = curl_slist_append(slist,
"Content-Type: application/json");
917 slist = curl_slist_append(slist, user.c_str());
918 slist = curl_slist_append(slist, token.c_str());
920 CURL *curl = curl_easy_init();
921 curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
922 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
923 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json.c_str());
925 CURLcode curl_result = curl_easy_perform(curl);
926 curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
928 if (curl_result != CURLE_OK || response_code != 200)
930 Ogre::LogManager::getSingleton().stream()
931 <<
"[RoR|GameScript] `useOnlineAPI()` failed to submit data;"
932 <<
" Error: '" << curl_easy_strerror(curl_result) <<
"'; HTTP status code: " << response_code;
935 curl_easy_cleanup(curl);
937 curl_slist_free_all(slist);
942 _L(
"Cannot use Online API in this build (CURL not available)"));
948 void GameScript::openUrlInDefaultBrowser(
const std::string& url)
953 void GameScript::fetchUrlAsStringAsync(
const std::string& url,
const std::string& display_filename)
955 #if defined(USE_CURL)
965 std::thread(std::move(pktask), task).detach();
966 #endif // defined(USE_CURL)
969 void GameScript::boostCurrentTruck(
float factor)
975 rpm += 2000.0f * factor;
1010 int GameScript::getScriptVariable(
const Ogre::String& varName,
void *ref,
int refTypeId,
ScriptUnitID_t nid)
1015 int GameScript::sendGameCmd(
const String& message)
1023 #endif // USE_SOCKETW
1028 AngelScript::CScriptArray* GameScript::getRunningScripts()
1030 std::vector<ScriptUnitID_t> ids;
1032 ids.push_back(pair.first);
1044 AngelScript::CScriptDictionary* dict = AngelScript::CScriptDictionary::Create(
App::GetScriptEngine()->getEngine());
1048 dict->Set(
"uniqueId", (asINT64)info.
uniqueId);
1049 dict->Set(
"scriptName",
new std::string(info.
scriptName), stringTypeid);
1050 dict->Set(
"scriptCategory", &info.
scriptCategory, scriptCategoryTypeid);
1051 dict->Set(
"eventMask", (asINT64)info.
eventMask);
1052 dict->Set(
"scriptBuffer",
new std::string(info.
scriptBuffer), stringTypeid);
1080 if (actor !=
nullptr)
1087 ActorPtr GameScript::spawnTruck(Ogre::String& truckName, Ogre::Vector3& pos, Ogre::Vector3& rot)
1091 rq.
asr_rotation = Quaternion(Degree(rot.x), Vector3::UNIT_X) * Quaternion(Degree(rot.y), Vector3::UNIT_Y) * Quaternion(Degree(rot.z), Vector3::UNIT_Z);
1096 ActorPtr GameScript::spawnTruckAI(Ogre::String& truckName, Ogre::Vector3& pos, Ogre::String& truckSectionConfig, std::string& truckSkin,
int x)
1104 std::vector<Ogre::Vector3> waypoints;
1111 std::reverse(waypoints.begin(), waypoints.end());
1115 Ogre::Vector3 dir = Ogre::Vector3::ZERO;
1116 if (waypoints.size() >= 2)
1117 dir = waypoints[0] - waypoints[1];
1118 else if (waypoints.size() >= 1)
1121 rq.
asr_rotation = Ogre::Vector3::UNIT_X.getRotationTo(dir, Ogre::Vector3::UNIT_Y);
1136 AngelScript::CScriptArray* GameScript::getWaypoints(
int x)
1138 std::vector<Ogre::Vector3> vec;
1145 std::reverse(vec.begin(), vec.end());
1148 AngelScript::CScriptArray* arr = AngelScript::CScriptArray::Create(AngelScript::asGetActiveContext()->GetEngine()->GetTypeInfoByDecl(
"array<vector3>"), vec.size());
1150 for(AngelScript::asUINT i = 0; i < arr->GetSize(); i++)
1153 arr->SetValue(i, &vec[i]);
1159 AngelScript::CScriptArray* GameScript::getAllTrucks()
1162 AngelScript::CScriptArray* arr = AngelScript::CScriptArray::Create(AngelScript::asGetActiveContext()->GetEngine()->GetTypeInfoByDecl(
"array<BeamClass@>"), actors.size());
1164 for (AngelScript::asUINT i = 0; i < arr->GetSize(); i++)
1167 arr->SetValue(i, &actors[i]);
1173 void GameScript::addWaypoint(
const Ogre::Vector3& pos)
1175 std::vector<Ogre::Vector3> waypoints;
1182 AngelScript::CScriptArray* GameScript::getWaypointsSpeed()
1184 std::vector<int> vec;
1190 AngelScript::CScriptArray* arr = AngelScript::CScriptArray::Create(AngelScript::asGetActiveContext()->GetEngine()->GetTypeInfoByDecl(
"array<int>"), vec.size());
1192 for(AngelScript::asUINT i = 0; i < arr->GetSize(); i++)
1195 arr->SetValue(i, &vec[i]);
1201 int GameScript::getAIVehicleCount()
1207 int GameScript::getAIVehicleDistance()
1213 int GameScript::getAIVehiclePositionScheme()
1219 int GameScript::getAIVehicleSpeed()
1225 Ogre::String GameScript::getAIVehicleName(
int x)
1239 Ogre::String GameScript::getAIVehicleSectionConfig(
int x)
1253 std::string GameScript::getAIVehicleSkin(
int x)
1267 int GameScript::getAIRepeatTimes()
1273 int GameScript::getAIMode()
1281 void GameScript::setAIVehicleCount(
int num)
1286 void GameScript::setAIVehicleDistance(
int dist)
1291 void GameScript::setAIVehiclePositionScheme(
int scheme)
1296 void GameScript::setAIVehicleSpeed(
int speed)
1301 void GameScript::setAIVehicleName(
int x, std::string name)
1313 void GameScript::setAIVehicleSectionConfig(
int x, std::string config)
1324 this->
log(
fmt::format(
"setAIVehicleSectionConfig: ERROR, valid 'x' is 0 or 1, got {}", x));
1329 void GameScript::setAIVehicleSkin(
int x, std::string skin)
1340 this->
log(
fmt::format(
"setAIVehicleSkin: ERROR, valid 'x' is 0 or 1, got {}", x));
1345 void GameScript::setAIRepeatTimes(
int times)
1350 void GameScript::setAIMode(
int mode)
1355 void GameScript::showMessageBox(Ogre::String& title, Ogre::String& text,
bool use_btn1, Ogre::String& btn1_text,
bool allow_close,
bool use_btn2, Ogre::String& btn2_text)
1358 const char* btn1_cstr =
nullptr;
1359 const char* btn2_cstr =
nullptr;
1363 btn1_cstr = (btn1_text.empty() ?
"~1~" : btn1_text.c_str());
1367 btn2_cstr = (btn2_text.empty() ?
"~2~" : btn2_text.c_str());
1373 void GameScript::backToMenu()
1379 void GameScript::quitGame()
1384 float GameScript::getFPS()
1389 float GameScript::getAvgFPS()
1394 bool GameScript::getMousePositionOnTerrain(Ogre::Vector3& out_pos)
1396 if (!HaveSimTerrain(__FUNCTION__))
1404 out_pos = ray_result.position;
1406 return ray_result.hit;
1417 results_array.push_back(obj);
1421 bool queryResult(SceneQuery::WorldFragment* fragment, Real distance)
override
1427 CScriptArray* GameScript::getMousePointedMovableObjects()
1429 if (!HaveSimTerrain(__FUNCTION__))
1436 query.setSortByDistance(
true);
1439 query.execute(&qlis);
1443 Ogre::SceneManager* GameScript::getSceneManager()
1448 bool GameScript::pushMessage(
MsgType type, AngelScript::CScriptDictionary* dict)
1493 if (!has_filename && !has_buffer)
1495 this->
log(
fmt::format(
"{}: ERROR, either 'filename' or 'buffer' must be set!", log_msg));
1502 int64_t instance_id;
1505 this->
log(
fmt::format(
"{}: WARNING, category 'ACTOR' specified but 'associated_actor' not given.", log_msg, rq->
lsr_filename));
1582 std::string skin_name;
1587 this->
log(
fmt::format(
"{}: WARNING, skin '{}' is not installed.", log_msg, skin_name));
1604 int64_t instance_id = -1;
1625 int64_t instance_id = -1;
1635 this->
log(
fmt::format(
"{}: Actor with instance ID '{}' not found!", log_msg, instance_id));
1649 int64_t instance_id = -1;
1652 && instance_id > -1)
1662 Ogre::Vector3 position;
1665 m.
payload =
new Ogre::Vector3(position);
1687 case (int64_t)FreeForceType::CONSTANT:
1699 case (int64_t)FreeForceType::TOWARDS_COORDS:
1711 case (int64_t)FreeForceType::TOWARDS_NODE:
1806 CScriptArray* GameScript::getAllSoundScriptTemplates()
1816 AngelScript::CScriptArray* GameScript::getAllSoundScriptInstances()
1821 SoundPtr GameScript::createSoundFromResource(
const std::string& filename,
const std::string& resource_group_name)
1826 SoundScriptInstancePtr GameScript::createSoundScriptInstance(
const std::string& template_name,
int actor_instance_id = SoundScriptInstance::ACTOR_ID_UNKNOWN)
1831 bool GameScript::checkResourceExists(
const std::string& filename,
const std::string& resource_group)
1835 std::string resource_name = this->CheckFileAccess(
"checkResourceExists()", filename, resource_group);
1836 if (resource_name ==
"")
1840 return Ogre::ResourceGroupManager::getSingleton().resourceExists(resource_group, resource_name);
1849 bool GameScript::deleteResource(
const std::string& filename,
const std::string& resource_group)
1853 std::string resource_name = this->CheckFileAccess(
"deleteResource()", filename, resource_group);
1854 if (resource_name ==
"")
1858 Ogre::ResourceGroupManager::getSingleton().deleteResource(resource_name, resource_group);
1868 std::string GameScript::loadTextResourceAsString(
const std::string& filename,
const std::string& resource_group)
1872 std::string resource_name = this->CheckFileAccess(
"loadTextResourceAsString()", filename, resource_group);
1873 if (resource_name ==
"")
1876 Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingleton().openResource(resource_name, resource_group);
1878 if (!stream || !stream->isReadable())
1881 fmt::format(
"loadTextResourceAsString() could not read resource '{}' in group '{}'",
1882 resource_name, resource_group));
1886 #if OGRE_PLATFORM == OGRE_PLATFORM_LINUX
1891 const size_t BUF_LEN = 4000;
1892 char buf[BUF_LEN] = {};
1896 size_t read_len = stream->read(buf, BUF_LEN);
1897 if (read_len < BUF_LEN)
1902 str.append(buf, read_len);
1906 return stream->getAsString();
1916 bool GameScript::createTextResourceFromString(
const std::string& data,
const std::string& filename,
const std::string& resource_group,
bool overwrite)
1920 std::string resource_name = this->CheckFileAccess(
"createTextResourceFromString()", filename, resource_group);
1921 if (resource_name ==
"")
1924 Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingleton().createResource(resource_name, resource_group, overwrite);
1926 if (!stream || !stream->isWriteable())
1929 fmt::format(
"createTextResourceFromString() could not create resource '{}' in group '{}'",
1930 resource_name, resource_group));
1934 stream->write(data.data(), data.size());
1944 AngelScript::CScriptArray* GameScript::findResourceFileInfo(
const std::string& resource_group,
const std::string& pattern,
bool dirs )
1949 Ogre::FileInfoListPtr fileInfoList
1950 = Ogre::ResourceGroupManager::getSingleton().findResourceFileInfo(resource_group, pattern, dirs);
1954 AngelScript::CScriptArray* arr = AngelScript::CScriptArray::Create(typeinfo);
1956 for (
const Ogre::FileInfo& fileinfo: *fileInfoList)
1958 AngelScript::CScriptDictionary* dict = AngelScript::CScriptDictionary::Create(
App::GetScriptEngine()->getEngine());
1959 dict->Set(
"filename",
new std::string(fileinfo.filename), stringTypeid);
1960 dict->Set(
"basename",
new std::string(fileinfo.basename), stringTypeid);
1961 dict->Set(
"compressedSize", (asINT64)fileinfo.compressedSize);
1962 dict->Set(
"uncompressedSize", (asINT64)fileinfo.uncompressedSize);
1964 arr->InsertLast(dict);
1975 Ogre::Image GameScript::loadImageResource(
const std::string& filename,
const std::string& resource_group)
1979 std::string resource_name = this->CheckFileAccess(
"loadImageResource()", filename, resource_group);
1980 if (resource_name ==
"")
1981 return Ogre::Image();
1984 return img.load(resource_name, resource_group);
1989 return Ogre::Image();
1993 bool GameScript::serializeMeshResource(
const std::string& filename,
const std::string& resource_group,
const Ogre::MeshPtr& mesh)
1997 std::string resource_name = this->CheckFileAccess(
"serializeMeshResource()", filename, resource_group);
1998 if (resource_name ==
"")
2001 Ogre::MeshSerializer ser;
2002 Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingleton().createResource(resource_name, resource_group);
2003 ser.exportMesh(mesh.get(), stream);
2016 bool GameScript::HaveSimTerrain(
const char* func_name)
2020 this->logFormat(
"Cannot execute '%s', terrain not ready", func_name);
2026 bool GameScript::HavePlayerAvatar(
const char* func_name)
2030 this->logFormat(
"Cannot execute '%s', player avatar not ready", func_name);
2036 bool GameScript::HaveMainCamera(
const char* func_name)
2040 this->logFormat(
"Cannot execute '%s', main camera not ready", func_name);
2046 std::string GameScript::CheckFileAccess(
const char* func_name,
const std::string& filename,
const std::string& resource_group)
2051 std::string basename, extension, path;
2052 Ogre::StringUtil::splitFullFilename(filename, basename, extension, path);
2056 fmt::format(
"{}: access denied to '{}' with group '{}' - file paths are not allowed",
2057 func_name, filename, resource_group));
2062 return basename +
"." + extension;