diff --git a/extract_assets.py b/extract_assets.py index 7f02be04ca..6a7afd1e37 100755 --- a/extract_assets.py +++ b/extract_assets.py @@ -20,6 +20,10 @@ def ExtractFile(xmlPath, outputPath, outputSourcePath): return execStr = "tools/ZAPD/ZAPD.out e -eh -i %s -b baserom/ -o %s -osf %s -gsf 1 -rconf tools/ZAPDConfigs/MqDbg/Config.xml" % (xmlPath, outputPath, outputSourcePath) + + if "overlays" in xmlPath: + execStr += " --static" + if globalUnaccounted: execStr += " -wu" diff --git a/tools/ZAPD/.gitignore b/tools/ZAPD/.gitignore index 4a9671810a..68c502e36a 100644 --- a/tools/ZAPD/.gitignore +++ b/tools/ZAPD/.gitignore @@ -333,5 +333,9 @@ ASALocalRun/ *.o *.d lib/libgfxd/libgfxd.a +ExporterTest/ExporterTest.a +ZAPDUtils/ZAPDUtils.a .vscode/ -ZAPD/BuildInfo.h \ No newline at end of file +build/ +ZAPDUtils/build/ +ZAPD/BuildInfo.h diff --git a/tools/ZAPD/.gitrepo b/tools/ZAPD/.gitrepo index 73ce262034..1034fcf320 100644 --- a/tools/ZAPD/.gitrepo +++ b/tools/ZAPD/.gitrepo @@ -6,7 +6,7 @@ [subrepo] remote = https://github.com/zeldaret/ZAPD.git branch = master - commit = 6be9af65d39a1608ef854efbaf0bf9399aac5da1 - parent = 913b88b160c735d81f2d4f1d14717de8c7ba8dee + commit = d0cd6b3974706fc4d89c9b6545b8c17dd424b664 + parent = c0e02913038e871221b2fcfc8be65b8dc281aa4a method = merge cmdver = 0.4.3 diff --git a/tools/ZAPD/ExporterTest/CollisionExporter.cpp b/tools/ZAPD/ExporterTest/CollisionExporter.cpp new file mode 100644 index 0000000000..e00f5c1b0b --- /dev/null +++ b/tools/ZAPD/ExporterTest/CollisionExporter.cpp @@ -0,0 +1,74 @@ +#include "CollisionExporter.h" + +void ExporterExample_Collision::Save(ZResource* res, [[maybe_unused]] fs::path outPath, + BinaryWriter* writer) +{ + ZCollisionHeader* col = (ZCollisionHeader*)res; + + writer->Write(col->absMinX); + writer->Write(col->absMinY); + writer->Write(col->absMinZ); + + writer->Write(col->absMaxX); + writer->Write(col->absMaxY); + writer->Write(col->absMaxZ); + + writer->Write(col->numVerts); + writer->Write(col->vtxAddress); + + writer->Write(col->numPolygons); + writer->Write(col->polyAddress); + writer->Write(col->polyTypeDefAddress); + writer->Write(col->camDataAddress); + + writer->Write(col->numWaterBoxes); + writer->Write(col->waterBoxAddress); + + writer->Write(col->vtxSegmentOffset); + writer->Write(col->polySegmentOffset); + writer->Write(col->polyTypeDefSegmentOffset); + writer->Write(col->camDataSegmentOffset); + writer->Write(col->waterBoxSegmentOffset); + + uint32_t oldOffset = writer->GetBaseAddress(); + + writer->Seek(col->vtxSegmentOffset, SeekOffsetType::Start); + + for (uint16_t i = 0; i < col->vertices.size(); i++) + { + for (uint32_t j = 0; j < col->vertices[i].dimensions; j++) + { + writer->Write(col->vertices[i].scalars[j].scalarData.s16); + } + } + + writer->Seek(col->polySegmentOffset, SeekOffsetType::Start); + + for (uint16_t i = 0; i < col->polygons.size(); i++) + { + writer->Write(col->polygons[i].type); + writer->Write(col->polygons[i].vtxA); + writer->Write(col->polygons[i].vtxB); + writer->Write(col->polygons[i].vtxC); + writer->Write(col->polygons[i].a); + writer->Write(col->polygons[i].b); + writer->Write(col->polygons[i].c); + writer->Write(col->polygons[i].d); + } + + writer->Seek(col->polyTypeDefSegmentOffset, SeekOffsetType::Start); + + for (uint16_t i = 0; i < col->polygonTypes.size(); i++) + writer->Write(col->polygonTypes[i]); + + writer->Seek(col->camDataSegmentOffset, SeekOffsetType::Start); + + for (auto entry : col->camData->entries) + { + writer->Write(entry->cameraSType); + writer->Write(entry->numData); + writer->Write(entry->cameraPosDataSeg); + } + + writer->Seek(oldOffset, SeekOffsetType::Start); +} diff --git a/tools/ZAPD/ExporterTest/CollisionExporter.h b/tools/ZAPD/ExporterTest/CollisionExporter.h new file mode 100644 index 0000000000..5f48e6557e --- /dev/null +++ b/tools/ZAPD/ExporterTest/CollisionExporter.h @@ -0,0 +1,10 @@ +#pragma once + +#include "ZCollision.h" +#include "ZResource.h" + +class ExporterExample_Collision : public ZResourceExporter +{ +public: + void Save(ZResource* res, fs::path outPath, BinaryWriter* writer) override; +}; \ No newline at end of file diff --git a/tools/ZAPD/ExporterTest/ExporterTest.vcxproj b/tools/ZAPD/ExporterTest/ExporterTest.vcxproj new file mode 100644 index 0000000000..a709a35091 --- /dev/null +++ b/tools/ZAPD/ExporterTest/ExporterTest.vcxproj @@ -0,0 +1,159 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + Win32Proj + {65608eb0-1a47-45ad-ab66-192fb64c762c} + ExporterTest + 10.0 + ExporterExample + + + + Application + true + v142 + Unicode + + + Application + false + v142 + true + Unicode + + + StaticLibrary + true + v142 + Unicode + + + Application + false + v142 + true + Unicode + + + + + + + + + + + + + + + + + + + + + true + + + false + + + true + $(SolutionDir)\ZAPD\;$(SolutionDir)ZAPDUtils;$(SolutionDir)lib\tinyxml2;$(SolutionDir)lib\libgfxd;$(SolutionDir)lib\elfio;$(SolutionDir)lib\stb;$(ProjectDir);$(IncludePath) + + + false + + + + Level3 + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + Level3 + true + _DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + true + stdcpp17 + stdc11 + + + Console + true + + + + + Level3 + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + + + + + + + + + + + diff --git a/tools/ZAPD/ExporterTest/ExporterTest.vcxproj.filters b/tools/ZAPD/ExporterTest/ExporterTest.vcxproj.filters new file mode 100644 index 0000000000..166f563a17 --- /dev/null +++ b/tools/ZAPD/ExporterTest/ExporterTest.vcxproj.filters @@ -0,0 +1,42 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Header Files + + + Header Files + + + Header Files + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + \ No newline at end of file diff --git a/tools/ZAPD/ExporterTest/Main.cpp b/tools/ZAPD/ExporterTest/Main.cpp new file mode 100644 index 0000000000..732dcedc2f --- /dev/null +++ b/tools/ZAPD/ExporterTest/Main.cpp @@ -0,0 +1,79 @@ +#include +#include +#include +#include + +enum class ExporterFileMode +{ + ModeExample1 = (int)ZFileMode::Custom + 1, + ModeExample2 = (int)ZFileMode::Custom + 2, + ModeExample3 = (int)ZFileMode::Custom + 3, +}; + +static void ExporterParseFileMode(const std::string& buildMode, ZFileMode& fileMode) +{ + if (buildMode == "me1") + fileMode = (ZFileMode)ExporterFileMode::ModeExample1; + else if (buildMode == "me2") + fileMode = (ZFileMode)ExporterFileMode::ModeExample2; + else if (buildMode == "me3") + fileMode = (ZFileMode)ExporterFileMode::ModeExample3; +} + +static void ExporterParseArgs([[maybe_unused]] int argc, char* argv[], int& i) +{ + std::string arg = argv[i]; + + if (arg == "--do-x") + { + } + else if (arg == "--do-y") + { + } +} + +static bool ExporterProcessFileMode(ZFileMode fileMode) +{ + // Do whatever work is associated with these custom file modes... + // Return true to indicate one of our own file modes is being processed + if (fileMode == (ZFileMode)ExporterFileMode::ModeExample1) + return true; + else if (fileMode == (ZFileMode)ExporterFileMode::ModeExample2) + return true; + else if (fileMode == (ZFileMode)ExporterFileMode::ModeExample3) + return true; + + return false; +} + +static void ExporterFileBegin(ZFile* file) +{ + printf("ExporterFileBegin() called on ZFile %s.\n", file->GetName().c_str()); +} + +static void ExporterFileEnd(ZFile* file) +{ + printf("ExporterFileEnd() called on ZFile %s.\n", file->GetName().c_str()); +} + +static void ImportExporters() +{ + // In this example we set up a new exporter called "EXAMPLE". + // By running ZAPD with the argument -se EXAMPLE, we tell it that we want to use this exporter + // for our resources. + ExporterSet* exporterSet = new ExporterSet(); + exporterSet->processFileModeFunc = ExporterProcessFileMode; + exporterSet->parseFileModeFunc = ExporterParseFileMode; + exporterSet->parseArgsFunc = ExporterParseArgs; + exporterSet->beginFileFunc = ExporterFileBegin; + exporterSet->endFileFunc = ExporterFileEnd; + exporterSet->exporters[ZResourceType::Texture] = new ExporterExample_Texture(); + exporterSet->exporters[ZResourceType::Room] = new ExporterExample_Room(); + exporterSet->exporters[ZResourceType::CollisionHeader] = new ExporterExample_Collision(); + + Globals::AddExporter("EXAMPLE", exporterSet); +} + +// When ZAPD starts up, it will automatically call the below function, which in turn sets up our +// exporters. +REGISTER_EXPORTER(ImportExporters) \ No newline at end of file diff --git a/tools/ZAPD/ExporterTest/Makefile b/tools/ZAPD/ExporterTest/Makefile new file mode 100644 index 0000000000..a2bfa9a814 --- /dev/null +++ b/tools/ZAPD/ExporterTest/Makefile @@ -0,0 +1,28 @@ +# Only used for standalone compilation, usually inherits these from the main makefile +CXXFLAGS ?= -Wall -Wextra -O2 -g -std=c++17 + +SRC_DIRS := $(shell find -type d -not -path "*build*") +CPP_FILES := $(foreach dir,$(SRC_DIRS),$(wildcard $(dir)/*.cpp)) +H_FILES := $(foreach dir,$(SRC_DIRS),$(wildcard $(dir)/*.h)) + +O_FILES := $(foreach f,$(CPP_FILES:.cpp=.o),build/$f) +LIB := ExporterTest.a + +# create build directories +$(shell mkdir -p $(foreach dir,$(SRC_DIRS),build/$(dir))) + +all: $(LIB) + +clean: + rm -rf build $(LIB) + +format: + clang-format-11 -i $(CPP_FILES) $(H_FILES) + +.PHONY: all clean format + +build/%.o: %.cpp + $(CXX) $(CXXFLAGS) $(OPTFLAGS) -I ./ -I ../ZAPD -I ../ZAPDUtils -I ../lib/tinyxml2 -c $(OUTPUT_OPTION) $< + +$(LIB): $(O_FILES) + $(AR) rcs $@ $^ diff --git a/tools/ZAPD/ExporterTest/RoomExporter.cpp b/tools/ZAPD/ExporterTest/RoomExporter.cpp new file mode 100644 index 0000000000..c4a6844fb5 --- /dev/null +++ b/tools/ZAPD/ExporterTest/RoomExporter.cpp @@ -0,0 +1,372 @@ +#include "RoomExporter.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +void ExporterExample_Room::Save(ZResource* res, fs::path outPath, BinaryWriter* writer) +{ + ZRoom* room = dynamic_cast(res); + + // MemoryStream* memStream = new MemoryStream(); + // BinaryWriter* writer = new BinaryWriter(memStream); + + for (size_t i = 0; i < room->commands.size() * 8; i++) + writer->Write((uint8_t)0); + + for (size_t i = 0; i < room->commands.size(); i++) + { + ZRoomCommand* cmd = room->commands[i]; + + writer->Seek(i * 8, SeekOffsetType::Start); + + writer->Write((uint8_t)cmd->cmdID); + + switch (cmd->cmdID) + { + case RoomCommand::SetWind: + { + SetWind* cmdSetWind = (SetWind*)cmd; + + writer->Write((uint8_t)0); // 0x01 + writer->Write((uint8_t)0); // 0x02 + writer->Write((uint8_t)0); // 0x03 + + writer->Write(cmdSetWind->windWest); // 0x04 + writer->Write(cmdSetWind->windVertical); // 0x05 + writer->Write(cmdSetWind->windSouth); // 0x06 + writer->Write(cmdSetWind->clothFlappingStrength); // 0x07 + } + break; + case RoomCommand::SetTimeSettings: + { + SetTimeSettings* cmdTime = (SetTimeSettings*)cmd; + + writer->Write((uint8_t)0); // 0x01 + writer->Write((uint8_t)0); // 0x02 + writer->Write((uint8_t)0); // 0x03 + + writer->Write(cmdTime->hour); // 0x04 + writer->Write(cmdTime->min); // 0x05 + writer->Write(cmdTime->unk); // 0x06 + writer->Write((uint8_t)0); // 0x07 + } + break; + case RoomCommand::SetSkyboxModifier: + { + SetSkyboxModifier* cmdSkybox = (SetSkyboxModifier*)cmd; + + writer->Write((uint8_t)0); // 0x01 + writer->Write((uint8_t)0); // 0x02 + writer->Write((uint8_t)0); // 0x03 + + writer->Write(cmdSkybox->disableSky); // 0x04 + writer->Write(cmdSkybox->disableSunMoon); // 0x05 + writer->Write((uint8_t)0); // 0x06 + writer->Write((uint8_t)0); // 0x07 + } + break; + case RoomCommand::SetEchoSettings: + { + SetEchoSettings* cmdEcho = (SetEchoSettings*)cmd; + + writer->Write((uint8_t)0); // 0x01 + writer->Write((uint8_t)0); // 0x02 + writer->Write((uint8_t)0); // 0x03 + writer->Write((uint8_t)0); // 0x04 + writer->Write((uint8_t)0); // 0x05 + writer->Write((uint8_t)0); // 0x06 + writer->Write((uint8_t)cmdEcho->echo); // 0x07 + } + break; + case RoomCommand::SetSoundSettings: + { + SetSoundSettings* cmdSound = (SetSoundSettings*)cmd; + + writer->Write((uint8_t)cmdSound->reverb); // 0x01 + writer->Write((uint8_t)0); // 0x02 + writer->Write((uint8_t)0); // 0x03 + writer->Write((uint8_t)0); // 0x04 + writer->Write((uint8_t)0); // 0x05 + + writer->Write(cmdSound->nightTimeSFX); // 0x06 + writer->Write(cmdSound->musicSequence); // 0x07 + } + break; + case RoomCommand::SetSkyboxSettings: + { + SetSkyboxSettings* cmdSkybox = (SetSkyboxSettings*)cmd; + + writer->Write((uint8_t)cmdSkybox->unk1); // 0x01 + writer->Write((uint8_t)0); // 0x02 + writer->Write((uint8_t)0); // 0x03 + writer->Write((uint8_t)cmdSkybox->skyboxNumber); // 0x04 + writer->Write((uint8_t)cmdSkybox->cloudsType); // 0x05 + writer->Write((uint8_t)cmdSkybox->isIndoors); // 0x06 + } + break; + case RoomCommand::SetRoomBehavior: + { + SetRoomBehavior* cmdRoom = (SetRoomBehavior*)cmd; + + writer->Write((uint8_t)cmdRoom->gameplayFlags); // 0x01 + writer->Write((uint8_t)0); // 0x02 + writer->Write((uint8_t)0); // 0x03 + writer->Write(cmdRoom->gameplayFlags2); // 0x04 + } + break; + case RoomCommand::SetCsCamera: + { + SetCsCamera* cmdCsCam = (SetCsCamera*)cmd; + + writer->Write((uint8_t)cmdCsCam->cameras.size()); // 0x01 + writer->Write((uint8_t)0); // 0x02 + writer->Write((uint8_t)0); // 0x03 + + writer->Write(cmdCsCam->segmentOffset); // 0x04 + } + break; + case RoomCommand::SetMesh: + { + SetMesh* cmdMesh = (SetMesh*)cmd; + + int baseStreamEnd = writer->GetStream().get()->GetLength(); + + writer->Write((uint8_t)cmdMesh->data); // 0x01 + writer->Write((uint8_t)0); // 0x02 + writer->Write((uint8_t)0); // 0x03 + + writer->Write(baseStreamEnd); // 0x04 + + uint32_t oldOffset = writer->GetBaseAddress(); + writer->Seek(baseStreamEnd, SeekOffsetType::Start); + + // TODO: NOT DONE + + writer->Write(cmdMesh->meshHeaderType); + + if (cmdMesh->meshHeaderType == 0) + { + // writer->Write(cmdMesh->) + } + else if (cmdMesh->meshHeaderType == 1) + { + } + else if (cmdMesh->meshHeaderType == 2) + { + } + + writer->Seek(oldOffset, SeekOffsetType::Start); + } + break; + case RoomCommand::SetCameraSettings: + { + SetCameraSettings* cmdCam = (SetCameraSettings*)cmd; + + writer->Write((uint8_t)cmdCam->cameraMovement); // 0x01 + writer->Write((uint8_t)0); // 0x02 + writer->Write((uint8_t)0); // 0x03 + writer->Write(cmdCam->mapHighlight); // 0x04 + } + break; + case RoomCommand::SetLightingSettings: + { + SetLightingSettings* cmdLight = (SetLightingSettings*)cmd; + + writer->Write((uint8_t)cmdLight->settings.size()); // 0x01 + writer->Write((uint8_t)0); // 0x02 + writer->Write((uint8_t)0); // 0x03 + writer->Write(cmdLight->segmentOffset); // 0x04 + + uint32_t oldOffset = writer->GetBaseAddress(); + writer->Seek(cmdLight->segmentOffset, SeekOffsetType::Start); + + for (LightingSettings setting : cmdLight->settings) + { + writer->Write(setting.ambientClrR); + writer->Write(setting.ambientClrG); + writer->Write(setting.ambientClrB); + + writer->Write(setting.diffuseClrA_R); + writer->Write(setting.diffuseClrA_G); + writer->Write(setting.diffuseClrA_B); + + writer->Write(setting.diffuseDirA_X); + writer->Write(setting.diffuseDirA_Y); + writer->Write(setting.diffuseDirA_Z); + + writer->Write(setting.diffuseClrB_R); + writer->Write(setting.diffuseClrB_G); + writer->Write(setting.diffuseClrB_B); + + writer->Write(setting.diffuseDirB_X); + writer->Write(setting.diffuseDirB_Y); + writer->Write(setting.diffuseDirB_Z); + + writer->Write(setting.fogClrR); + writer->Write(setting.fogClrG); + writer->Write(setting.fogClrB); + + writer->Write(setting.unk); + writer->Write(setting.drawDistance); + } + + writer->Seek(oldOffset, SeekOffsetType::Start); + } + break; + case RoomCommand::SetRoomList: + { + SetRoomList* cmdRoom = (SetRoomList*)cmd; + + writer->Write((uint8_t)cmdRoom->romfile->rooms.size()); // 0x01 + writer->Write((uint8_t)0); // 0x02 + writer->Write((uint8_t)0); // 0x03 + + auto baseStreamEnd = writer->GetLength(); + writer->Write(baseStreamEnd); // 0x04 + + uint32_t oldOffset = writer->GetBaseAddress(); + writer->Seek(baseStreamEnd, SeekOffsetType::Start); + + for (const auto& entry : cmdRoom->romfile->rooms) + { + writer->Write(entry.virtualAddressStart); + writer->Write(entry.virtualAddressEnd); + } + + writer->Seek(oldOffset, SeekOffsetType::Start); + } + break; + case RoomCommand::SetCollisionHeader: + { + SetCollisionHeader* cmdCollHeader = (SetCollisionHeader*)cmd; + + int streamEnd = writer->GetStream().get()->GetLength(); + + writer->Write((uint8_t)0); // 0x01 + writer->Write((uint8_t)0); // 0x02 + writer->Write((uint8_t)0); // 0x03 + writer->Write(streamEnd); // 0x04 + + // TODO: NOT DONE + + uint32_t oldOffset = writer->GetBaseAddress(); + writer->Seek(streamEnd, SeekOffsetType::Start); + + ExporterExample_Collision colExp = ExporterExample_Collision(); + + colExp.Save(cmdCollHeader->collisionHeader, outPath, writer); + + writer->Seek(oldOffset, SeekOffsetType::Start); + } + break; + case RoomCommand::SetEntranceList: + { + SetEntranceList* cmdEntrance = (SetEntranceList*)cmd; + + uint32_t baseStreamEnd = writer->GetStream().get()->GetLength(); + + writer->Write((uint8_t)0); // 0x01 + writer->Write((uint8_t)0); // 0x02 + writer->Write((uint8_t)0); // 0x03 + writer->Write(baseStreamEnd); // 0x04 + + uint32_t oldOffset = writer->GetBaseAddress(); + writer->Seek(baseStreamEnd, SeekOffsetType::Start); + + for (EntranceEntry entry : cmdEntrance->entrances) + { + writer->Write((uint8_t)entry.startPositionIndex); + writer->Write((uint8_t)entry.roomToLoad); + } + + writer->Seek(oldOffset, SeekOffsetType::Start); + } + break; + case RoomCommand::SetSpecialObjects: + { + SetSpecialObjects* cmdSpecObj = (SetSpecialObjects*)cmd; + + writer->Write((uint8_t)cmdSpecObj->elfMessage); // 0x01 + writer->Write((uint8_t)0); // 0x02 + writer->Write((uint8_t)0); // 0x03 + writer->Write((uint8_t)0); // 0x04 + writer->Write((uint8_t)0); // 0x05 + writer->Write((uint16_t)cmdSpecObj->globalObject); // 0x06 + } + break; + case RoomCommand::SetStartPositionList: + { + SetStartPositionList* cmdStartPos = (SetStartPositionList*)cmd; + + uint32_t baseStreamEnd = writer->GetStream().get()->GetLength(); + + writer->Write((uint8_t)cmdStartPos->actors.size()); // 0x01 + writer->Write((uint8_t)0); // 0x02 + writer->Write((uint8_t)0); // 0x03 + writer->Write(baseStreamEnd); // 0x04 + + uint32_t oldOffset = writer->GetBaseAddress(); + writer->Seek(baseStreamEnd, SeekOffsetType::Start); + + for (ActorSpawnEntry entry : cmdStartPos->actors) + { + writer->Write(entry.actorNum); + writer->Write(entry.posX); + writer->Write(entry.posY); + writer->Write(entry.posZ); + writer->Write(entry.rotX); + writer->Write(entry.rotY); + writer->Write(entry.rotZ); + writer->Write(entry.initVar); + } + + writer->Seek(oldOffset, SeekOffsetType::Start); + } + break; + case RoomCommand::EndMarker: + { + writer->Write((uint8_t)0); // 0x01 + writer->Write((uint8_t)0); // 0x02 + writer->Write((uint8_t)0); // 0x03 + writer->Write((uint8_t)0); // 0x04 + writer->Write((uint8_t)0); // 0x05 + writer->Write((uint8_t)0); // 0x06 + writer->Write((uint8_t)0); // 0x07 + } + break; + default: + printf("UNIMPLEMENTED COMMAND: %i\n", (int)cmd->cmdID); + + writer->Write((uint8_t)0); // 0x01 + writer->Write((uint8_t)0); // 0x02 + writer->Write((uint8_t)0); // 0x03 + writer->Write((uint8_t)0); // 0x04 + writer->Write((uint8_t)0); // 0x05 + writer->Write((uint8_t)0); // 0x06 + writer->Write((uint8_t)0); // 0x07 + + break; + } + } + + // writer->Close(); + // File::WriteAllBytes(StringHelper::Sprintf("%s", res->GetName().c_str()), + // memStream->ToVector()); +} diff --git a/tools/ZAPD/ExporterTest/RoomExporter.h b/tools/ZAPD/ExporterTest/RoomExporter.h new file mode 100644 index 0000000000..ee531dc87b --- /dev/null +++ b/tools/ZAPD/ExporterTest/RoomExporter.h @@ -0,0 +1,10 @@ +#pragma once + +#include "ZResource.h" +#include "ZRoom/ZRoom.h" + +class ExporterExample_Room : public ZResourceExporter +{ +public: + void Save(ZResource* res, fs::path outPath, BinaryWriter* writer) override; +}; \ No newline at end of file diff --git a/tools/ZAPD/ExporterTest/TextureExporter.cpp b/tools/ZAPD/ExporterTest/TextureExporter.cpp new file mode 100644 index 0000000000..6488bed3a2 --- /dev/null +++ b/tools/ZAPD/ExporterTest/TextureExporter.cpp @@ -0,0 +1,14 @@ +#include "TextureExporter.h" +#include "../ZAPD/ZFile.h" + +void ExporterExample_Texture::Save(ZResource* res, [[maybe_unused]] fs::path outPath, + BinaryWriter* writer) +{ + ZTexture* tex = (ZTexture*)res; + + auto data = tex->parent->GetRawData(); + + for (offset_t i = tex->GetRawDataIndex(); i < tex->GetRawDataIndex() + tex->GetRawDataSize(); + i++) + writer->Write(data[i]); +} diff --git a/tools/ZAPD/ExporterTest/TextureExporter.h b/tools/ZAPD/ExporterTest/TextureExporter.h new file mode 100644 index 0000000000..ffe6001dca --- /dev/null +++ b/tools/ZAPD/ExporterTest/TextureExporter.h @@ -0,0 +1,11 @@ +#pragma once + +#include +#include "ZResource.h" +#include "ZTexture.h" + +class ExporterExample_Texture : public ZResourceExporter +{ +public: + void Save(ZResource* res, fs::path outPath, BinaryWriter* writer) override; +}; \ No newline at end of file diff --git a/tools/ZAPD/Jenkinsfile b/tools/ZAPD/Jenkinsfile index 3062c4851b..051e5f9982 100644 --- a/tools/ZAPD/Jenkinsfile +++ b/tools/ZAPD/Jenkinsfile @@ -1,70 +1,90 @@ pipeline { agent { - label "ZAPD" + label 'ZAPD' } stages { + // Non-parallel ZAPD stage stage('Build ZAPD') { steps { sh 'make -j' } } - stage('Checkout oot') { - steps { - dir('oot') { - git url: 'https://github.com/zeldaret/oot.git' - } - } - } - stage('Set up oot') { - steps { - dir('oot') { - sh 'cp /usr/local/etc/roms/baserom_oot.z64 baserom_original.z64' - // Identical to `make setup` except for copying our newer ZAPD.out into oot - sh 'git submodule update --init --recursive' - sh 'make -C tools' - sh 'cp ../ZAPD.out tools/ZAPD/' - sh 'python3 fixbaserom.py' - sh 'python3 extract_baserom.py' - sh 'python3 extract_assets.py' + // CHECKOUT THE REPOS + stage('Checkout Repos') { + parallel { + stage('Checkout oot') { + steps { + dir('oot') { + git url: 'https://github.com/zeldaret/oot.git' + } + } } - } - } - stage('Build oot') { - steps { - dir('oot') { - sh 'make -j' + + stage('Checkout mm') { + steps{ + dir('mm') { + git url: 'https://github.com/zeldaret/mm.git' + } + } } } } - stage('Checkout mm') { - steps { - dir('mm') { - git url: 'https://github.com/zeldaret/mm.git' - } - } - } - stage('Set up mm') { - steps { - dir('mm') { - sh 'cp /usr/local/etc/roms/mm.us.rev1.z64 baserom.mm.us.rev1.z64' + // SETUP THE REPOS + stage('Set up repos') { + parallel { + stage('Setup OOT') { + steps { + dir('oot') { + sh 'cp /usr/local/etc/roms/baserom_oot.z64 baserom_original.z64' - // Identical to `make setup` except for copying our newer ZAPD.out into mm - sh 'git submodule update --init --recursive' - sh 'make -C tools' - sh 'cp ../ZAPD.out tools/ZAPD/' - sh 'python3 tools/extract_rom.py baserom.mm.us.rev1.z64' - sh 'python3 extract_assets.py' + // Identical to `make setup` except for copying our newer ZAPD.out into oot + sh 'git submodule update --init --recursive' + sh 'make -C tools' + sh 'cp ../ZAPD.out tools/ZAPD/' + sh 'python3 fixbaserom.py' + sh 'python3 extract_baserom.py' + sh 'python3 extract_assets.py' + } + } + } + + stage('Setup MM') { + steps { + dir('mm') { + sh 'cp /usr/local/etc/roms/mm.us.rev1.z64 baserom.mm.us.rev1.z64' + + // Identical to `make setup` except for copying our newer ZAPD.out into mm + sh 'make -C tools' + sh 'cp ../ZAPD.out tools/ZAPD/' + sh 'python3 tools/fixbaserom.py' + sh 'python3 tools/extract_baserom.py' + sh 'python3 extract_assets.py -t 4' + } + } } } } - stage('Build mm') { - steps { - dir('mm') { - sh 'make assembly -j' - sh 'make -j' + + // BUILD THE REPOS + stage('Build repos') { + parallel { + stage('Build oot') { + steps { + dir('oot') { + sh 'make -j' + } + } + } + stage('Build mm') { + steps { + dir('mm') { + sh 'make -j disasm' + sh 'make -j all' + } + } } } } diff --git a/tools/ZAPD/Makefile b/tools/ZAPD/Makefile index afd50e0167..737b85ecf7 100644 --- a/tools/ZAPD/Makefile +++ b/tools/ZAPD/Makefile @@ -1,78 +1,118 @@ +# use variables in submakes +export OPTIMIZATION_ON ?= 1 ASAN ?= 0 DEPRECATION_ON ?= 1 DEBUG ?= 0 -CXXFLAGS ?= -COPYCHECK_ARGS ?= +COPYCHECK_ARGS ?= +LLD ?= 0 -CXX := g++ -INC := -I ZAPD -I lib/assimp/include -I lib/elfio -I lib/json/include -I lib/stb -I lib/tinygltf -I lib/libgfxd -I lib/tinyxml2 -CXXFLAGS += -fpic -std=c++17 -Wall -fno-omit-frame-pointer +# Use clang++ if available, else use g++ +ifeq ($(shell command -v clang++ >/dev/null 2>&1; echo $$?),0) + CXX := clang++ +else + CXX := g++ +endif + +INC := -I ZAPD -I lib/elfio -I lib/libgfxd -I lib/tinyxml2 -I ZAPDUtils +CXXFLAGS := -fpic -std=c++17 -Wall -Wextra -fno-omit-frame-pointer +OPTFLAGS := ifneq ($(DEBUG),0) OPTIMIZATION_ON = 0 - DEPRECATION_OFF = 1 - CXXFLAGS += -g3 -DDEVELOPMENT + CXXFLAGS += -g3 -DDEVELOPMENT -D_DEBUG COPYCHECK_ARGS += --devel DEPRECATION_ON = 0 +else + CXXFLAGS += -Werror endif ifeq ($(OPTIMIZATION_ON),0) - CXXFLAGS += -O0 + OPTFLAGS := -O0 else -CXXFLAGS += -O2 -march=native -mtune=native + OPTFLAGS := -O2 -march=native -mtune=native endif ifneq ($(ASAN),0) - CXXFLAGS += -fsanitize=address + CXXFLAGS += -fsanitize=address -fsanitize=pointer-compare -fsanitize=pointer-subtract -fsanitize=undefined endif ifneq ($(DEPRECATION_ON),0) CXXFLAGS += -DDEPRECATION_ON endif # CXXFLAGS += -DTEXTURE_DEBUG -LDFLAGS := -lstdc++ -lm -ldl -lpng +LDFLAGS := -lm -ldl -lpng + +# Use LLD if available. Set LLD=0 to not use it +ifeq ($(shell command -v ld.lld >/dev/null 2>&1; echo $$?),0) + LLD := 1 +endif + +ifneq ($(LLD),0) + LDFLAGS += -fuse-ld=lld +endif UNAME := $(shell uname) ifneq ($(UNAME), Darwin) LDFLAGS += -Wl,-export-dynamic -lstdc++fs endif -SRC_DIRS := ZAPD ZAPD/ZRoom ZAPD/ZRoom/Commands ZAPD/Overlays ZAPD/HighLevel +ZAPD_SRC_DIRS := $(shell find ZAPD -type d) +SRC_DIRS = $(ZAPD_SRC_DIRS) lib/tinyxml2 -ZAPD_CPP_FILES := $(foreach dir,$(SRC_DIRS),$(wildcard $(dir)/*.cpp)) -ZAPD_H_FILES := $(foreach dir,$(SRC_DIRS),$(wildcard $(dir)/*.h)) +ZAPD_CPP_FILES := $(foreach dir,$(ZAPD_SRC_DIRS),$(wildcard $(dir)/*.cpp)) +ZAPD_H_FILES := $(foreach dir,$(ZAPD_SRC_DIRS),$(wildcard $(dir)/*.h)) CPP_FILES += $(ZAPD_CPP_FILES) lib/tinyxml2/tinyxml2.cpp -O_FILES := $(CPP_FILES:.cpp=.o) +O_FILES := $(foreach f,$(CPP_FILES:.cpp=.o),build/$f) +O_FILES += build/ZAPD/BuildInfo.o +# create build directories +$(shell mkdir -p $(foreach dir,$(SRC_DIRS),build/$(dir))) + + +# Main targets all: ZAPD.out copycheck -genbuildinfo: +build/ZAPD/BuildInfo.o: python3 ZAPD/genbuildinfo.py $(COPYCHECK_ARGS) + $(CXX) $(CXXFLAGS) $(OPTFLAGS) $(INC) -c $(OUTPUT_OPTION) build/ZAPD/BuildInfo.cpp copycheck: ZAPD.out python3 copycheck.py clean: - rm -f $(O_FILES) ZAPD.out + rm -rf build ZAPD.out $(MAKE) -C lib/libgfxd clean + $(MAKE) -C ZAPDUtils clean + $(MAKE) -C ExporterTest clean rebuild: clean all format: clang-format-11 -i $(ZAPD_CPP_FILES) $(ZAPD_H_FILES) + $(MAKE) -C ZAPDUtils format + $(MAKE) -C ExporterTest format -.PHONY: all genbuildinfo copycheck clean rebuild format +.PHONY: all build/ZAPD/BuildInfo.o copycheck clean rebuild format -%.o: %.cpp - $(CXX) $(CXXFLAGS) $(INC) -c $< -o $@ +build/%.o: %.cpp + $(CXX) $(CXXFLAGS) $(OPTFLAGS) $(INC) -c $(OUTPUT_OPTION) $< -ZAPD/Main.o: genbuildinfo ZAPD/Main.cpp - $(CXX) $(CXXFLAGS) $(INC) -c ZAPD/Main.cpp -o $@ +# Submakes lib/libgfxd/libgfxd.a: $(MAKE) -C lib/libgfxd -ZAPD.out: $(O_FILES) lib/libgfxd/libgfxd.a - $(CXX) $(CXXFLAGS) $(INC) $(O_FILES) lib/libgfxd/libgfxd.a -o $@ $(FS_INC) $(LDFLAGS) +.PHONY: ExporterTest +ExporterTest: + $(MAKE) -C ExporterTest + +.PHONY: ZAPDUtils +ZAPDUtils: + $(MAKE) -C ZAPDUtils + + +# Linking +ZAPD.out: $(O_FILES) lib/libgfxd/libgfxd.a ExporterTest ZAPDUtils + $(CXX) $(CXXFLAGS) $(O_FILES) lib/libgfxd/libgfxd.a ZAPDUtils/ZAPDUtils.a -Wl,--whole-archive ExporterTest/ExporterTest.a -Wl,--no-whole-archive $(LDFLAGS) $(OUTPUT_OPTION) diff --git a/tools/ZAPD/README.md b/tools/ZAPD/README.md index 719492d92b..e2764b6277 100644 --- a/tools/ZAPD/README.md +++ b/tools/ZAPD/README.md @@ -30,7 +30,8 @@ You can configure a bit your ZAPD build with the following options: - `DEBUG`: If non-zero, ZAPD will be compiled in _development mode_. This implies the following: - Debugging symbols enabled (`-g3`). They are disabled by default. - `OPTIMIZATION_ON=0`: Disables optimizations (`-O0`). - - `DEPRECATION_OFF=1`: Disables deprecation warnings. + - `DEPRECATION_ON=0`: Disables deprecation warnings. +- `LLD=1`: builds with the LLVM linker `ld.lld` instead of the system default. As an example, if you want to build ZAPD with optimizations disabled and use the address sanitizer, you could use the following command: @@ -109,6 +110,10 @@ ZAPD also accepts the following list of extra parameters: - Can be used only in `e` or `bsf` modes. - `-tm MODE`: Test Mode (enables certain experimental features). To enable it, set `MODE` to `1`. - `-wno` / `--warn-no-offsets` : Enable warnings for nodes that dont have offsets specified. Takes priority over `-eno`/ `--error-no-offsets`. -- `-eno`/ `--error-no-offsets` : Enable errors for nodes that dont have offsets specified. +- `-eno` / `--error-no-offsets` : Enable errors for nodes that dont have offsets specified. +- `-se` / `--set-exporter` : Sets which exporter to use. +- `--gcc-compat` : Enables GCC compatible mode. Slower. +- `-s` / `--static` : Mark every asset as `static`. + - This behaviour can be overridden per asset using `Static=` in the respective XML node. Additionally, you can pass the flag `--version` to see the current ZAPD version. If that flag is passed, ZAPD will ignore any other parameter passed. diff --git a/tools/ZAPD/ZAPD.sln b/tools/ZAPD/ZAPD.sln index 4280808b49..82538dd9f4 100644 --- a/tools/ZAPD/ZAPD.sln +++ b/tools/ZAPD/ZAPD.sln @@ -5,6 +5,10 @@ VisualStudioVersion = 16.0.30320.27 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ZAPD", "ZAPD\ZAPD.vcxproj", "{B53F9E5B-0A58-4BAE-9AFE-856C8CBB8D36}" EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ExporterExample", "ExporterTest\ExporterTest.vcxproj", "{65608EB0-1A47-45AD-AB66-192FB64C762C}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ZAPDUtils", "ZAPDUtils\ZAPDUtils.vcxproj", "{A2E01C3E-D647-45D1-9788-043DEBC1A908}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x64 = Debug|x64 @@ -33,6 +37,38 @@ Global {B53F9E5B-0A58-4BAE-9AFE-856C8CBB8D36}.RelWithDebInfo|x64.Build.0 = Release|x64 {B53F9E5B-0A58-4BAE-9AFE-856C8CBB8D36}.RelWithDebInfo|x86.ActiveCfg = Release|Win32 {B53F9E5B-0A58-4BAE-9AFE-856C8CBB8D36}.RelWithDebInfo|x86.Build.0 = Release|Win32 + {65608EB0-1A47-45AD-AB66-192FB64C762C}.Debug|x64.ActiveCfg = Debug|x64 + {65608EB0-1A47-45AD-AB66-192FB64C762C}.Debug|x64.Build.0 = Debug|x64 + {65608EB0-1A47-45AD-AB66-192FB64C762C}.Debug|x86.ActiveCfg = Debug|Win32 + {65608EB0-1A47-45AD-AB66-192FB64C762C}.Debug|x86.Build.0 = Debug|Win32 + {65608EB0-1A47-45AD-AB66-192FB64C762C}.MinSizeRel|x64.ActiveCfg = Debug|x64 + {65608EB0-1A47-45AD-AB66-192FB64C762C}.MinSizeRel|x64.Build.0 = Debug|x64 + {65608EB0-1A47-45AD-AB66-192FB64C762C}.MinSizeRel|x86.ActiveCfg = Debug|Win32 + {65608EB0-1A47-45AD-AB66-192FB64C762C}.MinSizeRel|x86.Build.0 = Debug|Win32 + {65608EB0-1A47-45AD-AB66-192FB64C762C}.Release|x64.ActiveCfg = Release|x64 + {65608EB0-1A47-45AD-AB66-192FB64C762C}.Release|x64.Build.0 = Release|x64 + {65608EB0-1A47-45AD-AB66-192FB64C762C}.Release|x86.ActiveCfg = Release|Win32 + {65608EB0-1A47-45AD-AB66-192FB64C762C}.Release|x86.Build.0 = Release|Win32 + {65608EB0-1A47-45AD-AB66-192FB64C762C}.RelWithDebInfo|x64.ActiveCfg = Release|x64 + {65608EB0-1A47-45AD-AB66-192FB64C762C}.RelWithDebInfo|x64.Build.0 = Release|x64 + {65608EB0-1A47-45AD-AB66-192FB64C762C}.RelWithDebInfo|x86.ActiveCfg = Release|Win32 + {65608EB0-1A47-45AD-AB66-192FB64C762C}.RelWithDebInfo|x86.Build.0 = Release|Win32 + {A2E01C3E-D647-45D1-9788-043DEBC1A908}.Debug|x64.ActiveCfg = Debug|x64 + {A2E01C3E-D647-45D1-9788-043DEBC1A908}.Debug|x64.Build.0 = Debug|x64 + {A2E01C3E-D647-45D1-9788-043DEBC1A908}.Debug|x86.ActiveCfg = Debug|Win32 + {A2E01C3E-D647-45D1-9788-043DEBC1A908}.Debug|x86.Build.0 = Debug|Win32 + {A2E01C3E-D647-45D1-9788-043DEBC1A908}.MinSizeRel|x64.ActiveCfg = Debug|x64 + {A2E01C3E-D647-45D1-9788-043DEBC1A908}.MinSizeRel|x64.Build.0 = Debug|x64 + {A2E01C3E-D647-45D1-9788-043DEBC1A908}.MinSizeRel|x86.ActiveCfg = Debug|Win32 + {A2E01C3E-D647-45D1-9788-043DEBC1A908}.MinSizeRel|x86.Build.0 = Debug|Win32 + {A2E01C3E-D647-45D1-9788-043DEBC1A908}.Release|x64.ActiveCfg = Release|x64 + {A2E01C3E-D647-45D1-9788-043DEBC1A908}.Release|x64.Build.0 = Release|x64 + {A2E01C3E-D647-45D1-9788-043DEBC1A908}.Release|x86.ActiveCfg = Release|Win32 + {A2E01C3E-D647-45D1-9788-043DEBC1A908}.Release|x86.Build.0 = Release|Win32 + {A2E01C3E-D647-45D1-9788-043DEBC1A908}.RelWithDebInfo|x64.ActiveCfg = Release|x64 + {A2E01C3E-D647-45D1-9788-043DEBC1A908}.RelWithDebInfo|x64.Build.0 = Release|x64 + {A2E01C3E-D647-45D1-9788-043DEBC1A908}.RelWithDebInfo|x86.ActiveCfg = Release|Win32 + {A2E01C3E-D647-45D1-9788-043DEBC1A908}.RelWithDebInfo|x86.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/tools/ZAPD/ZAPD/Declaration.cpp b/tools/ZAPD/ZAPD/Declaration.cpp index 63a3918050..d2a86ffcc5 100644 --- a/tools/ZAPD/ZAPD/Declaration.cpp +++ b/tools/ZAPD/ZAPD/Declaration.cpp @@ -1,37 +1,31 @@ #include "Declaration.h" -Declaration::Declaration(DeclarationAlignment nAlignment, DeclarationPadding nPadding, size_t nSize, - std::string nText) +#include "Globals.h" +#include "Utils/StringHelper.h" + +Declaration::Declaration(offset_t nAddress, DeclarationAlignment nAlignment, size_t nSize, + const std::string& nText) { + address = nAddress; alignment = nAlignment; - padding = nPadding; size = nSize; text = nText; } -Declaration::Declaration(DeclarationAlignment nAlignment, size_t nSize, std::string nVarType, - std::string nVarName, bool nIsArray, std::string nText) - : Declaration(nAlignment, DeclarationPadding::None, nSize, nText) +Declaration::Declaration(offset_t nAddress, DeclarationAlignment nAlignment, size_t nSize, + const std::string& nVarType, const std::string& nVarName, bool nIsArray, + const std::string& nText) + : Declaration(nAddress, nAlignment, nSize, nText) { varType = nVarType; varName = nVarName; isArray = nIsArray; } -Declaration::Declaration(DeclarationAlignment nAlignment, DeclarationPadding nPadding, size_t nSize, - std::string nVarType, std::string nVarName, bool nIsArray, - std::string nText) - : Declaration(nAlignment, nPadding, nSize, nText) -{ - varType = nVarType; - varName = nVarName; - isArray = nIsArray; -} - -Declaration::Declaration(DeclarationAlignment nAlignment, size_t nSize, std::string nVarType, - std::string nVarName, bool nIsArray, size_t nArrayItemCnt, - std::string nText) - : Declaration(nAlignment, DeclarationPadding::None, nSize, nText) +Declaration::Declaration(offset_t nAddress, DeclarationAlignment nAlignment, size_t nSize, + const std::string& nVarType, const std::string& nVarName, bool nIsArray, + size_t nArrayItemCnt, const std::string& nText) + : Declaration(nAddress, nAlignment, nSize, nText) { varType = nVarType; varName = nVarName; @@ -39,10 +33,10 @@ Declaration::Declaration(DeclarationAlignment nAlignment, size_t nSize, std::str arrayItemCnt = nArrayItemCnt; } -Declaration::Declaration(DeclarationAlignment nAlignment, size_t nSize, std::string nVarType, - std::string nVarName, bool nIsArray, std::string nArrayItemCntStr, - std::string nText) - : Declaration(nAlignment, DeclarationPadding::None, nSize, nText) +Declaration::Declaration(offset_t nAddress, DeclarationAlignment nAlignment, size_t nSize, + const std::string& nVarType, const std::string& nVarName, bool nIsArray, + const std::string& nArrayItemCntStr, const std::string& nText) + : Declaration(nAddress, nAlignment, nSize, nText) { varType = nVarType; varName = nVarName; @@ -50,30 +44,179 @@ Declaration::Declaration(DeclarationAlignment nAlignment, size_t nSize, std::str arrayItemCntStr = nArrayItemCntStr; } -Declaration::Declaration(DeclarationAlignment nAlignment, size_t nSize, std::string nVarType, - std::string nVarName, bool nIsArray, size_t nArrayItemCnt, - std::string nText, bool nIsExternal) - : Declaration(nAlignment, nSize, nVarType, nVarName, nIsArray, nArrayItemCnt, nText) +Declaration::Declaration(offset_t nAddress, DeclarationAlignment nAlignment, size_t nSize, + const std::string& nVarType, const std::string& nVarName, bool nIsArray, + size_t nArrayItemCnt, const std::string& nText, bool nIsExternal) + : Declaration(nAddress, nAlignment, nSize, nVarType, nVarName, nIsArray, nArrayItemCnt, nText) { isExternal = nIsExternal; } -Declaration::Declaration(DeclarationAlignment nAlignment, DeclarationPadding nPadding, size_t nSize, - std::string nVarType, std::string nVarName, bool nIsArray, - size_t nArrayItemCnt, std::string nText) - : Declaration(nAlignment, nPadding, nSize, nText) -{ - varType = nVarType; - varName = nVarName; - isArray = nIsArray; - arrayItemCnt = nArrayItemCnt; -} - -Declaration::Declaration(std::string nIncludePath, size_t nSize, std::string nVarType, - std::string nVarName) - : Declaration(DeclarationAlignment::None, DeclarationPadding::None, nSize, "") +Declaration::Declaration(offset_t nAddress, const std::string& nIncludePath, size_t nSize, + const std::string& nVarType, const std::string& nVarName) + : Declaration(nAddress, DeclarationAlignment::Align4, nSize, "") { includePath = nIncludePath; varType = nVarType; varName = nVarName; } + +bool Declaration::IsStatic() const +{ + switch (staticConf) + { + case StaticConfig::Off: + return false; + + case StaticConfig::Global: + return Globals::Instance->forceStatic; + + case StaticConfig::On: + return true; + } + + return false; +} + +std::string Declaration::GetNormalDeclarationStr() const +{ + std::string output; + + if (preText != "") + output += preText + "\n"; + + if (IsStatic()) + { + output += "static "; + } + + if (isArray) + { + if (arrayItemCntStr != "") + { + output += StringHelper::Sprintf("%s %s[%s];\n", varType.c_str(), varName.c_str(), + arrayItemCntStr.c_str()); + } + else if (arrayItemCnt == 0) + { + output += StringHelper::Sprintf("%s %s[] = {\n", varType.c_str(), varName.c_str()); + } + else + { + output += StringHelper::Sprintf("%s %s[%i] = {\n", varType.c_str(), varName.c_str(), + arrayItemCnt); + } + + output += text + "\n"; + } + else + { + output += StringHelper::Sprintf("%s %s = { ", varType.c_str(), varName.c_str()); + output += text; + } + + if (output.back() == '\n') + output += "};"; + else + output += " };"; + + if (rightText != "") + output += " " + rightText + ""; + + output += "\n"; + + if (postText != "") + output += postText + "\n"; + + output += "\n"; + + return output; +} + +std::string Declaration::GetExternalDeclarationStr() const +{ + std::string output; + + if (preText != "") + output += preText + "\n"; + + if (IsStatic()) + { + output += "static "; + } + + if (arrayItemCntStr != "") + output += + StringHelper::Sprintf("%s %s[%s] = {\n#include \"%s\"\n};", varType.c_str(), + varName.c_str(), arrayItemCntStr.c_str(), includePath.c_str()); + else if (arrayItemCnt != 0) + output += StringHelper::Sprintf("%s %s[%i] = {\n#include \"%s\"\n};", varType.c_str(), + varName.c_str(), arrayItemCnt, includePath.c_str()); + else + output += StringHelper::Sprintf("%s %s[] = {\n#include \"%s\"\n};", varType.c_str(), + varName.c_str(), includePath.c_str()); + + if (rightText != "") + output += " " + rightText + ""; + + output += "\n"; + + if (postText != "") + output += postText + "\n"; + + output += "\n"; + + return output; +} + +std::string Declaration::GetExternStr() const +{ + if (IsStatic() || varType == "") + { + return ""; + } + + if (isArray) + { + if (arrayItemCntStr != "") + { + return StringHelper::Sprintf("extern %s %s[%s];\n", varType.c_str(), varName.c_str(), + arrayItemCntStr.c_str()); + } + else if (arrayItemCnt != 0) + return StringHelper::Sprintf("extern %s %s[%i];\n", varType.c_str(), varName.c_str(), + arrayItemCnt); + else + return StringHelper::Sprintf("extern %s %s[];\n", varType.c_str(), varName.c_str()); + } + + return StringHelper::Sprintf("extern %s %s;\n", varType.c_str(), varName.c_str()); +} + +std::string Declaration::GetStaticForwardDeclarationStr() const +{ + if (!IsStatic() || isUnaccounted) + return ""; + + if (isArray) + { + if (arrayItemCntStr == "" && arrayItemCnt == 0) + { + // Forward declaring static arrays without specifying the size is not allowed. + return ""; + } + + if (arrayItemCntStr != "") + { + return StringHelper::Sprintf("static %s %s[%s];\n", varType.c_str(), varName.c_str(), + arrayItemCntStr.c_str()); + } + else + { + return StringHelper::Sprintf("static %s %s[%i];\n", varType.c_str(), varName.c_str(), + arrayItemCnt); + } + } + + return StringHelper::Sprintf("static %s %s;\n", varType.c_str(), varName.c_str()); +} diff --git a/tools/ZAPD/ZAPD/Declaration.h b/tools/ZAPD/ZAPD/Declaration.h index fa8653b858..138524a4c2 100644 --- a/tools/ZAPD/ZAPD/Declaration.h +++ b/tools/ZAPD/ZAPD/Declaration.h @@ -3,28 +3,32 @@ #include #include +// TODO: should we drop the `_t` suffix because of UNIX compliance? +typedef uint32_t segptr_t; +typedef uint32_t offset_t; + +#define SEGMENTED_NULL ((segptr_t)0) + enum class DeclarationAlignment { - None, Align4, Align8, Align16 }; -enum class DeclarationPadding +enum class StaticConfig { - None, - Pad4, - Pad8, - Pad16 + Off, + Global, + On }; class Declaration { public: + offset_t address; DeclarationAlignment alignment; - DeclarationPadding padding; - size_t size = 0; + size_t size; std::string preText; std::string text; std::string rightText; @@ -38,28 +42,38 @@ public: bool isArray = false; size_t arrayItemCnt = 0; std::string arrayItemCntStr; - std::vector references; + std::vector references; bool isUnaccounted = false; bool isPlaceholder = false; + bool declaredInXml = false; + StaticConfig staticConf = StaticConfig::Global; - Declaration(DeclarationAlignment nAlignment, size_t nSize, std::string nVarType, - std::string nVarName, bool nIsArray, std::string nText); - Declaration(DeclarationAlignment nAlignment, DeclarationPadding nPadding, size_t nSize, - std::string nVarType, std::string nVarName, bool nIsArray, std::string nText); - Declaration(DeclarationAlignment nAlignment, size_t nSize, std::string nVarType, - std::string nVarName, bool nIsArray, size_t nArrayItemCnt, std::string nText); - Declaration(DeclarationAlignment nAlignment, size_t nSize, std::string nVarType, - std::string nVarName, bool nIsArray, std::string nArrayItemCntStr, - std::string nText); - Declaration(DeclarationAlignment nAlignment, size_t nSize, std::string nVarType, - std::string nVarName, bool nIsArray, size_t nArrayItemCnt, std::string nText, - bool nIsExternal); - Declaration(DeclarationAlignment nAlignment, DeclarationPadding nPadding, size_t nSize, - std::string nVarType, std::string nVarName, bool nIsArray, size_t nArrayItemCnt, - std::string nText); - Declaration(std::string nIncludePath, size_t nSize, std::string nVarType, std::string nVarName); + Declaration(offset_t nAddress, DeclarationAlignment nAlignment, size_t nSize, + const std::string& nVarType, const std::string& nVarName, bool nIsArray, + const std::string& nText); + Declaration(offset_t nAddress, DeclarationAlignment nAlignment, size_t nSize, + const std::string& nVarType, const std::string& nVarName, bool nIsArray, + size_t nArrayItemCnt, const std::string& nText); + Declaration(offset_t nAddress, DeclarationAlignment nAlignment, size_t nSize, + const std::string& nVarType, const std::string& nVarName, bool nIsArray, + const std::string& nArrayItemCntStr, const std::string& nText); + Declaration(offset_t nAddress, DeclarationAlignment nAlignment, size_t nSize, + const std::string& nVarType, const std::string& nVarName, bool nIsArray, + size_t nArrayItemCnt, const std::string& nText, bool nIsExternal); + + Declaration(offset_t nAddress, const std::string& nIncludePath, size_t nSize, + const std::string& nVarType, const std::string& nVarName); + + bool IsStatic() const; + + std::string GetNormalDeclarationStr() const; + std::string GetExternalDeclarationStr() const; + + std::string GetExternStr() const; + + std::string GetStaticForwardDeclarationStr() const; protected: - Declaration(DeclarationAlignment nAlignment, DeclarationPadding nPadding, size_t nSize, - std::string nText); + Declaration(offset_t nAddress, DeclarationAlignment nAlignment, size_t nSize, + const std::string& nText); }; diff --git a/tools/ZAPD/ZAPD/GameConfig.cpp b/tools/ZAPD/ZAPD/GameConfig.cpp new file mode 100644 index 0000000000..f197493a4a --- /dev/null +++ b/tools/ZAPD/ZAPD/GameConfig.cpp @@ -0,0 +1,184 @@ +#include "GameConfig.h" + +#include +#include + +#include "Utils/Directory.h" +#include "Utils/File.h" +#include "Utils/Path.h" +#include "ZFile.h" +#include "tinyxml2.h" + +using ConfigFunc = void (GameConfig::*)(const tinyxml2::XMLElement&); + +GameConfig::~GameConfig() +{ + for (auto& declPair : segmentRefFiles) + { + for (auto& file : declPair.second) + { + delete file; + } + } +} + +void GameConfig::ReadTexturePool(const fs::path& texturePoolXmlPath) +{ + tinyxml2::XMLDocument doc; + tinyxml2::XMLError eResult = doc.LoadFile(texturePoolXmlPath.c_str()); + + if (eResult != tinyxml2::XML_SUCCESS) + { + fprintf(stderr, "Warning: Unable to read texture pool XML with error code %i\n", eResult); + return; + } + + tinyxml2::XMLNode* root = doc.FirstChild(); + + if (root == nullptr) + return; + + for (tinyxml2::XMLElement* child = root->FirstChildElement(); child != nullptr; + child = child->NextSiblingElement()) + { + if (std::string_view(child->Name()) == "Texture") + { + std::string crcStr = child->Attribute("CRC"); + fs::path texPath = child->Attribute("Path"); + std::string texName; + + uint32_t crc = strtoul(crcStr.c_str(), nullptr, 16); + + texturePool[crc].path = texPath; + } + } +} + +void GameConfig::GenSymbolMap(const fs::path& symbolMapPath) +{ + auto symbolLines = File::ReadAllLines(symbolMapPath); + + for (std::string& symbolLine : symbolLines) + { + auto split = StringHelper::Split(symbolLine, " "); + uint32_t addr = strtoul(split[0].c_str(), nullptr, 16); + std::string symbolName = split[1]; + + symbolMap[addr] = std::move(symbolName); + } +} + +void GameConfig::ConfigFunc_SymbolMap(const tinyxml2::XMLElement& element) +{ + std::string fileName = element.Attribute("File"); + GenSymbolMap(Path::GetDirectoryName(configFilePath) / fileName); +} + +void GameConfig::ConfigFunc_ActorList(const tinyxml2::XMLElement& element) +{ + std::string fileName = element.Attribute("File"); + std::vector lines = + File::ReadAllLines(Path::GetDirectoryName(configFilePath) / fileName); + + for (auto& line : lines) + actorList.emplace_back(std::move(line)); +} + +void GameConfig::ConfigFunc_ObjectList(const tinyxml2::XMLElement& element) +{ + std::string fileName = element.Attribute("File"); + std::vector lines = + File::ReadAllLines(Path::GetDirectoryName(configFilePath) / fileName); + + for (auto& line : lines) + objectList.emplace_back(std::move(line)); +} + +void GameConfig::ConfigFunc_TexturePool(const tinyxml2::XMLElement& element) +{ + std::string fileName = element.Attribute("File"); + ReadTexturePool(Path::GetDirectoryName(configFilePath) / fileName); +} + +void GameConfig::ConfigFunc_BGConfig(const tinyxml2::XMLElement& element) +{ + bgScreenWidth = element.IntAttribute("ScreenWidth", 320); + bgScreenHeight = element.IntAttribute("ScreenHeight", 240); +} + +void GameConfig::ConfigFunc_ExternalXMLFolder(const tinyxml2::XMLElement& element) +{ + const char* pathValue = element.Attribute("Path"); + if (pathValue == nullptr) + { + throw std::runtime_error( + StringHelper::Sprintf("Parse: Fatal error in configuration file.\n" + "\t Missing 'Path' attribute in `ExternalXMLFolder` element.\n")); + } + if (externalXmlFolder != "") + { + throw std::runtime_error(StringHelper::Sprintf("Parse: Fatal error in configuration file.\n" + "\t `ExternalXMLFolder` is duplicated.\n")); + } + externalXmlFolder = pathValue; +} + +void GameConfig::ConfigFunc_ExternalFile(const tinyxml2::XMLElement& element) +{ + const char* xmlPathValue = element.Attribute("XmlPath"); + if (xmlPathValue == nullptr) + { + throw std::runtime_error( + StringHelper::Sprintf("Parse: Fatal error in configuration file.\n" + "\t Missing 'XmlPath' attribute in `ExternalFile` element.\n")); + } + const char* outPathValue = element.Attribute("OutPath"); + if (outPathValue == nullptr) + { + throw std::runtime_error( + StringHelper::Sprintf("Parse: Fatal error in configuration file.\n" + "\t Missing 'OutPath' attribute in `ExternalFile` element.\n")); + } + + externalFiles.push_back(ExternalFile(fs::path(xmlPathValue), fs::path(outPathValue))); +} + +void GameConfig::ReadConfigFile(const fs::path& argConfigFilePath) +{ + static const std::map ConfigFuncDictionary = { + {"SymbolMap", &GameConfig::ConfigFunc_SymbolMap}, + {"ActorList", &GameConfig::ConfigFunc_ActorList}, + {"ObjectList", &GameConfig::ConfigFunc_ObjectList}, + {"TexturePool", &GameConfig::ConfigFunc_TexturePool}, + {"BGConfig", &GameConfig::ConfigFunc_BGConfig}, + {"ExternalXMLFolder", &GameConfig::ConfigFunc_ExternalXMLFolder}, + {"ExternalFile", &GameConfig::ConfigFunc_ExternalFile}, + }; + + configFilePath = argConfigFilePath; + tinyxml2::XMLDocument doc; + tinyxml2::XMLError eResult = doc.LoadFile(configFilePath.c_str()); + + if (eResult != tinyxml2::XML_SUCCESS) + { + throw std::runtime_error("Error: Unable to read config file."); + } + + tinyxml2::XMLNode* root = doc.FirstChild(); + + if (root == nullptr) + return; + + for (tinyxml2::XMLElement* child = root->FirstChildElement(); child != nullptr; + child = child->NextSiblingElement()) + { + auto it = ConfigFuncDictionary.find(child->Name()); + if (it == ConfigFuncDictionary.end()) + { + fprintf(stderr, "Unsupported configuration variable: %s\n", child->Name()); + continue; + } + + std::invoke(it->second, *this, *child); + } +} diff --git a/tools/ZAPD/ZAPD/GameConfig.h b/tools/ZAPD/ZAPD/GameConfig.h new file mode 100644 index 0000000000..c478d16ceb --- /dev/null +++ b/tools/ZAPD/ZAPD/GameConfig.h @@ -0,0 +1,58 @@ +#pragma once + +#include +#include +#include +#include + +#include "Utils/Directory.h" +#include "tinyxml2.h" + +struct TexturePoolEntry +{ + fs::path path = ""; // Path to Shared Texture +}; + +class ExternalFile +{ +public: + fs::path xmlPath, outPath; + + ExternalFile(fs::path nXmlPath, fs::path nOutPath); +}; + +class ZFile; + +class GameConfig +{ +public: + std::string configFilePath; + std::map> segmentRefFiles; + std::map symbolMap; + std::vector actorList; + std::vector objectList; + std::map texturePool; // Key = CRC + + // ZBackground + uint32_t bgScreenWidth = 320, bgScreenHeight = 240; + + // ExternalFile + fs::path externalXmlFolder; + std::vector externalFiles; + + GameConfig() = default; + ~GameConfig(); + + void ReadTexturePool(const fs::path& texturePoolXmlPath); + void GenSymbolMap(const fs::path& symbolMapPath); + + void ConfigFunc_SymbolMap(const tinyxml2::XMLElement& element); + void ConfigFunc_ActorList(const tinyxml2::XMLElement& element); + void ConfigFunc_ObjectList(const tinyxml2::XMLElement& element); + void ConfigFunc_TexturePool(const tinyxml2::XMLElement& element); + void ConfigFunc_BGConfig(const tinyxml2::XMLElement& element); + void ConfigFunc_ExternalXMLFolder(const tinyxml2::XMLElement& element); + void ConfigFunc_ExternalFile(const tinyxml2::XMLElement& element); + + void ReadConfigFile(const fs::path& configFilePath); +}; diff --git a/tools/ZAPD/ZAPD/Globals.cpp b/tools/ZAPD/ZAPD/Globals.cpp index 5de7843cdb..51880b5d51 100644 --- a/tools/ZAPD/ZAPD/Globals.cpp +++ b/tools/ZAPD/ZAPD/Globals.cpp @@ -1,10 +1,11 @@ #include "Globals.h" -#include -#include "File.h" -#include "Path.h" -#include "tinyxml2.h" -using namespace tinyxml2; +#include +#include + +#include +#include +#include "tinyxml2.h" Globals* Globals::Instance; @@ -12,176 +13,183 @@ Globals::Globals() { Instance = this; - files = std::vector(); - segments = std::vector(); - symbolMap = std::map(); - segmentRefs = std::map(); - segmentRefFiles = std::map(); game = ZGame::OOT_RETAIL; genSourceFile = true; testMode = false; profile = false; useLegacyZDList = false; useExternalResources = true; - lastScene = nullptr; verbosity = VerbosityLevel::VERBOSITY_SILENT; outputPath = Directory::GetCurrentDirectory(); } -std::string Globals::FindSymbolSegRef(int32_t segNumber, uint32_t symbolAddress) -{ - if (segmentRefs.find(segNumber) != segmentRefs.end()) - { - if (segmentRefFiles.find(segNumber) == segmentRefFiles.end()) - { - XMLDocument doc; - std::string filePath = segmentRefs[segNumber]; - XMLError eResult = doc.LoadFile(filePath.c_str()); - - if (eResult != tinyxml2::XML_SUCCESS) - return "ERROR"; - - XMLNode* root = doc.FirstChild(); - - if (root == nullptr) - return "ERROR"; - - for (XMLElement* child = root->FirstChildElement(); child != NULL; - child = child->NextSiblingElement()) - { - if (std::string(child->Name()) == "File") - { - ZFile* file = new ZFile(fileMode, child, "", "", filePath, true); - file->GeneratePlaceholderDeclarations(); - segmentRefFiles[segNumber] = file; - break; - } - } - } - - return segmentRefFiles[segNumber]->GetDeclarationName(symbolAddress, "ERROR"); - } - - return "ERROR"; -} - -void Globals::ReadConfigFile(const std::string& configFilePath) -{ - XMLDocument doc; - XMLError eResult = doc.LoadFile(configFilePath.c_str()); - - if (eResult != tinyxml2::XML_SUCCESS) - { - throw std::runtime_error("Error: Unable to read config file."); - return; - } - - XMLNode* root = doc.FirstChild(); - - if (root == nullptr) - return; - - for (XMLElement* child = root->FirstChildElement(); child != NULL; - child = child->NextSiblingElement()) - { - if (std::string(child->Name()) == "SymbolMap") - { - std::string fileName = std::string(child->Attribute("File")); - GenSymbolMap(Path::GetDirectoryName(configFilePath) + "/" + fileName); - } - else if (std::string(child->Name()) == "Segment") - { - std::string fileName = std::string(child->Attribute("File")); - int32_t segNumber = child->IntAttribute("Number"); - segmentRefs[segNumber] = fileName; - } - else if (std::string(child->Name()) == "ActorList") - { - std::string fileName = std::string(child->Attribute("File")); - std::vector lines = - File::ReadAllLines(Path::GetDirectoryName(configFilePath) + "/" + fileName); - - for (std::string line : lines) - cfg.actorList.push_back(StringHelper::Strip(line, "\r")); - } - else if (std::string(child->Name()) == "ObjectList") - { - std::string fileName = std::string(child->Attribute("File")); - std::vector lines = - File::ReadAllLines(Path::GetDirectoryName(configFilePath) + "/" + fileName); - - for (std::string line : lines) - cfg.objectList.push_back(StringHelper::Strip(line, "\r")); - } - else if (std::string(child->Name()) == "TexturePool") - { - std::string fileName = std::string(child->Attribute("File")); - ReadTexturePool(Path::GetDirectoryName(configFilePath) + "/" + fileName); - } - else if (std::string(child->Name()) == "BGConfig") - { - cfg.bgScreenWidth = child->IntAttribute("ScreenWidth", 320); - cfg.bgScreenHeight = child->IntAttribute("ScreenHeight", 240); - } - } -} - -void Globals::ReadTexturePool(const std::string& texturePoolXmlPath) -{ - XMLDocument doc; - XMLError eResult = doc.LoadFile(texturePoolXmlPath.c_str()); - - if (eResult != tinyxml2::XML_SUCCESS) - { - fprintf(stderr, "Warning: Unable to read texture pool XML with error code %i\n", eResult); - return; - } - - XMLNode* root = doc.FirstChild(); - - if (root == nullptr) - return; - - for (XMLElement* child = root->FirstChildElement(); child != NULL; - child = child->NextSiblingElement()) - { - if (std::string(child->Name()) == "Texture") - { - std::string crcStr = std::string(child->Attribute("CRC")); - fs::path texPath = std::string(child->Attribute("Path")); - std::string texName = ""; - - uint32_t crc = strtoul(crcStr.c_str(), NULL, 16); - - cfg.texturePool[crc].path = texPath; - } - } -} - -void Globals::GenSymbolMap(const std::string& symbolMapPath) -{ - auto symbolLines = File::ReadAllLines(symbolMapPath); - - for (std::string symbolLine : symbolLines) - { - auto split = StringHelper::Split(symbolLine, " "); - uint32_t addr = strtoul(split[0].c_str(), NULL, 16); - std::string symbolName = split[1]; - - symbolMap[addr] = symbolName; - } -} - void Globals::AddSegment(int32_t segment, ZFile* file) { if (std::find(segments.begin(), segments.end(), segment) == segments.end()) segments.push_back(segment); + if (cfg.segmentRefFiles.find(segment) == cfg.segmentRefFiles.end()) + cfg.segmentRefFiles[segment] = std::vector(); - segmentRefs[segment] = file->GetXmlFilePath(); - segmentRefFiles[segment] = file; + cfg.segmentRefFiles[segment].push_back(file); } bool Globals::HasSegment(int32_t segment) { return std::find(segments.begin(), segments.end(), segment) != segments.end(); } + +std::map* Globals::GetExporterMap() +{ + static std::map exporters; + return &exporters; +} + +void Globals::AddExporter(std::string exporterName, ExporterSet* exporterSet) +{ + auto exporters = GetExporterMap(); + (*exporters)[exporterName] = exporterSet; +} + +ZResourceExporter* Globals::GetExporter(ZResourceType resType) +{ + auto exporters = *GetExporterMap(); + + if (currentExporter != "" && exporters[currentExporter]->exporters.find(resType) != + exporters[currentExporter]->exporters.end()) + return exporters[currentExporter]->exporters[resType]; + else + return nullptr; +} + +ExporterSet* Globals::GetExporterSet() +{ + auto exporters = *GetExporterMap(); + + if (currentExporter != "") + return exporters[currentExporter]; + else + return nullptr; +} + +bool Globals::GetSegmentedPtrName(segptr_t segAddress, ZFile* currentFile, + const std::string& expectedType, std::string& declName) +{ + if (segAddress == 0) + { + declName = "NULL"; + return true; + } + + uint8_t segment = GETSEGNUM(segAddress); + uint32_t offset = Seg2Filespace(segAddress, currentFile->baseAddress); + ZSymbol* sym; + + sym = currentFile->GetSymbolResource(offset); + if (sym != nullptr) + { + if (expectedType == "" || expectedType == sym->GetSourceTypeName()) + { + declName = sym->GetName(); + return true; + } + } + sym = currentFile->GetSymbolResource(segAddress); + if (sym != nullptr) + { + if (expectedType == "" || expectedType == sym->GetSourceTypeName()) + { + declName = sym->GetName(); + return true; + } + } + + if (currentFile->IsSegmentedInFilespaceRange(segAddress)) + { + if (currentFile->GetDeclarationPtrName(segAddress, expectedType, declName)) + return true; + } + else if (HasSegment(segment)) + { + for (auto file : cfg.segmentRefFiles[segment]) + { + offset = Seg2Filespace(segAddress, file->baseAddress); + + sym = file->GetSymbolResource(offset); + if (sym != nullptr) + { + if (expectedType == "" || expectedType == sym->GetSourceTypeName()) + { + declName = sym->GetName(); + return true; + } + } + sym = file->GetSymbolResource(segAddress); + if (sym != nullptr) + { + if (expectedType == "" || expectedType == sym->GetSourceTypeName()) + { + declName = sym->GetName(); + return true; + } + } + + if (file->IsSegmentedInFilespaceRange(segAddress)) + { + if (file->GetDeclarationPtrName(segAddress, expectedType, declName)) + return true; + } + } + } + + const auto& symbolFromMap = Globals::Instance->symbolMap.find(segAddress); + if (symbolFromMap != Globals::Instance->symbolMap.end()) + { + declName = "&" + symbolFromMap->second; + return true; + } + + declName = StringHelper::Sprintf("0x%08X", segAddress); + return false; +} + +bool Globals::GetSegmentedArrayIndexedName(segptr_t segAddress, size_t elementSize, + ZFile* currentFile, const std::string& expectedType, + std::string& declName) +{ + if (segAddress == 0) + { + declName = "NULL"; + return true; + } + + uint8_t segment = GETSEGNUM(segAddress); + + if (currentFile->IsSegmentedInFilespaceRange(segAddress)) + { + bool addressFound = currentFile->GetDeclarationArrayIndexedName(segAddress, elementSize, + expectedType, declName); + if (addressFound) + return true; + } + else if (HasSegment(segment)) + { + for (auto file : cfg.segmentRefFiles[segment]) + { + if (file->IsSegmentedInFilespaceRange(segAddress)) + { + bool addressFound = file->GetDeclarationArrayIndexedName(segAddress, elementSize, + expectedType, declName); + if (addressFound) + return true; + } + } + } + + declName = StringHelper::Sprintf("0x%08X", segAddress); + return false; +} + +ExternalFile::ExternalFile(fs::path nXmlPath, fs::path nOutPath) + : xmlPath{nXmlPath}, outPath{nOutPath} +{ +} diff --git a/tools/ZAPD/ZAPD/Globals.h b/tools/ZAPD/ZAPD/Globals.h index 61c07f8d1c..e90efc25fc 100644 --- a/tools/ZAPD/ZAPD/Globals.h +++ b/tools/ZAPD/ZAPD/Globals.h @@ -3,9 +3,10 @@ #include #include #include +#include "GameConfig.h" #include "ZFile.h" -#include "ZRoom/ZRoom.h" -#include "ZTexture.h" + +class ZRoom; enum class VerbosityLevel { @@ -14,25 +15,23 @@ enum class VerbosityLevel VERBOSITY_DEBUG }; -struct TexturePoolEntry -{ - fs::path path = ""; // Path to Shared Texture -}; +typedef void (*ExporterSetFunc)(ZFile*); +typedef bool (*ExporterSetFuncBool)(ZFileMode fileMode); +typedef void (*ExporterSetFuncVoid)(int argc, char* argv[], int& i); +typedef void (*ExporterSetFuncVoid2)(const std::string& buildMode, ZFileMode& fileMode); +typedef void (*ExporterSetFuncVoid3)(); -class GameConfig +class ExporterSet { public: - std::map segmentRefs; - std::map segmentRefFiles; - std::map symbolMap; - std::vector actorList; - std::vector objectList; - std::map texturePool; // Key = CRC - - // ZBackground - uint32_t bgScreenWidth = 320, bgScreenHeight = 240; - - GameConfig() = default; + std::map exporters; + ExporterSetFuncVoid parseArgsFunc = nullptr; + ExporterSetFuncVoid2 parseFileModeFunc = nullptr; + ExporterSetFuncBool processFileModeFunc = nullptr; + ExporterSetFunc beginFileFunc = nullptr; + ExporterSetFunc endFileFunc = nullptr; + ExporterSetFuncVoid3 beginXMLFunc = nullptr; + ExporterSetFuncVoid3 endXMLFunc = nullptr; }; class Globals @@ -56,35 +55,37 @@ public: bool warnNoOffset = false; bool errorNoOffset = false; bool verboseUnaccounted = false; + bool gccCompat = false; + bool forceStatic = false; std::vector files; + std::vector externalFiles; std::vector segments; - std::map segmentRefs; - std::map segmentRefFiles; - ZRoom* lastScene; std::map symbolMap; + std::string currentExporter; + static std::map* GetExporterMap(); + static void AddExporter(std::string exporterName, ExporterSet* exporterSet); + Globals(); - std::string FindSymbolSegRef(int32_t segNumber, uint32_t symbolAddress); - void ReadConfigFile(const std::string& configFilePath); - void ReadTexturePool(const std::string& texturePoolXmlPath); - void GenSymbolMap(const std::string& symbolMapPath); + void AddSegment(int32_t segment, ZFile* file); bool HasSegment(int32_t segment); -}; -/* - * Note: In being able to track references across files, there are a few major files that make use - * of segments... - * Segment 1: nintendo_rogo_static/title_static - * Segment 2: parameter_static - * Segment 4: gameplay_keep - * Segment 5: gameplay_field_keep, gameplay_dangeon_keep - * Segment 7: link_animetion - * Segment 8: icon_item_static - * Segment 9: icon_item_24_static - * Segment 12: icon_item_field_static, icon_item_dungeon_static - * Segment 13: icon_item_nes_static - * - * I'm thinking a config file could be usable, but I'll have to experiment... - */ + ZResourceExporter* GetExporter(ZResourceType resType); + ExporterSet* GetExporterSet(); + + /** + * Search in every file (and the symbol map) for the `segAddress` passed as parameter. + * If the segment of `currentFile` is the same segment of `segAddress`, then that file will be + * used only, otherwise, the search will be performed in every other file. + * The name of that variable will be stored in the `declName` parameter. + * Returns `true` if the address is found. `false` otherwise, + * in which case `declName` will be set to the address formatted as a pointer. + */ + bool GetSegmentedPtrName(segptr_t segAddress, ZFile* currentFile, + const std::string& expectedType, std::string& declName); + + bool GetSegmentedArrayIndexedName(segptr_t segAddress, size_t elementSize, ZFile* currentFile, + const std::string& expectedType, std::string& declName); +}; diff --git a/tools/ZAPD/ZAPD/HighLevel/HLAnimation.h b/tools/ZAPD/ZAPD/HighLevel/HLAnimation.h deleted file mode 100644 index 52d6847a66..0000000000 --- a/tools/ZAPD/ZAPD/HighLevel/HLAnimation.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include - -/* - * The high level format for animations. - */ - -class HLAnimation -{ -public: -}; \ No newline at end of file diff --git a/tools/ZAPD/ZAPD/HighLevel/HLAnimationIntermediette.cpp b/tools/ZAPD/ZAPD/HighLevel/HLAnimationIntermediette.cpp deleted file mode 100644 index a316ddf6f4..0000000000 --- a/tools/ZAPD/ZAPD/HighLevel/HLAnimationIntermediette.cpp +++ /dev/null @@ -1,110 +0,0 @@ -#include "HLAnimationIntermediette.h" - -using namespace tinyxml2; - -HLAnimationIntermediette::HLAnimationIntermediette() -{ - limit = 0; - limbCount = 0; - frameCount = 0; - rotationValues = std::vector(); - rotationIndices = std::vector(); -} - -HLAnimationIntermediette::~HLAnimationIntermediette() -{ -} - -HLAnimationIntermediette* HLAnimationIntermediette::FromXML(std::string xmlPath) -{ - HLAnimationIntermediette* anim = new HLAnimationIntermediette(); - XMLDocument doc; - - doc.LoadFile(xmlPath.c_str()); - - XMLElement* root = doc.RootElement(); - - anim->limit = root->IntAttribute("Limit"); - anim->limbCount = root->IntAttribute("LimbCount"); - anim->frameCount = root->IntAttribute("FrameCount"); - - for (XMLElement* child = root->FirstChildElement(); child != NULL; - child = child->NextSiblingElement()) - { - if (std::string(child->Name()) == "RotationValues") - { - for (XMLElement* child2 = child->FirstChildElement(); child2 != NULL; - child2 = child2->NextSiblingElement()) - { - std::string value = child2->GetText(); - anim->rotationValues.push_back(atoi(value.c_str())); - } - } - else if (std::string(child->Name()) == "RotationIndices") - { - for (XMLElement* child2 = child->FirstChildElement(); child2 != NULL; - child2 = child2->NextSiblingElement()) - anim->rotationIndices.push_back(RotationIndex(child2->IntAttribute("X"), - child2->IntAttribute("Y"), - child2->IntAttribute("Z"))); - } - } - - return anim; -} - -HLAnimationIntermediette* HLAnimationIntermediette::FromZAnimation(ZAnimation* zAnim) -{ - HLAnimationIntermediette* anim = new HLAnimationIntermediette(); - - return anim; -} - -ZAnimation* HLAnimationIntermediette::ToZAnimation() -{ - ZAnimation* zAnim = new ZNormalAnimation(nullptr); - - return zAnim; -} - -std::string HLAnimationIntermediette::OutputXML() -{ - std::string output = ""; - XMLDocument doc; - - XMLElement* root = doc.NewElement("HLAnimationIntermediette"); - root->SetAttribute("Limit", limit); - root->SetAttribute("LimbCount", limbCount); - root->SetAttribute("FrameCount", frameCount); - - doc.InsertFirstChild(root); - - XMLElement* rotValues = doc.NewElement("RotationValues"); - - for (size_t i = 0; i < rotationValues.size(); i++) - { - XMLElement* rotValue = doc.NewElement("Value"); - rotValue->SetText(rotationValues[i]); - rotValues->InsertEndChild(rotValue); - } - - root->InsertEndChild(rotValues); - - XMLElement* rotIndices = doc.NewElement("RotationIndices"); - - for (size_t i = 0; i < rotationIndices.size(); i++) - { - XMLElement* rotIndex = doc.NewElement("Value"); - rotIndex->SetAttribute("X", rotationIndices[i].x); - rotIndex->SetAttribute("Y", rotationIndices[i].y); - rotIndex->SetAttribute("Z", rotationIndices[i].z); - rotIndices->InsertEndChild(rotIndex); - } - - root->InsertEndChild(rotIndices); - - XMLPrinter printer; - - doc.Accept(&printer); - return printer.CStr(); -} \ No newline at end of file diff --git a/tools/ZAPD/ZAPD/HighLevel/HLAnimationIntermediette.h b/tools/ZAPD/ZAPD/HighLevel/HLAnimationIntermediette.h deleted file mode 100644 index 171ac9d4d9..0000000000 --- a/tools/ZAPD/ZAPD/HighLevel/HLAnimationIntermediette.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once - -#include -#include "../ZAnimation.h" -#include "HLFileIntermediette.h" -#include "tinyxml2.h" - -/* - * An intermediette format for animations. Going to use XML. - * Goes from FBX->XML->C - * Note: At the moment this is a very direct representation of the output format. - * Optimally we can determine where the keyframes are and remove redundant information. - */ - -class HLAnimationIntermediette -{ -public: - int16_t frameCount; - int16_t limit; - int16_t limbCount; - std::vector rotationValues; - std::vector rotationIndices; - - HLAnimationIntermediette(); - ~HLAnimationIntermediette(); - - std::string OutputXML(); - ZAnimation* ToZAnimation(); - - static HLAnimationIntermediette* FromXML(std::string xmlPath); - static HLAnimationIntermediette* FromZAnimation(ZAnimation* zAnim); -}; \ No newline at end of file diff --git a/tools/ZAPD/ZAPD/HighLevel/HLFileIntermediette.h b/tools/ZAPD/ZAPD/HighLevel/HLFileIntermediette.h deleted file mode 100644 index ef16bb8fd9..0000000000 --- a/tools/ZAPD/ZAPD/HighLevel/HLFileIntermediette.h +++ /dev/null @@ -1,5 +0,0 @@ -#pragma once - -class HLFileIntermediette -{ -}; \ No newline at end of file diff --git a/tools/ZAPD/ZAPD/HighLevel/HLModelIntermediette.cpp b/tools/ZAPD/ZAPD/HighLevel/HLModelIntermediette.cpp deleted file mode 100644 index f08dec4a86..0000000000 --- a/tools/ZAPD/ZAPD/HighLevel/HLModelIntermediette.cpp +++ /dev/null @@ -1,1185 +0,0 @@ -#include "HLModelIntermediette.h" -#include "../File.h" -#include "../Globals.h" -#include "../Path.h" -#include "../StringHelper.h" -#include "../ZDisplayList.h" - -#ifdef USE_ASSIMP -#include -#include -#include -#include -#endif - -using namespace tinyxml2; - -HLModelIntermediette::HLModelIntermediette() -{ - blocks = std::vector(); - startIndex = 0; - meshStartIndex = 0; - hasSkeleton = false; - lastTrans = Vec3s(0, 0, 0); -} - -HLModelIntermediette::~HLModelIntermediette() -{ -} - -HLModelIntermediette* HLModelIntermediette::FromXML(tinyxml2::XMLElement* root) -{ - HLModelIntermediette* model = new HLModelIntermediette(); - - for (XMLElement* child = root->FirstChildElement(); child != NULL; - child = child->NextSiblingElement()) - { - std::string childName = child->Name(); - HLIntermediette* block = nullptr; - - if (childName == "Mesh") - block = new HLMeshIntermediette(); - else if (childName == "Limb") - block = new HLLimbIntermediette(); - else if (childName == "Vertices") - block = new HLVerticesIntermediette(); - else if (childName == "Texture") - block = new HLTextureIntermediette(); - else if (childName == "Material") - block = new HLMaterialIntermediette(); - - if (block != nullptr) - { - block->parent = model; - block->InitFromXML(child); - model->blocks.push_back(block); - } - } - - return model; -} - -void HLModelIntermediette::FromZDisplayList(HLModelIntermediette* model, ZDisplayList* zDisplayList) -{ - HLLimbIntermediette* limb = new HLLimbIntermediette(); - limb->name = zDisplayList->GetName(); - - // Go through verts - std::vector finalVerts; - - int32_t vStart = -1; - - for (auto& pair : zDisplayList->vertices) - { - if (vStart == -1) // TODO: Find a better way to do this - vStart = pair.first; - - for (auto& v : pair.second) - finalVerts.push_back(v); - } - - HLVerticesIntermediette* vertIntr = new HLVerticesIntermediette(); - vertIntr->vertices = finalVerts; - vertIntr->name = StringHelper::Sprintf("%s_verts", zDisplayList->GetName().c_str()); - model->blocks.push_back(vertIntr); - - // Go through textures - // TODO: Textures are now stored directly in ZFile - /* - for (pair pair : zDisplayList->textures) - { - HLTextureIntermediette* texIntr = new HLTextureIntermediette(); - texIntr->tex = pair.second; - texIntr->name = texIntr->tex->GetName(); - - model->blocks.push_back(texIntr); - } - */ - - // Analyze display lists to determine components - HLDisplayListIntermediette* dList = new HLDisplayListIntermediette(); - dList->address = zDisplayList->GetRawDataIndex(); - int32_t startIndex = 0; - - // Go through the display lists and setup commands - int32_t meshCnt = 0; - - HLMeshIntermediette* mesh = new HLMeshIntermediette(); - mesh->name = StringHelper::Sprintf("%s_%i", zDisplayList->GetName().c_str(), meshCnt); - - int32_t matCnt = 0; - HLMaterialIntermediette* lastMat = new HLMaterialIntermediette(); - lastMat->name = StringHelper::Sprintf("Material_%i", matCnt); - - uint8_t lastClrR = 0, lastClrG = 0, lastClrB = 0, lastClrA = 0, lastClrM = 0, lastClrL = 0; - - startIndex = 0; - - for (size_t i = startIndex; i < zDisplayList->instructions.size(); i++) - { - uint64_t data = zDisplayList->instructions[i]; - F3DZEXOpcode opcode = (F3DZEXOpcode)(data >> 56); - - if (opcode == F3DZEXOpcode::G_SETOTHERMODE_L) - { - } - else if (opcode == F3DZEXOpcode::G_SETPRIMCOLOR) - { - int32_t mm = (data & 0x0000FF0000000000) >> 40; - int32_t ff = (data & 0x000000FF00000000) >> 32; - int32_t rr = (data & 0x00000000FF000000) >> 24; - int32_t gg = (data & 0x0000000000FF0000) >> 16; - int32_t bb = (data & 0x000000000000FF00) >> 8; - int32_t aa = (data & 0x00000000000000FF) >> 0; - - lastClrR = rr; - lastClrG = gg; - lastClrB = bb; - lastClrA = aa; - lastClrL = ff; - lastClrM = mm; - - lastMat->clrR = rr; - lastMat->clrG = gg; - lastMat->clrB = bb; - lastMat->clrA = aa; - lastMat->clrL = ff; - lastMat->clrM = mm; - } - else if (opcode == F3DZEXOpcode::G_SETTILE && - (F3DZEXOpcode)(zDisplayList->instructions[i - 1] >> 56) != - F3DZEXOpcode::G_RDPPIPESYNC) - { - int32_t cc = - (data & 0b0000000000000000000000000000000000000000000011000000000000000000) >> 18; - int32_t dd = - (data & 0b0000000000000000000000000000000000000000000000000000001100000000) >> 8; - - lastMat->cmtH = (HLMaterialCmt)cc; - lastMat->cmtV = (HLMaterialCmt)dd; - - matCnt++; - - if (matCnt > 1 && mesh->commands.size() > 0) - { - model->blocks.push_back(lastMat); - limb->commands.push_back(new HLLimbCommand(mesh->name, lastMat->name)); - lastMat = new HLMaterialIntermediette(); - lastMat->name = StringHelper::Sprintf("Material_%i", matCnt); - - lastMat->clrR = lastClrR; - lastMat->clrG = lastClrG; - lastMat->clrB = lastClrB; - lastMat->clrA = lastClrA; - lastMat->clrL = lastClrL; - lastMat->clrM = lastClrM; - - // Bit of a hack here... - // int32_t lastData = (int32_t)(zDisplayList->instructions[i - 1]); - // TODO - // string texName = zDisplayList->textures[lastData & 0x00FFFFFF]->GetName(); - // lastMat->textureName = texName; - - // -------------------------- - model->blocks.push_back(mesh); - - meshCnt++; - - mesh = new HLMeshIntermediette(); - mesh->name = - StringHelper::Sprintf("%s_%i", zDisplayList->GetName().c_str(), meshCnt); - } - } - else if (opcode == F3DZEXOpcode::G_SETTIMG) - { - // int32_t texAddress = data & 0x00FFFFFF; - - // TODO - // string texName = zDisplayList->textures[texAddress]->GetName(); - // lastMat->textureName = texName; - } - else if (opcode == F3DZEXOpcode::G_VTX) - { - int32_t nn = (data & 0x000FF00000000000ULL) >> 44; - int32_t aa = (data & 0x000000FF00000000ULL) >> 32; - int32_t startIndex = ((aa >> 1) - nn); - uint32_t vtxAddr = data & 0x00FFFFFF; - uint32_t diff = vtxAddr - vStart; - - startIndex += diff / 16; - - mesh->commands.push_back(new HLMeshCmdLoadVertices(nn, startIndex)); - } - else if (opcode == F3DZEXOpcode::G_TRI1) - { - int32_t aa = ((data & 0x00FF000000000000ULL) >> 48) / 2; - int32_t bb = ((data & 0x0000FF0000000000ULL) >> 40) / 2; - int32_t cc = ((data & 0x000000FF00000000ULL) >> 32) / 2; - - mesh->commands.push_back(new HLMeshCmdTriangle1(aa, bb, cc, 0)); - } - else if (opcode == F3DZEXOpcode::G_TRI2) - { - int32_t aa = ((data & 0x00FF000000000000ULL) >> 48) / 2; - int32_t bb = ((data & 0x0000FF0000000000ULL) >> 40) / 2; - int32_t cc = ((data & 0x000000FF00000000ULL) >> 32) / 2; - int32_t dd = ((data & 0x00000000FF0000ULL) >> 16) / 2; - int32_t ee = ((data & 0x0000000000FF00ULL) >> 8) / 2; - int32_t ff = ((data & 0x000000000000FFULL) >> 0) / 2; - - mesh->commands.push_back(new HLMeshCmdTriangle2(aa, bb, cc, 0, dd, ee, ff, 0)); - } - - // int32_t bp = 0; - } - - limb->commands.push_back(new HLLimbCommand(mesh->name, lastMat->name)); - model->blocks.push_back(lastMat); - model->blocks.push_back(mesh); - model->blocks.push_back(limb); -} - -void HLModelIntermediette::FromZSkeleton(HLModelIntermediette* model, ZSkeleton* zSkeleton) -{ - model->hasSkeleton = true; - - // Start at the root skeleton node, go down... - // ProcessZSkeletonLimb(model, zSkeleton, zSkeleton->limbs[0]); -} - -void HLModelIntermediette::ProcessZSkeletonLimb(HLModelIntermediette* model, ZSkeleton* zSkeleton, - ZLimb* limb) -{ - /* - if (limb->dList == nullptr && limb->dListPtr != 0) - limb->dList = (ZDisplayList*)zSkeleton->parent->FindResource(limb->dListPtr); - - if (limb->dList != nullptr) - { - auto cmdTrans = new HLSetTranslation(limb->transX, limb->transY, limb->transZ); - cmdTrans->parent = model; - model->blocks.push_back(cmdTrans); - - FromZDisplayList(model, limb->dList); - } - */ - - /*for (ZLimb* childLimb : limb->children) - { - ProcessZSkeletonLimb(model, zSkeleton, childLimb); - }*/ -} - -std::string HLModelIntermediette::ToOBJFile() -{ - std::string output = ""; - - for (HLIntermediette* block : blocks) - { - block->parent = this; - std::string code = block->OutputOBJ(); - - output += code; - - if (code != "") - output += "\n"; - } - - return output; -} - -std::string HLModelIntermediette::ToAssimpFile() -{ -#ifdef USE_ASSIMP - Assimp::Exporter exporter; - aiScene* newScene = new aiScene(); - newScene->mMeshes = new aiMesh*[128]; - newScene->mRootNode = new aiNode(); - newScene->mRootNode->mName = "RootNode"; - - std::vector vertices; - - int32_t idx = 0; - - for (HLIntermediette* block : blocks) - { - block->parent = this; - block->OutputAssimp(newScene, &vertices); - - idx++; - } - - newScene->mRootNode->mNumChildren += newScene->mNumMeshes; - newScene->mRootNode->mChildren = new aiNode*[newScene->mRootNode->mNumChildren]; - - for (size_t i = 0; i < newScene->mNumMeshes; i++) - { - aiNode* child = new aiNode(); - child->mName = StringHelper::Sprintf("OBJ_%i", i); - child->mNumMeshes = 1; - child->mMeshes = new uint32_t[1]; - child->mMeshes[0] = i; - child->mTransformation.Translation(aiVector3D(meshTranslations[i].x * 10, - meshTranslations[i].y * 10, - meshTranslations[i].z * 10), - child->mTransformation); - newScene->mRootNode->mChildren[i] = child; - } - - newScene->mNumMaterials = 1; - newScene->mMaterials = new aiMaterial*[1]; - newScene->mMaterials[0] = new aiMaterial(); - - exporter.Export(newScene, "fbx", "__export.fbx"); -#endif - - return ""; -} - -std::string HLModelIntermediette::OutputCode() -{ - std::string output = ""; - - for (HLIntermediette* block : blocks) - { - std::string code = block->OutputCode(); - - output += code; - - if (code != "") - output += "\n"; - } - - return output; -} - -std::string HLModelIntermediette::OutputXML() -{ - std::string output = ""; - XMLDocument doc; - - XMLElement* root = doc.NewElement("HLModelIntermediette"); - - for (HLIntermediette* block : blocks) - block->OutputXML(&doc, root); - - doc.InsertEndChild(root); - - XMLPrinter printer; - - doc.Accept(&printer); - return printer.CStr(); -} - -template -inline T* HLModelIntermediette::FindByName(std::string name) -{ - for (HLIntermediette* block : blocks) - { - if (typeid(*block) == typeid(T)) - { - if (block->name == name) - return (T*)block; - } - } - - return nullptr; -} - -template -inline T* HLModelIntermediette::FindByType() -{ - for (HLIntermediette* block : blocks) - { - if (typeid(*block) == typeid(T)) - return (T*)block; - } - - return nullptr; -} - -HLIntermediette::HLIntermediette() -{ - name = ""; - parent = nullptr; -} - -HLIntermediette::~HLIntermediette() -{ -} - -void HLIntermediette::InitFromXML(XMLElement* xmlElement) -{ - name = xmlElement->Attribute("Name"); -} - -std::string HLIntermediette::OutputCode() -{ - return ""; -} - -std::string HLIntermediette::OutputOBJ() -{ - return ""; -} - -void HLIntermediette::OutputAssimp(aiScene* scene, std::vector* verts) -{ -} - -void HLIntermediette::OutputXML(tinyxml2::XMLDocument* doc, tinyxml2::XMLElement* root) -{ -} - -void HLMeshCommand::InitFromXML(XMLElement* xmlElement) -{ -} - -std::string HLMeshCommand::OutputCode(HLModelIntermediette* parent) -{ - return ""; -} - -std::string HLMeshCommand::OutputOBJ(HLModelIntermediette* parent) -{ - return ""; -} - -void HLMeshCommand::OutputAssimp(HLModelIntermediette* parent, aiScene* scene, aiMesh* mesh) -{ -} - -void HLMeshCommand::OutputXML(tinyxml2::XMLElement* parent) -{ -} - -HLVerticesIntermediette::HLVerticesIntermediette() : HLIntermediette() -{ - vertices = std::vector(); -} - -void HLVerticesIntermediette::InitFromXML(XMLElement* verticesElement) -{ - name = verticesElement->Attribute("Name"); - - /* - for (XMLElement* child = verticesElement->FirstChildElement(); child != NULL; - child = child->NextSiblingElement()) - vertices.push_back(ZVtx(child->IntAttribute("X"), child->IntAttribute("Y"), - child->IntAttribute("Z"), child->IntAttribute("Flags"), - child->IntAttribute("S"), child->IntAttribute("T"), - child->IntAttribute("R"), child->IntAttribute("G"), - child->IntAttribute("B"), child->IntAttribute("A"))); - */ -} - -void HLVerticesIntermediette::InitFromVertices(std::vector dispListVertices) -{ - for (auto v : dispListVertices) - vertices.push_back(v); -} - -std::string HLVerticesIntermediette::OutputCode(HLModelIntermediette* parent) -{ - std::string output = ""; - - output += StringHelper::Sprintf("Vtx %s_verts[] = \n{\n", name.c_str()); - - for (auto v : vertices) - { - output += StringHelper::Sprintf(" { %i, %i, %i, %i, %i, %i, %i, %i, %i, %i },\n", v.x, - v.y, v.z, v.flag, v.s, v.t, v.r, v.g, v.b, v.a); - } - - output += StringHelper::Sprintf("};\n"); - - return output; -} - -std::string HLVerticesIntermediette::OutputOBJ() -{ - std::string output = ""; - - for (auto& v : vertices) - { - output += StringHelper::Sprintf("v %f %f %f %i %i %i %i\n", (float)v.x * 0.1f, - (float)v.y * 0.1f, (float)v.z * 0.1f, v.r, v.g, v.b, v.a); - } - - return output; -} - -void HLVerticesIntermediette::OutputAssimp(aiScene* scene, std::vector* verts) -{ - verts->clear(); - - for (size_t i = 0; i < vertices.size(); i++) - { - verts->push_back(aiVector3D(vertices[i].x, vertices[i].y, vertices[i].z)); - } -} - -void HLVerticesIntermediette::OutputXML(tinyxml2::XMLDocument* doc, tinyxml2::XMLElement* root) -{ - XMLElement* element = doc->NewElement("Vertices"); - - element->SetAttribute("Name", name.c_str()); - - for (auto& v : vertices) - { - XMLElement* vElem = doc->NewElement("Vertex"); - vElem->SetAttribute("X", v.x); - vElem->SetAttribute("Y", v.y); - vElem->SetAttribute("Z", v.z); - vElem->SetAttribute("Flag", v.flag); - vElem->SetAttribute("S", v.s); - vElem->SetAttribute("T", v.t); - vElem->SetAttribute("R", v.r); - vElem->SetAttribute("G", v.g); - vElem->SetAttribute("B", v.b); - vElem->SetAttribute("A", v.a); - - element->InsertEndChild(vElem); - } - - root->InsertEndChild(element); -} - -HLMeshCmdGeoSettings::HLMeshCmdGeoSettings() -{ - on = ""; - off = ""; -} - -void HLMeshCmdGeoSettings::InitFromXML(tinyxml2::XMLElement* xmlElement) -{ - on = xmlElement->Attribute("On"); - off = xmlElement->Attribute("Off"); -} - -std::string HLMeshCmdGeoSettings::OutputCode(HLModelIntermediette* parent) -{ - std::string output = ""; - - if (off != "") - output += - StringHelper::Sprintf("gsSPClearGeometryMode(G_TEXTURE_ENABLE | %s),\n", off.c_str()); - - if (on != "") - output += StringHelper::Sprintf("gsSPSetGeometryMode(G_TEXTURE_ENABLE | %s),", on.c_str()); - - return output; -} - -HLMeshCmdTriangle1::HLMeshCmdTriangle1() -{ - v0 = 0; - v1 = 0; - v2 = 0; - flag = 0; -} - -HLMeshCmdTriangle1::HLMeshCmdTriangle1(int32_t nV0, int32_t nV1, int32_t nV2, int32_t nFlag) -{ - v0 = nV0; - v1 = nV1; - v2 = nV2; - flag = nFlag; -} - -void HLMeshCmdTriangle1::InitFromXML(tinyxml2::XMLElement* xmlElement) -{ - v0 = xmlElement->IntAttribute("v0"); - v1 = xmlElement->IntAttribute("v1"); - v2 = xmlElement->IntAttribute("v2"); - flag = xmlElement->IntAttribute("flag"); -} - -std::string HLMeshCmdTriangle1::OutputCode(HLModelIntermediette* parent) -{ - return StringHelper::Sprintf("gsSP1Triangle(%i, %i, %i, %i),", v0, v1, v2, flag); -} - -void HLMeshCmdTriangle1::OutputAssimp(HLModelIntermediette* parent, aiScene* scene, aiMesh* mesh) -{ - aiFace* face = new aiFace(); - face->mNumIndices = 3; - face->mIndices = new uint32_t[3]; - face->mIndices[0] = parent->startIndex + v0; - face->mIndices[1] = parent->startIndex + v1; - face->mIndices[2] = parent->startIndex + v2; - - mesh->mFaces[mesh->mNumFaces++] = face[0]; -} - -void HLMeshCmdTriangle1::OutputXML(tinyxml2::XMLElement* parent) -{ - XMLElement* elem = parent->GetDocument()->NewElement("Triangle1"); - - elem->SetAttribute("V0", v0); - elem->SetAttribute("V1", v1); - elem->SetAttribute("V2", v2); - elem->SetAttribute("Flag", flag); - - parent->InsertEndChild(elem); -} - -HLMeshCmdTriangle2::HLMeshCmdTriangle2() -{ - v0 = 0; - v1 = 0; - v2 = 0; - flag0 = 0; - v10 = 0; - v11 = 0; - v12 = 0; - flag1 = 0; -} - -HLMeshCmdTriangle2::HLMeshCmdTriangle2(int32_t nV0, int32_t nV1, int32_t nV2, int32_t nFlag0, - int32_t nV10, int32_t nV11, int32_t nV12, int32_t nFlag1) -{ - v0 = nV0; - v1 = nV1; - v2 = nV2; - flag0 = nFlag0; - v10 = nV10; - v11 = nV11; - v12 = nV12; - flag1 = nFlag1; -} - -void HLMeshCmdTriangle2::InitFromXML(tinyxml2::XMLElement* xmlElement) -{ - v0 = xmlElement->IntAttribute("V0"); - v1 = xmlElement->IntAttribute("V1"); - v2 = xmlElement->IntAttribute("V2"); - flag0 = xmlElement->IntAttribute("Flag0"); - v10 = xmlElement->IntAttribute("V10"); - v11 = xmlElement->IntAttribute("V11"); - v12 = xmlElement->IntAttribute("V12"); - flag1 = xmlElement->IntAttribute("Flag1"); -} - -std::string HLMeshCmdTriangle2::OutputCode(HLModelIntermediette* parent) -{ - return StringHelper::Sprintf("gsSP2Triangles(%i, %i, %i, %i, %i, %i, %i, %i),", v0, v1, v2, - flag0, v10, v11, v12, flag1); -} - -std::string HLMeshCmdTriangle2::OutputOBJ(HLModelIntermediette* parent) -{ - std::string output = ""; - - int32_t startIndex = parent->startIndex; - - output += StringHelper::Sprintf("f %i %i %i\n", startIndex + v0 + 1, startIndex + v1 + 1, - startIndex + v2 + 1); - output += StringHelper::Sprintf("f %i %i %i\n", startIndex + v10 + 1, startIndex + v11 + 1, - startIndex + v12 + 1); - - return output; -} - -void HLMeshCmdTriangle2::OutputAssimp(HLModelIntermediette* parent, aiScene* scene, aiMesh* mesh) -{ - { - aiFace* face = new aiFace(); - face->mNumIndices = 3; - face->mIndices = new uint32_t[3]; - face->mIndices[0] = parent->startIndex + v0; - face->mIndices[1] = parent->startIndex + v1; - face->mIndices[2] = parent->startIndex + v2; - - mesh->mFaces[mesh->mNumFaces++] = face[0]; - } - - { - aiFace* face = new aiFace(); - face->mNumIndices = 3; - face->mIndices = new uint32_t[3]; - face->mIndices[0] = parent->startIndex + v10; - face->mIndices[1] = parent->startIndex + v11; - face->mIndices[2] = parent->startIndex + v12; - - mesh->mFaces[mesh->mNumFaces++] = face[0]; - } -} - -void HLMeshCmdTriangle2::OutputXML(tinyxml2::XMLElement* parent) -{ - XMLElement* elem = parent->GetDocument()->NewElement("Triangle2"); - - elem->SetAttribute("V0", v0); - elem->SetAttribute("V1", v1); - elem->SetAttribute("V2", v2); - elem->SetAttribute("Flag0", flag0); - elem->SetAttribute("V10", v10); - elem->SetAttribute("V11", v11); - elem->SetAttribute("V12", v12); - elem->SetAttribute("Flag1", flag1); - - parent->InsertEndChild(elem); -} - -HLMeshCmdLoadVertices::HLMeshCmdLoadVertices() : HLMeshCommand() -{ - numVerts = 0; - startIndex = 0; -} - -HLMeshCmdLoadVertices::HLMeshCmdLoadVertices(uint8_t nNumVerts, uint8_t nStartIndex) -{ - numVerts = nNumVerts; - startIndex = nStartIndex; -} - -void HLMeshCmdLoadVertices::OutputXML(tinyxml2::XMLElement* parent) -{ - XMLElement* elem = parent->GetDocument()->NewElement("LoadVertices"); - - elem->SetAttribute("StartIndex", startIndex); - elem->SetAttribute("NumVerts", numVerts); - - parent->InsertEndChild(elem); -} - -void HLMeshCmdLoadVertices::InitFromXML(tinyxml2::XMLElement* xmlElement) -{ - numVerts = xmlElement->IntAttribute("NumVerts", 0); - startIndex = xmlElement->IntAttribute("StartIndex", 0); -} - -std::string HLMeshCmdLoadVertices::OutputOBJ(HLModelIntermediette* parent) -{ - parent->startIndex = startIndex; - return ""; -} - -void HLMeshCmdLoadVertices::OutputAssimp(HLModelIntermediette* parent, aiScene* scene, aiMesh* mesh) -{ - parent->startIndex = startIndex; -} - -std::string HLMeshCmdLoadVertices::OutputCode(HLModelIntermediette* parent) -{ - HLVerticesIntermediette* verts = parent->FindByType(); - return StringHelper::Sprintf("gsSPVertex(&%s[%i], %i, %i),", verts->name.c_str(), startIndex, - numVerts, 0); -} - -HLMaterialIntermediette::HLMaterialIntermediette() -{ - textureName = ""; - clrR = 0; - clrG = 0; - clrB = 0; - clrA = 0; - clrM = 0; - clrL = 0; - cmtH = HLMaterialCmt::Wrap; - cmtV = HLMaterialCmt::Wrap; -} - -void HLMaterialIntermediette::InitFromXML(tinyxml2::XMLElement* xmlElement) -{ - name = xmlElement->Attribute("Name"); - textureName = xmlElement->Attribute("TextureName"); - clrR = xmlElement->IntAttribute("ClrR"); - clrG = xmlElement->IntAttribute("ClrG"); - clrB = xmlElement->IntAttribute("ClrB"); - clrA = xmlElement->IntAttribute("ClrA"); - clrM = xmlElement->IntAttribute("ClrM"); - clrL = xmlElement->IntAttribute("ClrL"); -} - -std::string HLMaterialIntermediette::OutputCode() -{ - return ""; -} - -void HLMaterialIntermediette::OutputXML(tinyxml2::XMLDocument* doc, tinyxml2::XMLElement* parent) -{ - XMLElement* elem = parent->GetDocument()->NewElement("Material"); - - elem->SetAttribute("Name", name.c_str()); - elem->SetAttribute("TextureName", textureName.c_str()); - elem->SetAttribute("ClrR", clrR); - elem->SetAttribute("ClrG", clrG); - elem->SetAttribute("ClrB", clrB); - elem->SetAttribute("ClrA", clrA); - elem->SetAttribute("ClrL", clrL); - elem->SetAttribute("ClrM", clrM); - elem->SetAttribute("CmtH", (int32_t)cmtH); - elem->SetAttribute("CmtV", (int32_t)cmtV); - - parent->InsertEndChild(elem); -} - -HLDisplayListIntermediette::HLDisplayListIntermediette() -{ - commands = std::vector(); -} - -std::string HLDisplayListIntermediette::OutputCode() -{ - return std::string(); -} - -void HLDisplayListIntermediette::InitFromXML(tinyxml2::XMLElement* xmlElement) -{ - for (XMLElement* child = xmlElement->FirstChildElement(); child != NULL; - child = child->NextSiblingElement()) - { - std::string name = child->Name(); - - HLDisplayListCommand* cmd = nullptr; - - if (name == "DrawMesh") - cmd = new HLDisplayListCmdDrawMesh(); - else if (name == "PipeSync") - cmd = new HLDisplayListCmdPipeSync(); - - if (cmd != nullptr) - { - cmd->InitFromXML(child); - commands.push_back(cmd); - } - } -} - -void HLDisplayListCommand::InitFromXML(tinyxml2::XMLElement* xmlElement) -{ -} - -std::string HLDisplayListCommand::OutputCode() -{ - return ""; -} - -void HLDisplayListCmdDrawMesh::InitFromXML(tinyxml2::XMLElement* xmlElement) -{ - meshName = xmlElement->Attribute("Mesh"); - materialName = xmlElement->Attribute("Material"); -} - -std::string HLDisplayListCmdDrawMesh::OutputCode() -{ - return ""; -} - -HLTextureIntermediette::HLTextureIntermediette() -{ - tex = nullptr; -} - -void HLTextureIntermediette::InitFromXML(tinyxml2::XMLElement* xmlElement) -{ - name = xmlElement->Attribute("Name"); - - fileName = xmlElement->Attribute("TextureName"); - // std::string format = xmlElement->Attribute("Format"); - std::string format = "rgba16"; // TEST - - // tex = HLTexture::FromPNG(fileName, - // (HLTextureType)ZTexture::GetTextureTypeFromString(format)); - tex = new ZTexture(nullptr); - tex->ZTexture::FromPNG(Path::GetDirectoryName(Globals::Instance->inputPath.string()) + "/" + - fileName, - ZTexture::GetTextureTypeFromString(format)); -} - -std::string HLTextureIntermediette::OutputCode() -{ - return StringHelper::Sprintf("#include <../%s/%s.inc.c>", Globals::Instance->outputPath.c_str(), - name.c_str()); -} - -void HLTextureIntermediette::OutputXML(tinyxml2::XMLDocument* doc, tinyxml2::XMLElement* root) -{ - XMLElement* element = doc->NewElement("Texture"); - - element->SetAttribute("Name", name.c_str()); - element->SetAttribute("TextureName", - (name + "." + tex->GetExternalExtension() + ".png").c_str()); - tex->Save(Globals::Instance->outputPath.string()); - - root->InsertEndChild(element); -} - -void HLDisplayListCmdPipeSync::InitFromXML(tinyxml2::XMLElement* xmlElement) -{ -} - -std::string HLDisplayListCmdPipeSync::OutputCode() -{ - return "gsDPPipeSync(),"; -} - -HLMeshCmdCull::HLMeshCmdCull() : HLMeshCommand() -{ - indexStart = 0; - indexEnd = 0; -} - -void HLMeshCmdCull::InitFromXML(tinyxml2::XMLElement* xmlElement) -{ - indexStart = xmlElement->IntAttribute("IndexStart", 0); - indexEnd = xmlElement->IntAttribute("IndexEnd", 0); -} - -std::string HLMeshCmdCull::OutputCode(HLModelIntermediette* parent) -{ - return StringHelper::Sprintf("gsSPCullDisplayList(%i, %i),", indexStart, indexEnd); -} - -HLMeshIntermediette::HLMeshIntermediette() : HLIntermediette() -{ - commands = std::vector(); -} - -void HLMeshIntermediette::InitFromXML(tinyxml2::XMLElement* xmlElement) -{ - name = xmlElement->Attribute("Name"); - - for (XMLElement* child = xmlElement->FirstChildElement(); child != NULL; - child = child->NextSiblingElement()) - { - std::string name = child->Name(); - - HLMeshCommand* cmd = nullptr; - - if (name == "Triangle1") - cmd = new HLMeshCmdTriangle1(); - else if (name == "Triangle2") - cmd = new HLMeshCmdTriangle2(); - else if (name == "LoadVertices") - cmd = new HLMeshCmdLoadVertices(); - else if (name == "GeoSettings") - cmd = new HLMeshCmdGeoSettings(); - else if (name == "Cull") - cmd = new HLMeshCmdCull(); - - if (cmd != nullptr) - { - cmd->InitFromXML(child); - commands.push_back(cmd); - } - } -} - -std::string HLMeshIntermediette::OutputCode(std::string materialName) -{ - std::string output = ""; - - HLMaterialIntermediette* mat = parent->FindByName(materialName); - HLTextureIntermediette* tex = parent->FindByName(mat->textureName); - - output += StringHelper::Sprintf(" gsDPPipeSync(),\n"); - output += StringHelper::Sprintf(" gsDPSetPrimColor(%i, %i, %i, %i, %i, %i),\n", mat->clrL, - mat->clrM, mat->clrR, mat->clrG, mat->clrB, mat->clrA); - output += StringHelper::Sprintf(" gsDPPipeSync(),\n"); - output += StringHelper::Sprintf(" gsSPTexture(65535, 65535, 0, 0, G_ON),\n"); - - output += StringHelper::Sprintf( - " gsDPLoadMultiBlock(%s, 0, 0, %s, %s, %i, %i, 0, 0, 0, 5, 5, 0, 0),\n", - mat->textureName.c_str(), tex->tex->GetIMFmtFromType().c_str(), - tex->tex->GetIMSizFromType().c_str(), tex->tex->GetWidth(), tex->tex->GetHeight()); - - for (HLMeshCommand* cmd : commands) - output += " " + cmd->OutputCode(parent) + "\n"; - - return output; -} - -std::string HLMeshIntermediette::OutputOBJ() -{ - std::string output = ""; - - output += StringHelper::Sprintf("o %s\n", name.c_str()); - - for (HLMeshCommand* cmd : commands) - output += cmd->OutputOBJ(parent); - - return output; -} - -void HLMeshIntermediette::OutputAssimp(aiScene* scene, std::vector* verts) -{ - aiMesh* mesh = new aiMesh(); - mesh->mVertices = - new aiVector3D[8192]; // TODO: Replace these hardcoded counts with the actual count - mesh->mNormals = new aiVector3D[8192]; - mesh->mFaces = new aiFace[8192]; - mesh->mPrimitiveTypes = 8; - mesh->mName = name; - - for (HLMeshCommand* cmd : commands) - { - cmd->OutputAssimp(parent, scene, mesh); - } - - parent->meshTranslations.push_back(parent->lastTrans); - // parent->objects.push_back(new HLModelObj(parent->lastTransX, )) - - scene->mMeshes[scene->mNumMeshes++] = mesh; -} - -void HLMeshIntermediette::OutputXML(tinyxml2::XMLDocument* doc, tinyxml2::XMLElement* root) -{ - XMLElement* element = doc->NewElement("Mesh"); - - element->SetAttribute("Name", name.c_str()); - - for (HLMeshCommand* cmd : commands) - { - cmd->OutputXML(element); - } - - root->InsertEndChild(element); -} - -HLLimbIntermediette::HLLimbIntermediette() -{ - commands = std::vector(); -} - -void HLLimbIntermediette::InitFromXML(tinyxml2::XMLElement* xmlElement) -{ - name = xmlElement->Attribute("Name"); - - for (XMLElement* child = xmlElement->FirstChildElement(); child != NULL; - child = child->NextSiblingElement()) - { - std::string name = child->Name(); - - HLLimbCommand* cmd = nullptr; - - if (name == "DrawMesh") - cmd = new HLLimbCommand(); - - if (cmd != nullptr) - { - cmd->InitFromXML(child); - commands.push_back(cmd); - } - } -} - -std::string HLLimbIntermediette::OutputCode() -{ - std::string output = ""; - - output += StringHelper::Sprintf("Gfx %s[] = \n{\n", name.c_str()); - - for (HLLimbCommand* cmd : commands) - output += cmd->OutputCode(parent); - - output += StringHelper::Sprintf(" gsSPEndDisplayList(),\n"); - output += StringHelper::Sprintf("};\n"); - - return output; -} - -void HLLimbIntermediette::OutputXML(tinyxml2::XMLDocument* doc, tinyxml2::XMLElement* root) -{ - XMLElement* element = doc->NewElement("Limb"); - - element->SetAttribute("Name", name.c_str()); - - for (HLLimbCommand* cmd : commands) - cmd->OutputXML(element); - - root->InsertEndChild(element); -} - -HLLimbCommand::HLLimbCommand() -{ - meshName = ""; - materialName = ""; -} - -HLLimbCommand::HLLimbCommand(std::string nMeshName, std::string nMaterialName) -{ - meshName = nMeshName; - materialName = nMaterialName; -} - -void HLLimbCommand::InitFromXML(tinyxml2::XMLElement* xmlElement) -{ - meshName = xmlElement->Attribute("Mesh"); - materialName = xmlElement->Attribute("Material"); -} - -void HLLimbCommand::OutputXML(tinyxml2::XMLElement* parent) -{ - XMLElement* elem = parent->GetDocument()->NewElement("DrawMesh"); - - elem->SetAttribute("Mesh", meshName.c_str()); - elem->SetAttribute("Material", materialName.c_str()); - - parent->InsertEndChild(elem); -} - -std::string HLLimbCommand::OutputCode(HLModelIntermediette* parent) -{ - std::string output = ""; - - // Time to generate the display list... - HLMeshIntermediette* mesh = parent->FindByName(meshName); - - output += mesh->OutputCode(materialName); - - return output; -} - -HLTerminator::HLTerminator() -{ -} - -HLTerminator::~HLTerminator() -{ -} - -void HLTerminator::OutputAssimp(aiScene* scene, std::vector* verts) -{ - for (uint32_t i = parent->meshStartIndex; i < scene->mNumMeshes; i++) - { - scene->mMeshes[i]->mNumVertices = verts->size(); - - for (uint32_t j = 0; j < verts->size(); j++) - scene->mMeshes[i]->mVertices[j] = verts[0][j]; - - parent->meshStartIndex++; - } - - verts->clear(); -} - -HLSetTranslation::HLSetTranslation() -{ - transX = 0; - transY = 0; - transZ = 0; -} - -HLSetTranslation::HLSetTranslation(float nTransX, float nTransY, float nTransZ) -{ - transX = nTransX; - transY = nTransY; - transZ = nTransZ; -} - -void HLSetTranslation::OutputAssimp(aiScene* scene, std::vector* verts) -{ - parent->lastTrans = Vec3s(transX, transY, transZ); -} - -HLModelObj::HLModelObj(Vec3s nPos, Vec3s nRot, std::vector nVerts, - std::vector nIndices) -{ - pos = nPos; - rot = nRot; - vertices = nVerts; - indices = nIndices; -} diff --git a/tools/ZAPD/ZAPD/HighLevel/HLModelIntermediette.h b/tools/ZAPD/ZAPD/HighLevel/HLModelIntermediette.h deleted file mode 100644 index e591e2c8f0..0000000000 --- a/tools/ZAPD/ZAPD/HighLevel/HLModelIntermediette.h +++ /dev/null @@ -1,312 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include "../ZDisplayList.h" -#include "../ZSkeleton.h" -#include "HLFileIntermediette.h" -#include "tinyxml2.h" - -/* - * An intermediette format for models. Goes from FBX<-->Intermediette<-->Display List C Code. - */ - -class HLModelIntermediette; - -class HLIntermediette -{ -public: - std::string name; - HLModelIntermediette* parent; - - HLIntermediette(); - ~HLIntermediette(); - - virtual std::string OutputCode(); - virtual std::string OutputOBJ(); - virtual void OutputAssimp(aiScene* scene, std::vector* verts); - virtual void OutputXML(tinyxml2::XMLDocument* doc, tinyxml2::XMLElement* root); - virtual void InitFromXML(tinyxml2::XMLElement* xmlElement); -}; - -class HLModelObj -{ -public: - Vec3s pos; - Vec3s rot; - std::vector vertices; - std::vector indices; - - HLModelObj() = default; - HLModelObj(Vec3s nPos, Vec3s nRot, std::vector nVerts, - std::vector nIndices); -}; - -class HLModelIntermediette : public HLFileIntermediette -{ -public: - std::vector blocks; - std::vector meshTranslations; - std::vector objects; - Vec3s lastTrans; - - bool hasSkeleton; - - bool startsWithPipeSync; - bool startsWithClearGeometryMode; - bool lerpBeforeTextureBlock; - - uint32_t startIndex; - uint32_t meshStartIndex; - - HLModelIntermediette(); - ~HLModelIntermediette(); - - static HLModelIntermediette* FromXML(tinyxml2::XMLElement* root); - static void FromZDisplayList(HLModelIntermediette* model, ZDisplayList* zDisplayList); - static void FromZSkeleton(HLModelIntermediette* model, ZSkeleton* zSkeleton); - static void ProcessZSkeletonLimb(HLModelIntermediette* model, ZSkeleton* zSkeleton, - ZLimb* limb); - std::string ToOBJFile(); - std::string ToAssimpFile(); - - std::string OutputCode(); - std::string OutputXML(); - - template - T* FindByName(std::string name); - - template - T* FindByType(); -}; - -class HLTextureIntermediette : public HLIntermediette -{ -public: - ZTexture* tex; - std::string fileName; - - HLTextureIntermediette(); - - virtual void InitFromXML(tinyxml2::XMLElement* xmlElement); - virtual std::string OutputCode(); - virtual void OutputXML(tinyxml2::XMLDocument* doc, tinyxml2::XMLElement* root); -}; - -class HLSetTranslation : public HLIntermediette -{ -public: - float transX, transY, transZ; - - HLSetTranslation(); - HLSetTranslation(float nTransX, float nTransY, float nTransZ); - - virtual void OutputAssimp(aiScene* scene, std::vector* verts); -}; - -class HLTerminator : public HLIntermediette -{ -public: - HLTerminator(); - ~HLTerminator(); - - virtual void OutputAssimp(aiScene* scene, std::vector* verts); -}; - -enum class HLMaterialCmt -{ - Wrap, - Mirror, - Clamp -}; - -class HLMaterialIntermediette : public HLIntermediette -{ -public: - std::string textureName; - // int32_t repeatH, repeatV; - uint8_t clrR, clrG, clrB, clrA, clrM, clrL; - // bool clampH, clampV; - // bool mirrorH, mirrorV; - HLMaterialCmt cmtH, cmtV; - - // TODO: Remember to add lerp params here... - - HLMaterialIntermediette(); - - virtual std::string OutputCode(); - virtual void OutputXML(tinyxml2::XMLDocument* doc, tinyxml2::XMLElement* parent); - virtual void InitFromXML(tinyxml2::XMLElement* xmlElement); -}; - -class HLMeshCommand -{ -public: - virtual void InitFromXML(tinyxml2::XMLElement* xmlElement); - virtual std::string OutputCode(HLModelIntermediette* parent); - virtual std::string OutputOBJ(HLModelIntermediette* parent); - virtual void OutputAssimp(HLModelIntermediette* parent, aiScene* scene, aiMesh* mesh); - - virtual void OutputXML(tinyxml2::XMLElement* parent); -}; - -class HLVerticesIntermediette : public HLIntermediette -{ -public: - std::vector vertices; - - HLVerticesIntermediette(); - - virtual void InitFromXML(tinyxml2::XMLElement* verticesElement); - void InitFromVertices(std::vector dispListVertices); - virtual std::string OutputCode(HLModelIntermediette* parent); - virtual std::string OutputOBJ(); - virtual void OutputAssimp(aiScene* scene, std::vector* verts); - virtual void OutputXML(tinyxml2::XMLDocument* doc, tinyxml2::XMLElement* root); -}; - -class HLMeshCmdTriangle1 : public HLMeshCommand -{ -public: - int32_t v0, v1, v2, flag; - - HLMeshCmdTriangle1(); - HLMeshCmdTriangle1(int32_t nV0, int32_t nV1, int32_t nV2, int32_t nFlag); - - virtual void InitFromXML(tinyxml2::XMLElement* xmlElement); - virtual std::string OutputCode(HLModelIntermediette* parent); - virtual void OutputAssimp(HLModelIntermediette* parent, aiScene* scene, aiMesh* mesh); - virtual void OutputXML(tinyxml2::XMLElement* parent); -}; - -class HLMeshCmdTriangle2 : public HLMeshCommand -{ -public: - int32_t v0, v1, v2, flag0, v10, v11, v12, flag1; - - HLMeshCmdTriangle2(); - HLMeshCmdTriangle2(int32_t nV0, int32_t nV1, int32_t nV2, int32_t nFlag0, int32_t nV10, - int32_t nV11, int32_t nV12, int32_t nFlag1); - - virtual void InitFromXML(tinyxml2::XMLElement* xmlElement); - virtual std::string OutputCode(HLModelIntermediette* parent); - virtual std::string OutputOBJ(HLModelIntermediette* parent); - virtual void OutputAssimp(HLModelIntermediette* parent, aiScene* scene, aiMesh* mesh); - virtual void OutputXML(tinyxml2::XMLElement* parent); -}; - -class HLMeshCmdLoadVertices : public HLMeshCommand -{ -public: - uint8_t numVerts; - uint8_t startIndex; - - HLMeshCmdLoadVertices(); - HLMeshCmdLoadVertices(uint8_t nNumVerts, uint8_t nStartIndex); - - virtual void OutputXML(tinyxml2::XMLElement* parent); - virtual void InitFromXML(tinyxml2::XMLElement* xmlElement); - virtual std::string OutputOBJ(HLModelIntermediette* parent); - virtual void OutputAssimp(HLModelIntermediette* parent, aiScene* scene, aiMesh* mesh); - virtual std::string OutputCode(HLModelIntermediette* parent); -}; - -class HLMeshCmdCull : public HLMeshCommand -{ -public: - uint8_t indexStart; - uint8_t indexEnd; - - HLMeshCmdCull(); - - virtual void InitFromXML(tinyxml2::XMLElement* xmlElement); - virtual std::string OutputCode(HLModelIntermediette* parent); -}; - -class HLMeshCmdGeoSettings : public HLMeshCommand -{ -public: - std::string on, off; - - HLMeshCmdGeoSettings(); - - virtual void InitFromXML(tinyxml2::XMLElement* xmlElement); - virtual std::string OutputCode(HLModelIntermediette* parent); -}; - -class HLMeshIntermediette : public HLIntermediette -{ -public: - std::vector commands; - - HLMeshIntermediette(); - - void InitFromXML(tinyxml2::XMLElement* xmlElement); - std::string OutputCode(std::string materialName); - virtual std::string OutputOBJ(); - virtual void OutputAssimp(aiScene* scene, std::vector* verts); - virtual void OutputXML(tinyxml2::XMLDocument* doc, tinyxml2::XMLElement* root); -}; - -class HLDisplayListCommand -{ -public: - virtual void InitFromXML(tinyxml2::XMLElement* xmlElement); - virtual std::string OutputCode(); -}; - -class HLDisplayListCmdDrawMesh : public HLDisplayListCommand -{ -public: - std::string meshName, materialName; - - virtual void InitFromXML(tinyxml2::XMLElement* xmlElement); - virtual std::string OutputCode(); -}; - -class HLDisplayListCmdPipeSync : public HLDisplayListCommand -{ -public: - virtual void InitFromXML(tinyxml2::XMLElement* xmlElement); - virtual std::string OutputCode(); -}; - -class HLDisplayListIntermediette : public HLIntermediette -{ -public: - std::vector commands; - uint32_t address; - - HLDisplayListIntermediette(); - - virtual std::string OutputCode(); - virtual void InitFromXML(tinyxml2::XMLElement* xmlElement); -}; - -class HLLimbCommand -{ -public: - std::string meshName, materialName; - - HLLimbCommand(); - HLLimbCommand(std::string nMeshName, std::string nMaterialName); - - virtual void InitFromXML(tinyxml2::XMLElement* xmlElement); - virtual void OutputXML(tinyxml2::XMLElement* parent); - virtual std::string OutputCode(HLModelIntermediette* parent); -}; - -class HLLimbIntermediette : public HLIntermediette -{ -public: - std::vector commands; - - HLLimbIntermediette(); - - void InitFromXML(tinyxml2::XMLElement* xmlElement); - std::string OutputCode(); - virtual void OutputXML(tinyxml2::XMLDocument* doc, tinyxml2::XMLElement* root); -}; \ No newline at end of file diff --git a/tools/ZAPD/ZAPD/HighLevel/HLTexture.cpp b/tools/ZAPD/ZAPD/HighLevel/HLTexture.cpp deleted file mode 100644 index b7e3a93e01..0000000000 --- a/tools/ZAPD/ZAPD/HighLevel/HLTexture.cpp +++ /dev/null @@ -1,13 +0,0 @@ -#include "HLTexture.h" -#include "../StringHelper.h" - -HLTexture* HLTexture::FromPNG(std::string pngFilePath, HLTextureType texType) -{ - // int32_t comp; - HLTexture* tex = new HLTexture(); - tex->type = texType; - // tex->bmpRgba = (uint8_t*)stbi_load((pngFilePath).c_str(), (int32_t*)&tex->width, - // (int32_t*)&tex->height, &comp, STBI_rgb_alpha); - - return tex; -} diff --git a/tools/ZAPD/ZAPD/HighLevel/HLTexture.h b/tools/ZAPD/ZAPD/HighLevel/HLTexture.h deleted file mode 100644 index 53f1cadee6..0000000000 --- a/tools/ZAPD/ZAPD/HighLevel/HLTexture.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once - -#include -#include -#include - -// TODO: This was duplicated from ZTexture. It's probably going to be modified to differentiate from -// ZTexture but if not, we're going to need to have the two share an enum. -enum class HLTextureType -{ - RGBA32bpp, - RGBA16bpp, - Palette4bpp, - Palette8bpp, - Grayscale4bpp, - Grayscale8bpp, - GrayscaleAlpha4bpp, - GrayscaleAlpha8bpp, - GrayscaleAlpha16bpp, - Error -}; - -class HLTexture -{ -public: - static HLTexture* FromPNG(std::string pngFilePath, HLTextureType texType); - - HLTextureType type; - uint32_t width, height; - uint8_t* bmpRgba; -}; \ No newline at end of file diff --git a/tools/ZAPD/ZAPD/ImageBackend.cpp b/tools/ZAPD/ZAPD/ImageBackend.cpp index 0b4bce360a..137e326c33 100644 --- a/tools/ZAPD/ZAPD/ImageBackend.cpp +++ b/tools/ZAPD/ZAPD/ImageBackend.cpp @@ -5,7 +5,7 @@ #include #include -#include "StringHelper.h" +#include "Utils/StringHelper.h" /* ImageBackend */ @@ -216,7 +216,9 @@ void ImageBackend::WritePng(const char* filename) void ImageBackend::WritePng(const fs::path& filename) { - WritePng(filename.c_str()); + // Note: The .string() is necessary for MSVC, due to the implementation of std::filesystem + // differing from GCC. Do not remove! + WritePng(filename.string().c_str()); } void ImageBackend::SetTextureData(const std::vector>& texData, @@ -385,11 +387,22 @@ void ImageBackend::SetPalette(const ImageBackend& pal) { for (size_t x = 0; x < pal.width; x++) { + size_t index = y * pal.width + x; + if (index >= paletteSize) + { + /* + * Some TLUTs are bigger than 256 colors. + * For those cases, we will only take the first 256 + * to colorize this CI texture. + */ + return; + } + uint8_t r = pal.pixelMatrix[y][x * bytePerPixel + 0]; uint8_t g = pal.pixelMatrix[y][x * bytePerPixel + 1]; uint8_t b = pal.pixelMatrix[y][x * bytePerPixel + 2]; uint8_t a = pal.pixelMatrix[y][x * bytePerPixel + 3]; - SetPaletteIndex(y * pal.width + x, r, g, b, a); + SetPaletteIndex(index, r, g, b, a); } } } diff --git a/tools/ZAPD/ZAPD/ImageBackend.h b/tools/ZAPD/ZAPD/ImageBackend.h index 25ab83216f..9e05a2eed1 100644 --- a/tools/ZAPD/ZAPD/ImageBackend.h +++ b/tools/ZAPD/ZAPD/ImageBackend.h @@ -3,7 +3,7 @@ #include #include -#include "Directory.h" +#include "Utils/Directory.h" class RGBAPixel { diff --git a/tools/ZAPD/ZAPD/Main.cpp b/tools/ZAPD/ZAPD/Main.cpp index 839e1ba990..298ca02629 100644 --- a/tools/ZAPD/ZAPD/Main.cpp +++ b/tools/ZAPD/ZAPD/Main.cpp @@ -1,11 +1,8 @@ -#include "BuildInfo.h" -#include "Directory.h" -#include "File.h" +#include +#include +#include #include "Globals.h" -#include "HighLevel/HLAnimationIntermediette.h" -#include "HighLevel/HLModelIntermediette.h" #include "Overlays/ZOverlay.h" -#include "Path.h" #include "ZAnimation.h" #include "ZBackground.h" #include "ZBlob.h" @@ -23,17 +20,17 @@ #endif #include +#include #include "tinyxml2.h" -using namespace tinyxml2; +extern const char gBuildHash[]; -bool Parse(const fs::path& xmlFilePath, const fs::path& basePath, ZFileMode fileMode); +bool Parse(const fs::path& xmlFilePath, const fs::path& basePath, const fs::path& outPath, + ZFileMode fileMode); void BuildAssetTexture(const fs::path& pngFilePath, TextureType texType, const fs::path& outPath); void BuildAssetBackground(const fs::path& imageFilePath, const fs::path& outPath); void BuildAssetBlob(const fs::path& blobFilePath, const fs::path& outPath); -void BuildAssetModelIntermediette(const fs::path& outPath); -void BuildAssetAnimationIntermediette(const fs::path& animPath, const fs::path& outPath); #if !defined(_MSC_VER) && !defined(__CYGWIN__) #define ARRAY_COUNT(arr) (sizeof(arr) / sizeof(arr[0])) @@ -116,34 +113,7 @@ int main(int argc, char* argv[]) } } - Globals* g = new Globals(); - - // Parse File Mode - std::string buildMode = argv[1]; - ZFileMode fileMode = ZFileMode::Invalid; - - if (buildMode == "btex") - fileMode = ZFileMode::BuildTexture; - else if (buildMode == "bren") - fileMode = ZFileMode::BuildBackground; - else if (buildMode == "bovl") - fileMode = ZFileMode::BuildOverlay; - else if (buildMode == "bsf") - fileMode = ZFileMode::BuildSourceFile; - else if (buildMode == "bblb") - fileMode = ZFileMode::BuildBlob; - else if (buildMode == "bmdlintr") - fileMode = ZFileMode::BuildModelIntermediette; - else if (buildMode == "bamnintr") - fileMode = ZFileMode::BuildAnimationIntermediette; - else if (buildMode == "e") - fileMode = ZFileMode::Extract; - - if (fileMode == ZFileMode::Invalid) - { - printf("Error: Invalid file mode '%s'\n", buildMode.c_str()); - return 1; - } + Globals* g = new Globals; // Parse other "commands" for (int32_t i = 2; i < argc; i++) @@ -152,76 +122,63 @@ int main(int argc, char* argv[]) if (arg == "-o" || arg == "--outputpath") // Set output path { - Globals::Instance->outputPath = argv[i + 1]; + Globals::Instance->outputPath = argv[++i]; if (Globals::Instance->sourceOutputPath == "") Globals::Instance->sourceOutputPath = Globals::Instance->outputPath; - - i++; } else if (arg == "-i" || arg == "--inputpath") // Set input path { - Globals::Instance->inputPath = argv[i + 1]; - i++; + Globals::Instance->inputPath = argv[++i]; } else if (arg == "-b" || arg == "--baserompath") // Set baserom path { - Globals::Instance->baseRomPath = argv[i + 1]; - i++; + Globals::Instance->baseRomPath = argv[++i]; } else if (arg == "-osf") // Set source output path { - Globals::Instance->sourceOutputPath = argv[i + 1]; - i++; + Globals::Instance->sourceOutputPath = argv[++i]; } else if (arg == "-gsf") // Generate source file during extraction { - Globals::Instance->genSourceFile = std::string(argv[i + 1]) == "1"; - i++; + Globals::Instance->genSourceFile = std::string_view(argv[++i]) == "1"; } else if (arg == "-tm") // Test Mode (enables certain experimental features) { - Globals::Instance->testMode = std::string(argv[i + 1]) == "1"; - i++; + Globals::Instance->testMode = std::string_view(argv[++i]) == "1"; } else if (arg == "-crc" || arg == "--output-crc") // Outputs a CRC file for each extracted texture. { - Globals::Instance->outputCrc = true; + Globals::Instance->testMode = std::string_view(argv[++i]) == "1"; } else if (arg == "-ulzdl") // Use Legacy ZDisplay List { - Globals::Instance->useLegacyZDList = std::string(argv[i + 1]) == "1"; - i++; + Globals::Instance->useLegacyZDList = std::string_view(argv[++i]) == "1"; } else if (arg == "-profile") // Enable profiling { - Globals::Instance->profile = std::string(argv[i + 1]) == "1"; - i++; + Globals::Instance->profile = std::string_view(argv[++i]) == "1"; } else if (arg == "-uer") // Split resources into their individual components (enabled by default) // TODO: We may wish to make this a part of the config file... { - Globals::Instance->useExternalResources = std::string(argv[i + 1]) == "1"; - i++; + Globals::Instance->useExternalResources = std::string_view(argv[++i]) == "1"; } else if (arg == "-tt") // Set texture type { - Globals::Instance->texType = ZTexture::GetTextureTypeFromString(argv[i + 1]); - i++; + Globals::Instance->texType = ZTexture::GetTextureTypeFromString(argv[++i]); } else if (arg == "-cfg") // Set cfg path (for overlays) // TODO: Change the name of this to something else so it doesn't // get confused with XML config files. { - Globals::Instance->cfgPath = argv[i + 1]; - i++; + Globals::Instance->cfgPath = argv[++i]; } else if (arg == "-rconf") // Read Config File { - Globals::Instance->ReadConfigFile(argv[i + 1]); - i++; + Globals::Instance->cfg.ReadConfigFile(argv[++i]); } else if (arg == "-eh") // Enable Error Handler { @@ -253,18 +210,93 @@ int main(int argc, char* argv[]) { Globals::Instance->verboseUnaccounted = true; } + else if (arg == "-se" || arg == "--set-exporter") // Set Current Exporter + { + Globals::Instance->currentExporter = argv[++i]; + } + else if (arg == "--gcc-compat") // GCC compatibility + { + Globals::Instance->gccCompat = true; + } + else if (arg == "-s" || arg == "--static") + { + Globals::Instance->forceStatic = true; + } + } + + // Parse File Mode + ExporterSet* exporterSet = Globals::Instance->GetExporterSet(); + std::string buildMode = argv[1]; + ZFileMode fileMode = ZFileMode::Invalid; + + if (buildMode == "btex") + fileMode = ZFileMode::BuildTexture; + else if (buildMode == "bren") + fileMode = ZFileMode::BuildBackground; + else if (buildMode == "bovl") + fileMode = ZFileMode::BuildOverlay; + else if (buildMode == "bsf") + fileMode = ZFileMode::BuildSourceFile; + else if (buildMode == "bblb") + fileMode = ZFileMode::BuildBlob; + else if (buildMode == "e") + fileMode = ZFileMode::Extract; + else if (exporterSet != nullptr && exporterSet->parseFileModeFunc != nullptr) + exporterSet->parseFileModeFunc(buildMode, fileMode); + + if (fileMode == ZFileMode::Invalid) + { + printf("Error: Invalid file mode '%s'\n", buildMode.c_str()); + return 1; + } + + // We've parsed through our commands once. If an exporter exists, it's been set by now. + // Now we'll parse through them again but pass them on to our exporter if one is available. + + if (exporterSet != nullptr && exporterSet->parseArgsFunc != nullptr) + { + for (int32_t i = 2; i < argc; i++) + exporterSet->parseArgsFunc(argc, argv, i); } if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_INFO) printf("ZAPD: Zelda Asset Processor For Decomp: %s\n", gBuildHash); + // TODO: switch if (fileMode == ZFileMode::Extract || fileMode == ZFileMode::BuildSourceFile) { - bool parseSuccessful = - Parse(Globals::Instance->inputPath, Globals::Instance->baseRomPath, fileMode); + bool procFileModeSuccess = false; - if (!parseSuccessful) - return 1; + if (exporterSet != nullptr && exporterSet->processFileModeFunc != nullptr) + procFileModeSuccess = exporterSet->processFileModeFunc(fileMode); + + if (!procFileModeSuccess) + { + bool parseSuccessful; + + for (auto& extFile : Globals::Instance->cfg.externalFiles) + { + fs::path externalXmlFilePath = + Globals::Instance->cfg.externalXmlFolder / extFile.xmlPath; + + if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_INFO) + { + printf("Parsing external file from config: '%s'\n", + externalXmlFilePath.c_str()); + } + + parseSuccessful = Parse(externalXmlFilePath, Globals::Instance->baseRomPath, + extFile.outPath, ZFileMode::ExternalFile); + + if (!parseSuccessful) + return 1; + } + + parseSuccessful = Parse(Globals::Instance->inputPath, Globals::Instance->baseRomPath, + Globals::Instance->outputPath, fileMode); + if (!parseSuccessful) + return 1; + } } else if (fileMode == ZFileMode::BuildTexture) { @@ -279,33 +311,26 @@ int main(int argc, char* argv[]) { BuildAssetBlob(Globals::Instance->inputPath, Globals::Instance->outputPath); } - else if (fileMode == ZFileMode::BuildModelIntermediette) - { - BuildAssetModelIntermediette(Globals::Instance->outputPath); - } - else if (fileMode == ZFileMode::BuildAnimationIntermediette) - { - BuildAssetAnimationIntermediette(Globals::Instance->inputPath, - Globals::Instance->outputPath); - } else if (fileMode == ZFileMode::BuildOverlay) { ZOverlay* overlay = ZOverlay::FromBuild(Path::GetDirectoryName(Globals::Instance->inputPath), Path::GetDirectoryName(Globals::Instance->cfgPath)); - if (overlay) + if (overlay != nullptr) File::WriteAllText(Globals::Instance->outputPath.string(), overlay->GetSourceOutputCode("")); } + delete g; return 0; } -bool Parse(const fs::path& xmlFilePath, const fs::path& basePath, ZFileMode fileMode) +bool Parse(const fs::path& xmlFilePath, const fs::path& basePath, const fs::path& outPath, + ZFileMode fileMode) { - XMLDocument doc; - XMLError eResult = doc.LoadFile(xmlFilePath.string().c_str()); + tinyxml2::XMLDocument doc; + tinyxml2::XMLError eResult = doc.LoadFile(xmlFilePath.string().c_str()); if (eResult != tinyxml2::XML_SUCCESS) { @@ -313,7 +338,7 @@ bool Parse(const fs::path& xmlFilePath, const fs::path& basePath, ZFileMode file return false; } - XMLNode* root = doc.FirstChild(); + tinyxml2::XMLNode* root = doc.FirstChild(); if (root == nullptr) { @@ -321,37 +346,78 @@ bool Parse(const fs::path& xmlFilePath, const fs::path& basePath, ZFileMode file return false; } - for (XMLElement* child = root->FirstChildElement(); child != NULL; + for (tinyxml2::XMLElement* child = root->FirstChildElement(); child != NULL; child = child->NextSiblingElement()) { - if (std::string(child->Name()) == "File") + if (std::string_view(child->Name()) == "File") { - ZFile* file = new ZFile(fileMode, child, basePath, "", xmlFilePath, false); + ZFile* file = new ZFile(fileMode, child, basePath, outPath, "", xmlFilePath); Globals::Instance->files.push_back(file); + if (fileMode == ZFileMode::ExternalFile) + { + Globals::Instance->externalFiles.push_back(file); + file->isExternalFile = true; + } + } + else if (std::string(child->Name()) == "ExternalFile") + { + const char* xmlPathValue = child->Attribute("XmlPath"); + if (xmlPathValue == nullptr) + { + throw std::runtime_error(StringHelper::Sprintf( + "Parse: Fatal error in '%s'.\n" + "\t Missing 'XmlPath' attribute in `ExternalFile` element.\n", + xmlFilePath.c_str())); + } + const char* outPathValue = child->Attribute("OutPath"); + if (outPathValue == nullptr) + { + throw std::runtime_error(StringHelper::Sprintf( + "Parse: Fatal error in '%s'.\n" + "\t Missing 'OutPath' attribute in `ExternalFile` element.\n", + xmlFilePath.c_str())); + } + + fs::path externalXmlFilePath = + Globals::Instance->cfg.externalXmlFolder / fs::path(xmlPathValue); + fs::path externalOutFilePath = fs::path(outPathValue); + + if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_INFO) + { + printf("Parsing external file: '%s'\n", externalXmlFilePath.c_str()); + } + + // Recursion. What can go wrong? + Parse(externalXmlFilePath, basePath, externalOutFilePath, ZFileMode::ExternalFile); } else { - throw std::runtime_error( - StringHelper::Sprintf("Parse: Fatal error in '%s'.\n\t Found a resource outside of " - "a File element: '%s'\n", - xmlFilePath.c_str(), child->Name())); + throw std::runtime_error(StringHelper::Sprintf( + "Parse: Fatal error in '%s'.\n\t A resource was found outside of " + "a File element: '%s'\n", + xmlFilePath.c_str(), child->Name())); } } - for (ZFile* file : Globals::Instance->files) + if (fileMode != ZFileMode::ExternalFile) { - if (fileMode == ZFileMode::BuildSourceFile) - file->BuildSourceFile(); - else - file->ExtractResources(); + ExporterSet* exporterSet = Globals::Instance->GetExporterSet(); + + if (exporterSet != nullptr && exporterSet->beginXMLFunc != nullptr) + exporterSet->beginXMLFunc(); + + for (ZFile* file : Globals::Instance->files) + { + if (fileMode == ZFileMode::BuildSourceFile) + file->BuildSourceFile(); + else + file->ExtractResources(); + } + + if (exporterSet != nullptr && exporterSet->endXMLFunc != nullptr) + exporterSet->endXMLFunc(); } - // All done, free files - for (ZFile* file : Globals::Instance->files) - delete file; - - Globals::Instance->files.clear(); - return true; } @@ -360,7 +426,7 @@ void BuildAssetTexture(const fs::path& pngFilePath, TextureType texType, const f std::string name = outPath.stem().string(); ZTexture tex(nullptr); - tex.FromPNG(pngFilePath, texType); + tex.FromPNG(pngFilePath.string(), texType); std::string cfgPath = StringHelper::Split(pngFilePath.string(), ".")[0] + ".cfg"; if (File::Exists(cfgPath)) @@ -384,43 +450,9 @@ void BuildAssetBlob(const fs::path& blobFilePath, const fs::path& outPath) ZBlob* blob = ZBlob::FromFile(blobFilePath.string()); std::string name = outPath.stem().string(); // filename without extension - std::string src = blob->GetSourceOutputCode(name); + std::string src = blob->GetBodySourceCode(); File::WriteAllText(outPath.string(), src); delete blob; } - -void BuildAssetModelIntermediette(const fs::path& outPath) -{ - XMLDocument doc; - - HLModelIntermediette* mdl = HLModelIntermediette::FromXML(doc.RootElement()); - std::string output = mdl->OutputCode(); - - File::WriteAllText(outPath.string(), output); - - delete mdl; -} - -void BuildAssetAnimationIntermediette(const fs::path& animPath, const fs::path& outPath) -{ - std::vector split = StringHelper::Split(outPath.string(), "/"); - ZFile* file = new ZFile(split[split.size() - 2]); - HLAnimationIntermediette* anim = HLAnimationIntermediette::FromXML(animPath.string()); - ZAnimation* zAnim = anim->ToZAnimation(); - zAnim->SetName(Path::GetFileNameWithoutExtension(split[split.size() - 1])); - zAnim->parent = file; - - zAnim->GetSourceOutputCode(split[split.size() - 2]); - std::string output = ""; - - output += file->declarations[2]->text + "\n"; - output += file->declarations[1]->text + "\n"; - output += file->declarations[0]->text + "\n"; - - File::WriteAllText(outPath.string(), output); - - delete zAnim; - delete file; -} diff --git a/tools/ZAPD/ZAPD/OtherStructs/SkinLimbStructs.cpp b/tools/ZAPD/ZAPD/OtherStructs/SkinLimbStructs.cpp new file mode 100644 index 0000000000..9d16de4389 --- /dev/null +++ b/tools/ZAPD/ZAPD/OtherStructs/SkinLimbStructs.cpp @@ -0,0 +1,341 @@ +#include "SkinLimbStructs.h" + +#include "Globals.h" +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" +#include "ZDisplayList.h" +#include "ZFile.h" + +/* Struct_800A57C0 */ + +Struct_800A57C0::Struct_800A57C0(ZFile* nParent) : ZResource(nParent) +{ +} + +void Struct_800A57C0::ParseRawData() +{ + const auto& rawData = parent->GetRawData(); + + unk_0 = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x00); + unk_2 = BitConverter::ToInt16BE(rawData, rawDataIndex + 0x02); + unk_4 = BitConverter::ToInt16BE(rawData, rawDataIndex + 0x04); + unk_6 = BitConverter::ToInt8BE(rawData, rawDataIndex + 0x06); + unk_7 = BitConverter::ToInt8BE(rawData, rawDataIndex + 0x07); + unk_8 = BitConverter::ToInt8BE(rawData, rawDataIndex + 0x08); + unk_9 = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x09); +} + +std::string Struct_800A57C0::GetBodySourceCode() const +{ + return StringHelper::Sprintf("0x%02X, %i, %i, %i, %i, %i, 0x%02X", unk_0, unk_2, unk_4, unk_6, + unk_7, unk_8, unk_9); +} + +std::string Struct_800A57C0::GetSourceTypeName() const +{ + return "Struct_800A57C0"; +} + +ZResourceType Struct_800A57C0::GetResourceType() const +{ + // TODO + return ZResourceType::Error; +} + +size_t Struct_800A57C0::GetRawDataSize() const +{ + return 0x0A; +} + +/* Struct_800A598C_2 */ + +Struct_800A598C_2::Struct_800A598C_2(ZFile* nParent) : ZResource(nParent) +{ +} + +void Struct_800A598C_2::ParseRawData() +{ + const auto& rawData = parent->GetRawData(); + + unk_0 = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x00); + x = BitConverter::ToInt16BE(rawData, rawDataIndex + 0x02); + y = BitConverter::ToInt16BE(rawData, rawDataIndex + 0x04); + z = BitConverter::ToInt16BE(rawData, rawDataIndex + 0x06); + unk_8 = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x08); +} + +std::string Struct_800A598C_2::GetBodySourceCode() const +{ + return StringHelper::Sprintf("0x%02X, %i, %i, %i, 0x%02X", unk_0, x, y, z, unk_8); +} + +std::string Struct_800A598C_2::GetSourceTypeName() const +{ + return "Struct_800A598C_2"; +} + +ZResourceType Struct_800A598C_2::GetResourceType() const +{ + // TODO + return ZResourceType::Error; +} + +size_t Struct_800A598C_2::GetRawDataSize() const +{ + return 0x0A; +} + +/* Struct_800A598C */ + +Struct_800A598C::Struct_800A598C(ZFile* nParent) : ZResource(nParent) +{ +} + +void Struct_800A598C::ParseRawData() +{ + const auto& rawData = parent->GetRawData(); + + unk_0 = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x00); + unk_2 = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x02); + unk_4 = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x04); + unk_8 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x08); + unk_C = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x0C); + + if (unk_8 != 0 && GETSEGNUM(unk_8) == parent->segment) + { + uint32_t unk_8_Offset = Seg2Filespace(unk_8, parent->baseAddress); + for (size_t i = 0; i < unk_0; i++) + { + Struct_800A57C0 unk8_data(parent); + unk8_data.ExtractFromFile(unk_8_Offset); + unk_8_arr.push_back(unk8_data); + + unk_8_Offset += unk8_data.GetRawDataSize(); + } + } + + if (unk_C != 0 && GETSEGNUM(unk_8) == parent->segment) + { + uint32_t unk_C_Offset = Seg2Filespace(unk_C, parent->baseAddress); + for (size_t i = 0; i < unk_2; i++) + { + Struct_800A598C_2 unkC_data(parent); + unkC_data.ExtractFromFile(unk_C_Offset); + unk_C_arr.push_back(unkC_data); + + unk_C_Offset += unkC_data.GetRawDataSize(); + } + } +} + +void Struct_800A598C::DeclareReferences(const std::string& prefix) +{ + std::string varPrefix = prefix; + if (name != "") + varPrefix = name; + + if (unk_8 != 0 && GETSEGNUM(unk_8) == parent->segment) + { + const auto& res = unk_8_arr.at(0); + std::string unk_8_Str = res.GetDefaultName(varPrefix); + + size_t arrayItemCnt = unk_8_arr.size(); + std::string entryStr = ""; + + for (size_t i = 0; i < arrayItemCnt; i++) + { + auto& child = unk_8_arr[i]; + child.DeclareReferences(varPrefix); + entryStr += StringHelper::Sprintf("\t{ %s },", child.GetBodySourceCode().c_str()); + + if (i < arrayItemCnt - 1) + entryStr += "\n"; + } + + uint32_t unk_8_Offset = Seg2Filespace(unk_8, parent->baseAddress); + Declaration* decl = parent->GetDeclaration(unk_8_Offset); + if (decl == nullptr) + { + parent->AddDeclarationArray(unk_8_Offset, res.GetDeclarationAlignment(), + arrayItemCnt * res.GetRawDataSize(), + res.GetSourceTypeName(), unk_8_Str, arrayItemCnt, entryStr); + } + else + decl->text = entryStr; + } + + if (unk_C != 0 && GETSEGNUM(unk_C) == parent->segment) + { + const auto& res = unk_C_arr.at(0); + std::string unk_C_Str = res.GetDefaultName(varPrefix); + + size_t arrayItemCnt = unk_C_arr.size(); + std::string entryStr = ""; + + for (size_t i = 0; i < arrayItemCnt; i++) + { + auto& child = unk_C_arr[i]; + child.DeclareReferences(varPrefix); + entryStr += StringHelper::Sprintf("\t{ %s },", child.GetBodySourceCode().c_str()); + + if (i < arrayItemCnt - 1) + entryStr += "\n"; + } + + uint32_t unk_C_Offset = Seg2Filespace(unk_C, parent->baseAddress); + Declaration* decl = parent->GetDeclaration(unk_C_Offset); + if (decl == nullptr) + { + parent->AddDeclarationArray(unk_C_Offset, res.GetDeclarationAlignment(), + arrayItemCnt * res.GetRawDataSize(), + res.GetSourceTypeName(), unk_C_Str, arrayItemCnt, entryStr); + } + else + decl->text = entryStr; + } +} + +std::string Struct_800A598C::GetBodySourceCode() const +{ + std::string unk_8_Str; + std::string unk_C_Str; + Globals::Instance->GetSegmentedPtrName(unk_8, parent, "Struct_800A57C0", unk_8_Str); + Globals::Instance->GetSegmentedPtrName(unk_C, parent, "Struct_800A598C_2", unk_C_Str); + + std::string entryStr = StringHelper::Sprintf("\n\t\tARRAY_COUNTU(%s), ARRAY_COUNTU(%s),\n", + unk_8_Str.c_str(), unk_C_Str.c_str()); + entryStr += + StringHelper::Sprintf("\t\t%i, %s, %s\n\t", unk_4, unk_8_Str.c_str(), unk_C_Str.c_str()); + + return entryStr; +} + +std::string Struct_800A598C::GetSourceTypeName() const +{ + return "Struct_800A598C"; +} + +ZResourceType Struct_800A598C::GetResourceType() const +{ + // TODO + return ZResourceType::Error; +} + +size_t Struct_800A598C::GetRawDataSize() const +{ + return 0x10; +} + +/* Struct_800A5E28 */ + +Struct_800A5E28::Struct_800A5E28(ZFile* nParent) : ZResource(nParent) +{ +} + +void Struct_800A5E28::ParseRawData() +{ + const auto& rawData = parent->GetRawData(); + + unk_0 = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x00); + unk_2 = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x02); + unk_4 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x04); + unk_8 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x08); + + if (unk_4 != 0 && GETSEGNUM(unk_4) == parent->segment) + { + uint32_t unk_4_Offset = Seg2Filespace(unk_4, parent->baseAddress); + for (size_t i = 0; i < unk_2; i++) + { + Struct_800A598C unk_4_data(parent); + unk_4_data.ExtractFromFile(unk_4_Offset); + unk_4_arr.push_back(unk_4_data); + + unk_4_Offset += unk_4_data.GetRawDataSize(); + } + } +} + +void Struct_800A5E28::DeclareReferences(const std::string& prefix) +{ + std::string varPrefix = prefix; + if (name != "") + varPrefix = name; + + ZResource::DeclareReferences(varPrefix); + + if (unk_4 != 0 && GETSEGNUM(unk_4) == parent->segment) + { + const auto& res = unk_4_arr.at(0); + std::string unk_4_Str = res.GetDefaultName(varPrefix); + + size_t arrayItemCnt = unk_4_arr.size(); + std::string entryStr = ""; + + for (size_t i = 0; i < arrayItemCnt; i++) + { + auto& child = unk_4_arr[i]; + child.DeclareReferences(varPrefix); + entryStr += StringHelper::Sprintf("\t{ %s },", child.GetBodySourceCode().c_str()); + + if (i < arrayItemCnt - 1) + entryStr += "\n"; + } + + uint32_t unk_4_Offset = Seg2Filespace(unk_4, parent->baseAddress); + Declaration* decl = parent->GetDeclaration(unk_4_Offset); + if (decl == nullptr) + { + parent->AddDeclarationArray(unk_4_Offset, res.GetDeclarationAlignment(), + arrayItemCnt * res.GetRawDataSize(), + res.GetSourceTypeName(), unk_4_Str, arrayItemCnt, entryStr); + } + else + decl->text = entryStr; + } + + if (unk_8 != 0 && GETSEGNUM(unk_8) == parent->segment) + { + uint32_t unk_8_Offset = Seg2Filespace(unk_8, parent->baseAddress); + + int32_t dlistLength = ZDisplayList::GetDListLength( + parent->GetRawData(), unk_8_Offset, + Globals::Instance->game == ZGame::OOT_SW97 ? DListType::F3DEX : DListType::F3DZEX); + ZDisplayList* unk_8_dlist = new ZDisplayList(parent); + unk_8_dlist->ExtractFromBinary(unk_8_Offset, dlistLength); + + std::string dListStr = + StringHelper::Sprintf("%sSkinLimbDL_%06X", varPrefix.c_str(), unk_8_Offset); + unk_8_dlist->SetName(dListStr); + parent->AddResource(unk_8_dlist); + } +} + +std::string Struct_800A5E28::GetBodySourceCode() const +{ + std::string unk_4_Str; + std::string unk_8_Str; + Globals::Instance->GetSegmentedPtrName(unk_4, parent, "Struct_800A598C", unk_4_Str); + Globals::Instance->GetSegmentedPtrName(unk_8, parent, "Gfx", unk_8_Str); + + std::string entryStr = "\n"; + entryStr += StringHelper::Sprintf("\t%i, ARRAY_COUNTU(%s),\n", unk_0, unk_4_Str.c_str()); + entryStr += StringHelper::Sprintf("\t%s, %s\n", unk_4_Str.c_str(), unk_8_Str.c_str()); + + return entryStr; +} + +std::string Struct_800A5E28::GetSourceTypeName() const +{ + return "Struct_800A5E28"; +} + +ZResourceType Struct_800A5E28::GetResourceType() const +{ + // TODO + return ZResourceType::Error; +} + +size_t Struct_800A5E28::GetRawDataSize() const +{ + return 0x0C; +} diff --git a/tools/ZAPD/ZAPD/OtherStructs/SkinLimbStructs.h b/tools/ZAPD/ZAPD/OtherStructs/SkinLimbStructs.h new file mode 100644 index 0000000000..33edd07cae --- /dev/null +++ b/tools/ZAPD/ZAPD/OtherStructs/SkinLimbStructs.h @@ -0,0 +1,113 @@ +#pragma once + +#include +#include +#include + +#include "ZResource.h" + +// TODO: check if more types exists +enum class ZLimbSkinType +{ + SkinType_0, // Segment = 0 + SkinType_4 = 4, // Segment = segmented address // Struct_800A5E28 + SkinType_5 = 5, // Segment = 0 + SkinType_DList = 11, // Segment = DList address +}; + +class Struct_800A57C0 : public ZResource +{ +public: + Struct_800A57C0(ZFile* nParent); + + void ParseRawData() override; + + std::string GetBodySourceCode() const override; + + std::string GetSourceTypeName() const override; + ZResourceType GetResourceType() const override; + + size_t GetRawDataSize() const override; + +protected: + uint16_t unk_0; + int16_t unk_2; + int16_t unk_4; + int8_t unk_6; + int8_t unk_7; + int8_t unk_8; + uint8_t unk_9; +}; + +class Struct_800A598C_2 : public ZResource +{ +public: + Struct_800A598C_2(ZFile* nParent); + + void ParseRawData() override; + + std::string GetBodySourceCode() const override; + + std::string GetSourceTypeName() const override; + ZResourceType GetResourceType() const override; + + size_t GetRawDataSize() const override; + +protected: + uint8_t unk_0; + int16_t x; + int16_t y; + int16_t z; + uint8_t unk_8; +}; + +class Struct_800A598C : public ZResource +{ +public: + Struct_800A598C(ZFile* nParent); + + void ParseRawData() override; + void DeclareReferences(const std::string& prefix) override; + + std::string GetBodySourceCode() const override; + + std::string GetSourceTypeName() const override; + ZResourceType GetResourceType() const override; + + size_t GetRawDataSize() const override; + +protected: + uint16_t unk_0; // Length of unk_8 + uint16_t unk_2; // Length of unk_C + uint16_t unk_4; // 0 or 1 // Used as an index for unk_C + segptr_t unk_8; // Struct_800A57C0* + segptr_t unk_C; // Struct_800A598C_2* + + std::vector unk_8_arr; + std::vector unk_C_arr; +}; + +class Struct_800A5E28 : public ZResource +{ +public: + Struct_800A5E28(ZFile* nParent); + + void ParseRawData() override; + void DeclareReferences(const std::string& prefix) override; + + std::string GetBodySourceCode() const override; + + std::string GetSourceTypeName() const override; + ZResourceType GetResourceType() const override; + + size_t GetRawDataSize() const override; + +protected: + uint16_t unk_0; // Vtx count + uint16_t unk_2; // Length of unk_4 + segptr_t unk_4; // Struct_800A598C* + segptr_t unk_8; // Gfx* + + std::vector unk_4_arr; + // ZDisplayList* unk_8_dlist = nullptr; +}; diff --git a/tools/ZAPD/ZAPD/OutputFormatter.cpp b/tools/ZAPD/ZAPD/OutputFormatter.cpp index 65b45f3c3e..393ec1936a 100644 --- a/tools/ZAPD/ZAPD/OutputFormatter.cpp +++ b/tools/ZAPD/ZAPD/OutputFormatter.cpp @@ -101,10 +101,9 @@ int (*OutputFormatter::StaticWriter())(const char* buf, int count) return &WriteStatic; } -OutputFormatter::OutputFormatter(uint32_t tabSize, uint32_t defaultIndent, uint32_t lineLimit) - : tabSize{tabSize}, defaultIndent{defaultIndent}, lineLimit{lineLimit}, col{0}, nest{0}, - nestIndent{defaultIndent}, currentIndent{defaultIndent}, - wordNests(0), wordP{word}, spaceP{space} +OutputFormatter::OutputFormatter(uint32_t tabSize, uint32_t indentation, uint32_t lineLimit) + : tabSize{tabSize}, lineLimit{lineLimit}, col{0}, nest{0}, nestIndent{indentation}, + currentIndent{indentation}, wordNests(0), wordP{word}, spaceP{space} { } diff --git a/tools/ZAPD/ZAPD/OutputFormatter.h b/tools/ZAPD/ZAPD/OutputFormatter.h index b887b42588..28955b1cd1 100644 --- a/tools/ZAPD/ZAPD/OutputFormatter.h +++ b/tools/ZAPD/ZAPD/OutputFormatter.h @@ -8,7 +8,6 @@ class OutputFormatter { private: const uint32_t tabSize; - const uint32_t defaultIndent; const uint32_t lineLimit; uint32_t col; @@ -30,7 +29,7 @@ private: static int WriteStatic(const char* buf, int count); public: - OutputFormatter(uint32_t tabSize = 4, uint32_t defaultIndent = 4, uint32_t lineLimit = 120); + OutputFormatter(uint32_t tabSize = 4, uint32_t indentation = 4, uint32_t lineLimit = 120); int (*StaticWriter())(const char* buf, int count); // Must be `int` due to libgfxd @@ -38,4 +37,4 @@ public: int Write(const std::string& buf); std::string GetOutput(); -}; \ No newline at end of file +}; diff --git a/tools/ZAPD/ZAPD/Overlays/ZOverlay.cpp b/tools/ZAPD/ZAPD/Overlays/ZOverlay.cpp index a30d89ff5c..a842a7e7d9 100644 --- a/tools/ZAPD/ZAPD/Overlays/ZOverlay.cpp +++ b/tools/ZAPD/ZAPD/Overlays/ZOverlay.cpp @@ -1,18 +1,57 @@ #include "ZOverlay.h" -#include "../Directory.h" -#include "../File.h" -#include "../Path.h" -#include "../StringHelper.h" + +#include +#include + +#include +#include +#include +#include +#include "Globals.h" using namespace ELFIO; +const char* RelocationEntry::GetSectionName() const +{ + switch (sectionType) + { + case SectionType::Text: + return ".text"; + case SectionType::Data: + return ".data"; + case SectionType::RoData: + return ".rodata"; + case SectionType::Bss: + return ".bss"; + case SectionType::ERROR: + return ".ERROR"; + } + assert(!"Oh no :c"); +} + +const char* RelocationEntry::GetRelocTypeName() const +{ + switch (relocationType) + { + case RelocationType::R_MIPS_32: + return "R_MIPS_32"; + case RelocationType::R_MIPS_26: + return "R_MIPS_26"; + case RelocationType::R_MIPS_HI16: + return "R_MIPS_HI16"; + case RelocationType::R_MIPS_LO16: + return "R_MIPS_LO16"; + } + assert(!"Oh no :c"); +} + ZOverlay::ZOverlay() { name = ""; entries = std::vector(); } -ZOverlay::ZOverlay(std::string nName) : ZOverlay() +ZOverlay::ZOverlay(const std::string& nName) : ZOverlay() { name = nName; } @@ -25,15 +64,22 @@ ZOverlay::~ZOverlay() entries.clear(); } -ZOverlay* ZOverlay::FromBuild(std::string buildPath, std::string cfgFolderPath) +static const std::unordered_set sRelSections = { + ".rel.text", + ".rel.data", + ".rel.rodata", +}; +static const std::unordered_set sSections = { + ".text", ".data", ".symtab", ".rodata", ".rodata.str1.4", ".rodata.cst4", ".rodata.cst8", +}; + +ZOverlay* ZOverlay::FromBuild(fs::path buildPath, fs::path cfgFolderPath) { - std::string cfgText = File::ReadAllText(cfgFolderPath + "/overlay.cfg"); + std::string cfgText = File::ReadAllText(cfgFolderPath / "overlay.cfg"); std::vector cfgLines = StringHelper::Split(cfgText, "\n"); ZOverlay* ovl = new ZOverlay(StringHelper::Strip(cfgLines[0], "\r")); - - std::vector relSections = {".rel.text", ".rel.data", ".rel.rodata"}; - std::vector sections = {".text", ".data", ".rodata"}; + ovl->cfgLines = cfgLines; int32_t sectionOffs[5] = {0}; std::vector textRelocs; @@ -44,8 +90,7 @@ ZOverlay* ZOverlay::FromBuild(std::string buildPath, std::string cfgFolderPath) std::vector readers; for (size_t i = 1; i < cfgLines.size(); i++) { - std::string elfPath = - buildPath + "/" + cfgLines[i].substr(0, cfgLines[i].size() - 2) + ".o"; + std::string elfPath = buildPath / (cfgLines[i].substr(0, cfgLines[i].size() - 2) + ".o"); elfio* reader = new elfio(); if (!reader->load(elfPath)) @@ -62,102 +107,119 @@ ZOverlay* ZOverlay::FromBuild(std::string buildPath, std::string cfgFolderPath) readers.push_back(reader); } - for (auto curReader : readers) + for (size_t curReaderId = 0; curReaderId < readers.size(); curReaderId++) { + auto& curReader = readers[curReaderId]; + Elf_Half sec_num = curReader->sections.size(); for (int32_t i = 0; i < sec_num; i++) { section* pSec = curReader->sections[i]; - if (pSec->get_type() == SHT_REL && std::find(relSections.begin(), relSections.end(), - pSec->get_name()) != relSections.end()) + if (pSec->get_type() != SHT_REL || + sRelSections.find(pSec->get_name()) == sRelSections.end()) { - SectionType sectionType = GetSectionTypeFromStr(pSec->get_name()); + continue; + } - if (sectionType == SectionType::ERROR) - fprintf(stderr, "WARNING: One of the section types returned ERROR\n"); + symbol_section_accessor currentSymbols(*curReader, + curReader->sections[(Elf_Half)pSec->get_link()]); - relocation_section_accessor relocs(*curReader, pSec); - for (Elf_Xword j = 0; j < relocs.get_entries_num(); j++) + SectionType sectionType = GetSectionTypeFromStr(pSec->get_name()); + + if (sectionType == SectionType::ERROR) + fprintf(stderr, "WARNING: One of the section types returned ERROR\n"); + + relocation_section_accessor relocs(*curReader, pSec); + for (Elf_Xword j = 0; j < relocs.get_entries_num(); j++) + { + Elf64_Addr offset = 0; + Elf_Word symbol = 0; + Elf_Word type = 0; { - Elf64_Addr offset = 0; - Elf_Word symbol = 0; - Elf_Word type = 0; + Elf_Sxword addend = 0; + relocs.get_entry(j, offset, symbol, type, addend); + } + + std::string curSymName; + Elf_Half curSymShndx = SHN_UNDEF; + { + Elf64_Addr value; + Elf_Xword size; + unsigned char bind; + unsigned char type; + unsigned char other; + currentSymbols.get_symbol(symbol, curSymName, value, size, bind, type, + curSymShndx, other); + } + + // check symbols outside the elf but within the overlay + if (curSymShndx == SHN_UNDEF) + { + if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_DEBUG) { - Elf_Sxword addend = 0; - relocs.get_entry(j, offset, symbol, type, addend); + printf("Symbol '%s' doesn't exist in current .o file (%s). Searching...\n", + curSymName.c_str(), cfgLines[curReaderId + 1].c_str()); } - std::string curSymName; - Elf_Half curSymShndx = SHN_UNDEF; + for (size_t readerId = 0; readerId < readers.size(); readerId++) { - symbol_section_accessor symbols( - *curReader, curReader->sections[(Elf_Half)pSec->get_link()]); - Elf64_Addr value; - Elf_Xword size; - unsigned char bind; - unsigned char type; - unsigned char other; - symbols.get_symbol(symbol, curSymName, value, size, bind, type, curSymShndx, - other); - } + auto& reader = readers[readerId]; - // check symbols outside the elf but within the overlay - if (curSymShndx == SHN_UNDEF) - { - for (auto reader : readers) + if (curSymShndx != SHN_UNDEF) + break; + + if (reader == curReader) + continue; + + auto sectionData = reader->sections[(Elf_Half)pSec->get_link()]; + curSymShndx = + ovl->FindSymbolInSection(curSymName, sectionData, *reader, readerId); + if (curSymShndx != SHN_UNDEF) + break; + + if (Globals::Instance->gccCompat) { - if (curSymShndx != SHN_UNDEF) - break; - - if (reader == curReader) - continue; - - auto sectionData = reader->sections[(Elf_Half)pSec->get_link()]; - - if (sectionData == nullptr) - continue; - - symbol_section_accessor symbols(*reader, sectionData); - - for (Elf_Xword symIdx = 0; symIdx < symbols.get_symbols_num(); symIdx++) + // Symbol wasn't found, try checking every section + Elf_Half sec_num = reader->sections.size(); + for (int32_t otherSectionIdx = 0; otherSectionIdx < sec_num; + otherSectionIdx++) { - Elf_Half shndx = SHN_UNDEF; - Elf64_Addr value; - std::string name; - Elf_Xword size; - unsigned char bind; - unsigned char type; - unsigned char other; - - symbols.get_symbol(symIdx, name, value, size, bind, type, shndx, - other); - - if (name == curSymName) + if (curSymShndx != SHN_UNDEF) { - curSymShndx = shndx; break; } + + auto sectionDataIter = reader->sections[otherSectionIdx]; + + curSymShndx = ovl->FindSymbolInSection(curSymName, sectionDataIter, + *reader, readerId); } } } + } - if (curSymShndx != SHN_UNDEF) + if (curSymShndx != SHN_UNDEF) + { + RelocationType typeConverted = (RelocationType)type; + offset += sectionOffs[static_cast(sectionType)]; + + RelocationEntry* reloc = + new RelocationEntry(sectionType, typeConverted, offset); + + if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_DEBUG) { - RelocationType typeConverted = (RelocationType)type; - offset += sectionOffs[sectionType]; - - RelocationEntry* reloc = - new RelocationEntry(sectionType, typeConverted, offset); - - // this is to keep the correct reloc entry order - if (sectionType == SectionType::Text) - textRelocs.push_back(reloc); - if (sectionType == SectionType::Data) - dataRelocs.push_back(reloc); - if (sectionType == SectionType::RoData) - rodataRelocs.push_back(reloc); + printf(".word 0x%08X # %s %s 0x%04X\n", reloc->CalcRelocationWord(), + reloc->GetSectionName(), reloc->GetRelocTypeName(), reloc->offset); } + + // this is to keep the correct reloc entry order + if (sectionType == SectionType::Text) + textRelocs.push_back(reloc); + if (sectionType == SectionType::Data) + dataRelocs.push_back(reloc); + if (sectionType == SectionType::RoData) + rodataRelocs.push_back(reloc); } } } @@ -167,20 +229,18 @@ ZOverlay* ZOverlay::FromBuild(std::string buildPath, std::string cfgFolderPath) { section* pSec = curReader->sections[i]; if (pSec->get_type() == SHT_PROGBITS && - std::find(sections.begin(), sections.end(), pSec->get_name()) != sections.end()) + sSections.find(pSec->get_name()) != sSections.end()) { SectionType sectionType = GetSectionTypeFromStr(pSec->get_name()); - sectionOffs[sectionType] += pSec->get_size(); + sectionOffs[static_cast(sectionType)] += pSec->get_size(); } } } - for (auto reloc : textRelocs) - ovl->entries.push_back(reloc); - for (auto reloc : dataRelocs) - ovl->entries.push_back(reloc); - for (auto reloc : rodataRelocs) - ovl->entries.push_back(reloc); + ovl->entries.reserve(textRelocs.size() + dataRelocs.size() + rodataRelocs.size()); + ovl->entries.insert(ovl->entries.end(), textRelocs.begin(), textRelocs.end()); + ovl->entries.insert(ovl->entries.end(), dataRelocs.begin(), dataRelocs.end()); + ovl->entries.insert(ovl->entries.end(), rodataRelocs.begin(), rodataRelocs.end()); for (auto r : readers) delete r; @@ -189,23 +249,27 @@ ZOverlay* ZOverlay::FromBuild(std::string buildPath, std::string cfgFolderPath) return ovl; } -std::string ZOverlay::GetSourceOutputCode(const std::string& prefix) +std::string ZOverlay::GetSourceOutputCode([[maybe_unused]] const std::string& prefix) { - std::string output = ""; + std::string output; output += ".section .ovl\n"; + output += StringHelper::Sprintf("# %sOverlayInfo\n", name.c_str()); output += StringHelper::Sprintf(".word _%sSegmentTextSize\n", name.c_str()); output += StringHelper::Sprintf(".word _%sSegmentDataSize\n", name.c_str()); output += StringHelper::Sprintf(".word _%sSegmentRoDataSize\n", name.c_str()); output += StringHelper::Sprintf(".word _%sSegmentBssSize\n", name.c_str()); + output += "\n"; - output += StringHelper::Sprintf(".word %i\n", entries.size()); + output += StringHelper::Sprintf(".word %i # reloc_count\n", entries.size()); for (size_t i = 0; i < entries.size(); i++) { RelocationEntry* reloc = entries[i]; - output += StringHelper::Sprintf(".word 0x%08X\n", reloc->CalcRelocationWord()); + output += StringHelper::Sprintf(".word 0x%08X # %s %s 0x%04X\n", + reloc->CalcRelocationWord(), reloc->GetSectionName(), + reloc->GetRelocTypeName(), reloc->offset); } size_t offset = (entries.size() * 4) + 20; @@ -216,11 +280,13 @@ std::string ZOverlay::GetSourceOutputCode(const std::string& prefix) offset += 4; } - output += StringHelper::Sprintf(".word 0x%08X\n", offset + 4); + output += "\n"; + output += + StringHelper::Sprintf(".word 0x%08X # %sOverlayInfoOffset\n", offset + 4, name.c_str()); return output; } -SectionType ZOverlay::GetSectionTypeFromStr(std::string sectionName) +SectionType ZOverlay::GetSectionTypeFromStr(const std::string& sectionName) { if (sectionName == ".rel.text" || sectionName == ".text") return SectionType::Text; @@ -234,3 +300,50 @@ SectionType ZOverlay::GetSectionTypeFromStr(std::string sectionName) return SectionType::ERROR; } + +ELFIO::Elf_Half ZOverlay::FindSymbolInSection(const std::string& curSymName, + ELFIO::section* sectionData, ELFIO::elfio& reader, + size_t readerId) +{ + if (sectionData == nullptr) + return SHN_UNDEF; + + auto sectionDataName = sectionData->get_name(); + if (sSections.find(sectionDataName) == sSections.end()) + return SHN_UNDEF; + +#ifdef DEVELOPMENT + if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_DEBUG) + { + printf("\t File '%s' section: %s \n", cfgLines[readerId + 1].c_str(), + sectionDataName.c_str()); + } +#endif + + symbol_section_accessor symbols(reader, sectionData); + + Elf_Xword symbolNum = symbols.get_symbols_num(); + for (Elf_Xword symIdx = 0; symIdx < symbolNum; symIdx++) + { + Elf_Half shndx = SHN_UNDEF; + Elf64_Addr value; + std::string name; + Elf_Xword size; + unsigned char bind; + unsigned char type; + unsigned char other; + + symbols.get_symbol(symIdx, name, value, size, bind, type, shndx, other); + + if (name == curSymName) + { + if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_DEBUG) + { + printf("\t Symbol '%s' found in '%s' '%s' \n", curSymName.c_str(), + cfgLines[readerId + 1].c_str(), sectionDataName.c_str()); + } + return shndx; + } + } + return SHN_UNDEF; +} diff --git a/tools/ZAPD/ZAPD/Overlays/ZOverlay.h b/tools/ZAPD/ZAPD/Overlays/ZOverlay.h index 08e573de14..98ead90132 100644 --- a/tools/ZAPD/ZAPD/Overlays/ZOverlay.h +++ b/tools/ZAPD/ZAPD/Overlays/ZOverlay.h @@ -1,10 +1,11 @@ #pragma once -#include -#include "../ZResource.h" +#include "Utils/Directory.h" +#include "ZResource.h" +#include "elfio/elfio.hpp" #include "tinyxml2.h" -enum SectionType +enum class SectionType { Text = 1, Data = 2, @@ -13,7 +14,7 @@ enum SectionType ERROR = 255 }; -enum RelocationType +enum class RelocationType { R_MIPS_32 = 2, R_MIPS_26 = 4, @@ -39,12 +40,15 @@ public: { uint32_t relocationWord = 0; - relocationWord |= sectionType << 30; - relocationWord |= relocationType << 24; + relocationWord |= static_cast(sectionType) << 30; + relocationWord |= static_cast(relocationType) << 24; relocationWord |= offset; return relocationWord; } + + const char* GetSectionName() const; + const char* GetRelocTypeName() const; }; class ZOverlay @@ -52,16 +56,20 @@ class ZOverlay public: std::string name; - ZOverlay(std::string nName); + ZOverlay(const std::string& nName); ~ZOverlay(); - static ZOverlay* FromBuild(std::string buildPath, std::string cfgFolderPath); + static ZOverlay* FromBuild(fs::path buildPath, fs::path cfgFolderPath); std::string GetSourceOutputCode(const std::string& prefix); private: std::vector entries; + std::vector cfgLines; ZOverlay(); - static SectionType GetSectionTypeFromStr(std::string sectionName); + static SectionType GetSectionTypeFromStr(const std::string& sectionName); // static std::string GetOverlayNameFromElf(ELFIO::elfio& reader); + + ELFIO::Elf_Half FindSymbolInSection(const std::string& curSymName, ELFIO::section* sectionData, + ELFIO::elfio& reader, size_t readerId); }; diff --git a/tools/ZAPD/ZAPD/Path.h b/tools/ZAPD/ZAPD/Path.h deleted file mode 100644 index 68cfaea4bc..0000000000 --- a/tools/ZAPD/ZAPD/Path.h +++ /dev/null @@ -1,53 +0,0 @@ -#pragma once - -#include -#include -#include "StringHelper.h" - -#if __has_include() -#include -namespace fs = std::filesystem; -#else -#include -namespace fs = std::experimental::filesystem; -#endif - -class Path -{ -public: - static std::string GetFileName(const std::string& input) - { - std::vector split = StringHelper::Split(input, "/"); - return split[split.size() - 1]; - }; - - static std::string GetFileNameWithoutExtension(const std::string& input) - { - std::vector split = StringHelper::Split(input, "/"); - return split[split.size() - 1].substr(0, split[split.size() - 1].find_last_of(".")); - }; - - static std::string GetFileNameExtension(const std::string& input) - { - return input.substr(input.find_last_of("."), input.length()); - }; - - static std::string GetPath(const std::string& input) - { - std::vector split = StringHelper::Split(input, "/"); - std::string output = ""; - - for (std::string str : split) - { - if (str.find_last_of(".") == std::string::npos) - output += str + "/"; - } - - return output; - }; - - static std::string GetDirectoryName(const fs::path& path) - { - return path.parent_path().u8string(); - }; -}; diff --git a/tools/ZAPD/ZAPD/ZAPD.vcxproj b/tools/ZAPD/ZAPD/ZAPD.vcxproj index 59aaf11473..c74d28cbec 100644 --- a/tools/ZAPD/ZAPD/ZAPD.vcxproj +++ b/tools/ZAPD/ZAPD/ZAPD.vcxproj @@ -71,12 +71,16 @@ - $(SolutionDir)lib\tinyxml2;$(SolutionDir)lib\libgfxd;$(SolutionDir)lib\elfio;$(SolutionDir)lib\assimp\include;$(SolutionDir)lib\stb;$(ProjectDir);$(IncludePath) - $(SolutionDir)lib\libgfxd;$(SolutionDir)lib\assimp-built;$(LibraryPath) + $(SolutionDir)lib\libgfxd;$(SolutionDir)x64\Debug;$(SolutionDir)packages\libpng.1.6.28.1\build\native\lib\x64\v140\dynamic\Debug;$(LibraryPath) + $(SolutionDir)ZAPDUtils;$(SolutionDir)lib\tinyxml2;$(SolutionDir)lib\libgfxd;$(SolutionDir)lib\elfio;$(SolutionDir)lib\stb;$(ProjectDir);$(IncludePath) $(IncludePath) + + $(SolutionDir)ZAPD\lib\tinyxml2;$(SolutionDir)ZAPD\lib\libgfxd;$(SolutionDir)ZAPD\lib\elfio;$(SolutionDir)ZAPD\lib\stb;$(ProjectDir);$(IncludePath) + $(SolutionDir)ZAPD\lib\libgfxd;$(SolutionDir)x64\Debug;$(SolutionDir)packages\libpng.1.6.28.1\build\native\lib\x64\v140\dynamic\Debug;$(LibraryPath) + Level3 @@ -84,6 +88,8 @@ true true stdcpp17 + stdc11 + _CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) true @@ -96,13 +102,13 @@ true true stdcpp17 - _CRT_SECURE_NO_WARNINGS;_SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING;USE_ASSIMP;%(PreprocessorDefinitions) + _CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) EnableFastChecks stdc11 true - assimp-vc142-mt.lib;%(AdditionalDependencies) + libpng16.lib;ZAPDUtils.lib;/WHOLEARCHIVE:ExporterExample.lib;%(AdditionalDependencies) cd .. @@ -148,10 +154,9 @@ python3 ZAPD/genbuildinfo.py + - - - + @@ -160,8 +165,9 @@ python3 ZAPD/genbuildinfo.py + - + @@ -204,6 +210,7 @@ python3 ZAPD/genbuildinfo.py + @@ -222,29 +229,18 @@ python3 ZAPD/genbuildinfo.py - - - - - + - - - - - + - - - @@ -256,8 +252,9 @@ python3 ZAPD/genbuildinfo.py + - + @@ -266,7 +263,6 @@ python3 ZAPD/genbuildinfo.py - @@ -293,9 +289,9 @@ python3 ZAPD/genbuildinfo.py - + @@ -307,10 +303,22 @@ python3 ZAPD/genbuildinfo.py - - Document - + - + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + + + \ No newline at end of file diff --git a/tools/ZAPD/ZAPD/ZAPD.vcxproj.filters b/tools/ZAPD/ZAPD/ZAPD.vcxproj.filters index 0feff6f205..2d3050ed42 100644 --- a/tools/ZAPD/ZAPD/ZAPD.vcxproj.filters +++ b/tools/ZAPD/ZAPD/ZAPD.vcxproj.filters @@ -40,18 +40,6 @@ {73db0879-6df8-4f6a-8cc2-a1f836e9e796} - - {9464ff21-96af-4b7d-a57b-f62bd9b7389a} - - - {e9865c34-fd69-413c-8cce-3f51331c3503} - - - {0f9980bb-ae46-4891-a39e-275bf255f010} - - - {11dbd8e6-d97a-42a5-b40c-e1350389544d} - {be9a5be0-ec6a-4200-8e39-bb58c7da7aa8} @@ -174,15 +162,6 @@ Source Files\Z64 - - Source Files\HighLevel - - - Source Files\HighLevel - - - Source Files\HighLevel - Source Files\Z64 @@ -249,9 +228,6 @@ Source Files\Z64\ZRoom\Commands - - Source Files\Z64\ZRoom\Commands - Source Files\Z64\ZRoom\Commands @@ -267,17 +243,23 @@ Source Files\Z64 + + Source Files\Z64\ZRoom\Commands + + + Source Files\Z64 + + + Source Files + + + Source Files + + + Source Files\Z64 + - - Header Files - - - Header Files - - - Header Files - Header Files\Z64\ZRoom @@ -296,9 +278,6 @@ Header Files\Z64\ZRoom\Commands - - Header Files - Header Files\Z64\ZRoom\Commands @@ -359,9 +338,6 @@ Header Files\Libraries\elfio - - Header Files - Header Files @@ -389,12 +365,6 @@ Header Files\Z64\ZRoom\Commands - - Header Files\Z64\ZRoom - - - Header Files\Z64\ZRoom - Header Files\Z64\ZRoom\Commands @@ -407,21 +377,12 @@ Header Files\Z64\ZRoom\Commands - - Header Files - - - Header Files\Libraries - Header Files\Libraries Header Files\Libraries - - Header Files\Libraries - Header Files\Z64 @@ -446,24 +407,9 @@ Header Files\Z64 - - Header Files\HighLevel - - - Header Files\HighLevel - - - Header Files\HighLevel - - - Header Files\HighLevel - Header Files\Z64 - - Header Files\HighLevel - Header Files\Z64\ZRoom\Commands @@ -521,9 +467,6 @@ Header Files\Z64\ZRoom\Commands - - Header Files\Z64\ZRoom\Commands - Header Files\Z64\ZRoom\Commands @@ -539,6 +482,21 @@ Header Files\Z64 + + Header Files\Z64\ZRoom\Commands + + + Header Files + + + Header Files\Z64 + + + Header Files + + + Header Files\Z64 + @@ -546,8 +504,6 @@ - - Resource Files - + \ No newline at end of file diff --git a/tools/ZAPD/ZAPD/ZAnimation.cpp b/tools/ZAPD/ZAPD/ZAnimation.cpp index 742d8135ee..9242f657a8 100644 --- a/tools/ZAPD/ZAPD/ZAnimation.cpp +++ b/tools/ZAPD/ZAPD/ZAnimation.cpp @@ -1,10 +1,11 @@ #include "ZAnimation.h" + #include -#include "BitConverter.h" -#include "File.h" + #include "Globals.h" -#include "HighLevel/HLAnimationIntermediette.h" -#include "StringHelper.h" +#include "Utils/BitConverter.h" +#include "Utils/File.h" +#include "Utils/StringHelper.h" #include "ZFile.h" REGISTER_ZFILENODE(Animation, ZNormalAnimation); @@ -24,85 +25,15 @@ void ZAnimation::ParseRawData() frameCount = BitConverter::ToInt16BE(parent->GetRawData(), rawDataIndex + 0); } -void ZAnimation::Save(const fs::path& outFolder) -{ - if (Globals::Instance->testMode) - { - HLAnimationIntermediette* anim = HLAnimationIntermediette::FromZAnimation(this); - std::string xml = anim->OutputXML(); - File::WriteAllText(outFolder / (name + ".anmi"), xml); - - delete anim; - } -} - -std::string ZAnimation::GetSourceOutputCode(const std::string& prefix) -{ - return ""; -} - ZResourceType ZAnimation::GetResourceType() const { return ZResourceType::Animation; } +/* ZNormalAnimation */ + ZNormalAnimation::ZNormalAnimation(ZFile* nParent) : ZAnimation(nParent) { - rotationValues = std::vector(); - rotationIndices = std::vector(); - limit = 0; -} - -std::string ZNormalAnimation::GetSourceOutputCode(const std::string& prefix) -{ - if (parent != nullptr) - { - std::string defaultPrefix = name.c_str(); - defaultPrefix.replace(0, 1, "s"); // replace g prefix with s for local variables - - std::string headerStr = StringHelper::Sprintf("\n\t{ %i },\n", frameCount); - headerStr += StringHelper::Sprintf("\t%sFrameData,\n", defaultPrefix.c_str()); - headerStr += StringHelper::Sprintf("\t%sJointIndices,\n", defaultPrefix.c_str()); - headerStr += StringHelper::Sprintf("\t%i\n", limit); - parent->AddDeclaration(rawDataIndex, DeclarationAlignment::None, GetRawDataSize(), - GetSourceTypeName(), StringHelper::Sprintf("%s", name.c_str()), - headerStr); - - std::string indicesStr = ""; - std::string valuesStr = " "; - const uint8_t lineLength = 14; - const uint8_t offset = 0; - - for (size_t i = 0; i < rotationValues.size(); i++) - { - valuesStr += StringHelper::Sprintf("0x%04X, ", rotationValues[i]); - - if ((i - offset + 1) % lineLength == 0) - valuesStr += "\n "; - } - - for (size_t i = 0; i < rotationIndices.size(); i++) - { - indicesStr += - StringHelper::Sprintf(" { 0x%04X, 0x%04X, 0x%04X },", rotationIndices[i].x, - rotationIndices[i].y, rotationIndices[i].z); - - if (i != (rotationIndices.size() - 1)) - indicesStr += "\n"; - } - - parent->AddDeclarationArray(rotationValuesSeg, DeclarationAlignment::Align16, - rotationValues.size() * 2, "static s16", - StringHelper::Sprintf("%sFrameData", defaultPrefix.c_str()), - rotationValues.size(), valuesStr); - - parent->AddDeclarationArray(rotationIndicesSeg, DeclarationAlignment::Align16, - rotationIndices.size() * 6, "static JointIndex", - StringHelper::Sprintf("%sJointIndices", defaultPrefix.c_str()), - rotationIndices.size(), indicesStr); - } - - return ""; } size_t ZNormalAnimation::GetRawDataSize() const @@ -121,23 +52,26 @@ void ZNormalAnimation::ParseRawData() const uint8_t* data = parent->GetRawData().data(); - rotationValuesSeg = BitConverter::ToInt32BE(data, rawDataIndex + 4) & 0x00FFFFFF; - rotationIndicesSeg = BitConverter::ToInt32BE(data, rawDataIndex + 8) & 0x00FFFFFF; + rotationValuesSeg = BitConverter::ToInt32BE(data, rawDataIndex + 4); + rotationIndicesSeg = BitConverter::ToInt32BE(data, rawDataIndex + 8); limit = BitConverter::ToInt16BE(data, rawDataIndex + 12); - uint32_t currentPtr = rotationValuesSeg; + rotationValuesOffset = Seg2Filespace(rotationValuesSeg, parent->baseAddress); + rotationIndicesOffset = Seg2Filespace(rotationIndicesSeg, parent->baseAddress); + + uint32_t currentPtr = rotationValuesOffset; // Read the Rotation Values - for (uint32_t i = 0; i < ((rotationIndicesSeg - rotationValuesSeg) / 2); i++) + for (uint32_t i = 0; i < ((rotationIndicesOffset - rotationValuesOffset) / 2); i++) { rotationValues.push_back(BitConverter::ToInt16BE(data, currentPtr)); currentPtr += 2; } - currentPtr = rotationIndicesSeg; + currentPtr = rotationIndicesOffset; // Read the Rotation Indices - for (uint32_t i = 0; i < ((rawDataIndex - rotationIndicesSeg) / 6); i++) + for (uint32_t i = 0; i < ((rawDataIndex - rotationIndicesOffset) / 6); i++) { rotationIndices.push_back(RotationIndex(BitConverter::ToInt16BE(data, currentPtr), BitConverter::ToInt16BE(data, currentPtr + 2), @@ -146,31 +80,71 @@ void ZNormalAnimation::ParseRawData() } } +void ZNormalAnimation::DeclareReferences(const std::string& prefix) +{ + std::string defaultPrefix = prefix.c_str(); + if (name != "") + defaultPrefix = name; + + // replace g prefix with s for local variables + if (defaultPrefix.at(0) == 'g') + defaultPrefix.replace(0, 1, "s"); + + std::string indicesStr = ""; + std::string valuesStr = " "; + const uint8_t lineLength = 14; + const uint8_t offset = 0; + + for (size_t i = 0; i < rotationValues.size(); i++) + { + valuesStr += StringHelper::Sprintf("0x%04X, ", rotationValues[i]); + + if ((i - offset + 1) % lineLength == 0) + valuesStr += "\n "; + } + + parent->AddDeclarationArray(rotationValuesOffset, DeclarationAlignment::Align16, + rotationValues.size() * 2, "s16", + StringHelper::Sprintf("%sFrameData", defaultPrefix.c_str()), + rotationValues.size(), valuesStr); + + for (size_t i = 0; i < rotationIndices.size(); i++) + { + indicesStr += StringHelper::Sprintf(" { 0x%04X, 0x%04X, 0x%04X },", rotationIndices[i].x, + rotationIndices[i].y, rotationIndices[i].z); + + if (i != (rotationIndices.size() - 1)) + indicesStr += "\n"; + } + + parent->AddDeclarationArray(rotationIndicesOffset, DeclarationAlignment::Align16, + rotationIndices.size() * 6, "JointIndex", + StringHelper::Sprintf("%sJointIndices", defaultPrefix.c_str()), + rotationIndices.size(), indicesStr); +} + +std::string ZNormalAnimation::GetBodySourceCode() const +{ + std::string frameDataName; + Globals::Instance->GetSegmentedPtrName(rotationValuesSeg, parent, "s16", frameDataName); + std::string jointIndicesName; + Globals::Instance->GetSegmentedPtrName(rotationIndicesSeg, parent, "JointIndex", + jointIndicesName); + + std::string headerStr = + StringHelper::Sprintf("\n\t{ %i }, %s,\n", frameCount, frameDataName.c_str()); + headerStr += StringHelper::Sprintf("\t%s, %i\n", jointIndicesName.c_str(), limit); + + return headerStr; +} + +/* ZLinkAnimation */ + ZLinkAnimation::ZLinkAnimation(ZFile* nParent) : ZAnimation(nParent) { segmentAddress = 0; } -std::string ZLinkAnimation::GetSourceOutputCode(const std::string& prefix) -{ - if (parent != nullptr) - { - std::string segSymbol = - segmentAddress == 0 ? - "NULL" : - parent->GetDeclarationName( - segmentAddress, - StringHelper::Sprintf("%sSeg%06X", name.c_str(), segmentAddress)); - std::string headerStr = - StringHelper::Sprintf("\n\t{ %i },\n\t0x%08X\n", frameCount, segmentAddress); - parent->AddDeclaration(rawDataIndex, DeclarationAlignment::None, GetRawDataSize(), - GetSourceTypeName(), StringHelper::Sprintf("%s", name.c_str()), - headerStr); - } - - return ""; -} - size_t ZLinkAnimation::GetRawDataSize() const { return 8; @@ -185,8 +159,16 @@ void ZLinkAnimation::ParseRawData() { ZAnimation::ParseRawData(); - const uint8_t* data = parent->GetRawData().data(); - segmentAddress = (BitConverter::ToInt32BE(data, rawDataIndex + 4)); + const auto& rawData = parent->GetRawData(); + segmentAddress = BitConverter::ToInt32BE(rawData, rawDataIndex + 4); +} + +std::string ZLinkAnimation::GetBodySourceCode() const +{ + std::string segSymbol; + Globals::Instance->GetSegmentedPtrName(segmentAddress, parent, "", segSymbol); + + return StringHelper::Sprintf("\n\t{ %i }, %s\n", frameCount, segSymbol.c_str()); } /* ZCurveAnimation */ @@ -208,7 +190,7 @@ TransformData::TransformData(ZFile* parent, const std::vector& rawData, { } -std::string TransformData::GetBody(const std::string& prefix) const +std::string TransformData::GetBody([[maybe_unused]] const std::string& prefix) const { return StringHelper::Sprintf("0x%04X, 0x%04X, %i, %i, %ff", unk_00, unk_02, unk_04, unk_06, unk_08); @@ -256,8 +238,8 @@ void ZCurveAnimation::ParseRawData() unk_0C = BitConverter::ToInt16BE(rawData, rawDataIndex + 12); unk_10 = BitConverter::ToInt16BE(rawData, rawDataIndex + 14); - limbCount = - BitConverter::ToUInt8BE(rawData, Seg2Filespace(skelOffset, parent->baseAddress) + 4); + uint32_t limbCountAddress = Seg2Filespace(skelOffset, parent->baseAddress) + 4; + limbCount = BitConverter::ToUInt8BE(rawData, limbCountAddress); size_t transformDataSize = 0; size_t copyValuesSize = 0; @@ -293,14 +275,6 @@ void ZCurveAnimation::ParseRawData() } } -void ZCurveAnimation::ExtractFromXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex) -{ - ZResource::ExtractFromXML(reader, nRawDataIndex); - - parent->AddDeclaration(rawDataIndex, DeclarationAlignment::Align16, GetRawDataSize(), - GetSourceTypeName(), name, ""); -} - void ZCurveAnimation::DeclareReferences(const std::string& prefix) { if (refIndex != 0) @@ -321,7 +295,7 @@ void ZCurveAnimation::DeclareReferences(const std::string& prefix) Declaration* decl = parent->GetDeclaration(refIndexOffset); if (decl == nullptr) { - parent->AddDeclarationArray(refIndexOffset, DeclarationAlignment::None, + parent->AddDeclarationArray(refIndexOffset, DeclarationAlignment::Align4, arrayItemCnt * 1, "u8", refIndexStr, arrayItemCnt, entryStr); } @@ -338,7 +312,7 @@ void ZCurveAnimation::DeclareReferences(const std::string& prefix) "%sCurveAnime_%s_%06X", prefix.c_str(), transformDataArr.at(0).GetSourceTypeName().c_str(), transformDataOffset); - std::string entryStr = ""; + std::string entryStr; uint16_t arrayItemCnt = transformDataArr.size(); size_t i = 0; @@ -351,7 +325,7 @@ void ZCurveAnimation::DeclareReferences(const std::string& prefix) Declaration* decl = parent->GetDeclaration(transformDataOffset); if (decl == nullptr) { - parent->AddDeclarationArray(transformDataOffset, DeclarationAlignment::None, + parent->AddDeclarationArray(transformDataOffset, DeclarationAlignment::Align4, arrayItemCnt * transformDataArr.at(0).GetRawDataSize(), transformDataArr.at(0).GetSourceTypeName(), transformDataStr, arrayItemCnt, entryStr); @@ -380,7 +354,7 @@ void ZCurveAnimation::DeclareReferences(const std::string& prefix) Declaration* decl = parent->GetDeclaration(copyValuesOffset); if (decl == nullptr) { - parent->AddDeclarationArray(copyValuesOffset, DeclarationAlignment::None, + parent->AddDeclarationArray(copyValuesOffset, DeclarationAlignment::Align4, arrayItemCnt * 2, "s16", copyValuesStr, arrayItemCnt, entryStr); } @@ -391,81 +365,28 @@ void ZCurveAnimation::DeclareReferences(const std::string& prefix) } } +std::string ZCurveAnimation::GetBodySourceCode() const +{ + std::string refIndexStr; + Globals::Instance->GetSegmentedPtrName(refIndex, parent, "u8", refIndexStr); + std::string transformDataStr; + Globals::Instance->GetSegmentedPtrName(transformData, parent, "TransformData", + transformDataStr); + std::string copyValuesStr; + Globals::Instance->GetSegmentedPtrName(copyValues, parent, "s16", copyValuesStr); + + return StringHelper::Sprintf("\n\t%s,\n\t%s,\n\t%s,\n\t%i, %i\n", refIndexStr.c_str(), + transformDataStr.c_str(), copyValuesStr.c_str(), unk_0C, unk_10); +} + size_t ZCurveAnimation::GetRawDataSize() const { return 0x10; } -std::string ZCurveAnimation::GetSourceOutputCode(const std::string& prefix) +DeclarationAlignment ZCurveAnimation::GetDeclarationAlignment() const { - std::string bodyStr = ""; - uint32_t address = Seg2Filespace(rawDataIndex, parent->baseAddress); - - std::string refIndexStr = "NULL"; - if (refIndex != 0) - { - uint32_t refIndexOffset = Seg2Filespace(refIndex, parent->baseAddress); - Declaration* decl = parent->GetDeclaration(refIndexOffset); - if (decl == nullptr) - { - refIndexStr = StringHelper::Sprintf("%sCurveAnime_%s_%06X", prefix.c_str(), "Ref", - refIndexOffset); - } - else - { - refIndexStr = decl->varName; - } - } - - std::string transformDataStr = "NULL"; - if (transformData != 0) - { - uint32_t transformDataOffset = Seg2Filespace(transformData, parent->baseAddress); - Declaration* decl = parent->GetDeclaration(transformDataOffset); - if (decl == nullptr) - { - transformDataStr = StringHelper::Sprintf( - "%sCurveAnime_%s_%06X", prefix.c_str(), - transformDataArr.at(0).GetSourceTypeName().c_str(), transformDataOffset); - } - else - { - transformDataStr = decl->varName; - } - } - - std::string copyValuesStr = "NULL"; - if (copyValues != 0) - { - uint32_t copyValuesOffset = Seg2Filespace(copyValues, parent->baseAddress); - Declaration* decl = parent->GetDeclaration(copyValuesOffset); - if (decl == nullptr) - { - copyValuesStr = StringHelper::Sprintf("%sCurveAnime_%s_%06X", prefix.c_str(), "Copy", - copyValuesOffset); - } - else - { - copyValuesStr = decl->varName; - } - } - - bodyStr = - StringHelper::Sprintf("\n %s,\n %s,\n %s,\n %i, %i\n", refIndexStr.c_str(), - transformDataStr.c_str(), copyValuesStr.c_str(), unk_0C, unk_10); - - Declaration* decl = parent->GetDeclaration(address); - if (decl == nullptr) - { - parent->AddDeclaration(address, DeclarationAlignment::None, GetRawDataSize(), - GetSourceTypeName(), name, bodyStr); - } - else - { - decl->text = bodyStr; - } - - return ""; + return DeclarationAlignment::Align16; } std::string ZCurveAnimation::GetSourceTypeName() const @@ -479,14 +400,6 @@ ZLegacyAnimation::ZLegacyAnimation(ZFile* nParent) : ZAnimation(nParent) { } -void ZLegacyAnimation::ExtractFromXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex) -{ - ZAnimation::ExtractFromXML(reader, nRawDataIndex); - - parent->AddDeclaration(rawDataIndex, DeclarationAlignment::Align4, GetRawDataSize(), - GetSourceTypeName(), name, ""); -} - void ZLegacyAnimation::ParseRawData() { ZAnimation::ParseRawData(); @@ -556,7 +469,7 @@ void ZLegacyAnimation::DeclareReferences(const std::string& prefix) if (GETSEGNUM(jointKey) == parent->segment && !parent->HasDeclaration(jointKeyOffset)) { const auto res = jointKeyArray.at(0); - std::string jointKeyBody = ""; + std::string jointKeyBody; for (size_t i = 0; i < jointKeyArray.size(); i++) { @@ -580,8 +493,10 @@ std::string ZLegacyAnimation::GetBodySourceCode() const { std::string body = "\n"; - std::string frameDataName = parent->GetDeclarationPtrName(frameData); - std::string jointKeyName = parent->GetDeclarationPtrName(jointKey); + std::string frameDataName; + std::string jointKeyName; + Globals::Instance->GetSegmentedPtrName(frameData, parent, "s16", frameDataName); + Globals::Instance->GetSegmentedPtrName(jointKey, parent, "JointKey", jointKeyName); body += StringHelper::Sprintf("\t%i, %i,\n", frameCount, limbCount); body += StringHelper::Sprintf("\t%s,\n", frameDataName.c_str()); @@ -590,20 +505,6 @@ std::string ZLegacyAnimation::GetBodySourceCode() const return body; } -std::string ZLegacyAnimation::GetSourceOutputCode(const std::string& prefix) -{ - std::string body = GetBodySourceCode(); - - Declaration* decl = parent->GetDeclaration(rawDataIndex); - if (decl == nullptr || decl->isPlaceholder) - parent->AddDeclaration(rawDataIndex, DeclarationAlignment::Align4, GetRawDataSize(), - GetSourceTypeName(), name, body); - else - decl->text = body; - - return ""; -} - std::string ZLegacyAnimation::GetSourceTypeName() const { return "LegacyAnimationHeader"; diff --git a/tools/ZAPD/ZAPD/ZAnimation.h b/tools/ZAPD/ZAPD/ZAnimation.h index f7d2a7cf17..e5b69d3ef8 100644 --- a/tools/ZAPD/ZAPD/ZAnimation.h +++ b/tools/ZAPD/ZAPD/ZAnimation.h @@ -13,12 +13,7 @@ struct RotationIndex // uint16_t transX, transY, transZ; uint16_t x, y, z; - RotationIndex(uint16_t nX, uint16_t nY, uint16_t nZ) - { - x = nX; - y = nY; - z = nZ; - }; + RotationIndex(uint16_t nX, uint16_t nY, uint16_t nZ) : x(nX), y(nY), z(nZ) {} }; class ZAnimation : public ZResource @@ -28,12 +23,10 @@ public: ZAnimation(ZFile* nParent); - std::string GetSourceOutputCode(const std::string& prefix) override; ZResourceType GetResourceType() const override; protected: void ParseRawData() override; - void Save(const fs::path& outFolder) override; }; class ZNormalAnimation : public ZAnimation @@ -41,18 +34,22 @@ class ZNormalAnimation : public ZAnimation public: std::vector rotationValues; std::vector rotationIndices; - uint32_t rotationValuesSeg; - uint32_t rotationIndicesSeg; - int16_t limit; + segptr_t rotationValuesSeg = 0; + segptr_t rotationIndicesSeg = 0; + offset_t rotationValuesOffset = 0; + offset_t rotationIndicesOffset = 0; + int16_t limit = 0; ZNormalAnimation(ZFile* nParent); - std::string GetSourceOutputCode(const std::string& prefix) override; + void DeclareReferences(const std::string& prefix) override; + + std::string GetBodySourceCode() const override; + size_t GetRawDataSize() const override; std::string GetSourceTypeName() const override; -protected: - virtual void ParseRawData() override; + void ParseRawData() override; }; class ZLinkAnimation : public ZAnimation @@ -62,12 +59,12 @@ public: ZLinkAnimation(ZFile* nParent); - std::string GetSourceOutputCode(const std::string& prefix) override; + std::string GetBodySourceCode() const override; + size_t GetRawDataSize() const override; std::string GetSourceTypeName() const override; -protected: - virtual void ParseRawData() override; + void ParseRawData() override; }; class TransformData @@ -121,16 +118,17 @@ protected: std::vector copyValuesArr; public: - ZCurveAnimation(); ZCurveAnimation(ZFile* nParent); void ParseXML(tinyxml2::XMLElement* reader) override; void ParseRawData() override; - void ExtractFromXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex) override; void DeclareReferences(const std::string& prefix) override; + + std::string GetBodySourceCode() const override; + size_t GetRawDataSize() const override; - std::string GetSourceOutputCode(const std::string& prefix) override; + DeclarationAlignment GetDeclarationAlignment() const override; std::string GetSourceTypeName() const override; }; @@ -162,13 +160,10 @@ class ZLegacyAnimation : public ZAnimation public: ZLegacyAnimation(ZFile* nParent); - void ExtractFromXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex) override; - void ParseRawData() override; void DeclareReferences(const std::string& prefix) override; - std::string GetBodySourceCode() const override; - std::string GetSourceOutputCode(const std::string& prefix) override; + std::string GetBodySourceCode() const override; std::string GetSourceTypeName() const override; diff --git a/tools/ZAPD/ZAPD/ZArray.cpp b/tools/ZAPD/ZAPD/ZArray.cpp index e514960fb0..b1ba3a6693 100644 --- a/tools/ZAPD/ZAPD/ZArray.cpp +++ b/tools/ZAPD/ZAPD/ZArray.cpp @@ -1,7 +1,9 @@ #include "ZArray.h" + #include + #include "Globals.h" -#include "StringHelper.h" +#include "Utils/StringHelper.h" #include "ZFile.h" REGISTER_ZFILENODE(Array, ZArray); @@ -53,23 +55,56 @@ void ZArray::ParseXML(tinyxml2::XMLElement* reader) } } -std::string ZArray::GetSourceOutputCode(const std::string& prefix) +Declaration* ZArray::DeclareVar(const std::string& prefix, const std::string& bodyStr) { - std::string output = ""; + std::string auxName = name; + + if (name == "") + auxName = GetDefaultName(prefix); + + ZResource* res = resList.at(0); + Declaration* decl; + if (res->IsExternalResource()) + { + auto filepath = Globals::Instance->outputPath / name; + std::string includePath = StringHelper::Sprintf("%s.%s.inc", filepath.c_str(), + res->GetExternalExtension().c_str()); + decl = parent->AddDeclarationIncludeArray(rawDataIndex, includePath, GetRawDataSize(), + GetSourceTypeName(), name, arrayCnt); + decl->text = bodyStr; + decl->isExternal = true; + } + else + { + decl = + parent->AddDeclarationArray(rawDataIndex, GetDeclarationAlignment(), GetRawDataSize(), + GetSourceTypeName(), name, arrayCnt, bodyStr); + } + + decl->staticConf = staticConf; + return decl; +} + +std::string ZArray::GetBodySourceCode() const +{ + std::string output; for (size_t i = 0; i < arrayCnt; i++) { - output += resList.at(i)->GetBodySourceCode(); + const auto& res = resList[i]; + output += "\t"; - if (i < arrayCnt - 1) + if (res->GetResourceType() == ZResourceType::Scalar || + res->GetResourceType() == ZResourceType::Vertex) + output += resList.at(i)->GetBodySourceCode(); + else + output += StringHelper::Sprintf("{ %s }", resList.at(i)->GetBodySourceCode().c_str()); + + if (i < arrayCnt - 1 || res->IsExternalResource()) output += ",\n"; } - if (parent != nullptr) - parent->AddDeclarationArray(rawDataIndex, DeclarationAlignment::None, GetRawDataSize(), - resList.at(0)->GetSourceTypeName(), name, arrayCnt, output); - - return ""; + return output; } size_t ZArray::GetRawDataSize() const @@ -80,7 +115,21 @@ size_t ZArray::GetRawDataSize() const return size; } +std::string ZArray::GetSourceTypeName() const +{ + return resList.at(0)->GetSourceTypeName(); +} + ZResourceType ZArray::GetResourceType() const { return ZResourceType::Array; } + +DeclarationAlignment ZArray::GetDeclarationAlignment() const +{ + if (resList.size() == 0) + { + return DeclarationAlignment::Align4; + } + return resList.at(0)->GetDeclarationAlignment(); +} diff --git a/tools/ZAPD/ZAPD/ZArray.h b/tools/ZAPD/ZAPD/ZArray.h index f43dc1242e..46a04d7329 100644 --- a/tools/ZAPD/ZAPD/ZArray.h +++ b/tools/ZAPD/ZAPD/ZArray.h @@ -14,11 +14,16 @@ public: void ParseXML(tinyxml2::XMLElement* reader) override; - std::string GetSourceOutputCode(const std::string& prefix) override; + Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override; + std::string GetBodySourceCode() const override; + size_t GetRawDataSize() const override; + std::string GetSourceTypeName() const override; ZResourceType GetResourceType() const override; + DeclarationAlignment GetDeclarationAlignment() const override; + protected: size_t arrayCnt; std::string childName; diff --git a/tools/ZAPD/ZAPD/ZBackground.cpp b/tools/ZAPD/ZAPD/ZBackground.cpp index 2bc4cbc9a5..4125f239f3 100644 --- a/tools/ZAPD/ZAPD/ZBackground.cpp +++ b/tools/ZAPD/ZAPD/ZBackground.cpp @@ -1,30 +1,22 @@ #include "ZBackground.h" -#include "BitConverter.h" -#include "File.h" + #include "Globals.h" -#include "Path.h" -#include "StringHelper.h" +#include "Utils/BitConverter.h" +#include "Utils/File.h" +#include "Utils/Path.h" +#include "Utils/StringHelper.h" #include "ZFile.h" REGISTER_ZFILENODE(Background, ZBackground); #define JPEG_MARKER 0xFFD8FFE0 #define MARKER_DQT 0xFFDB +#define MARKER_EOI 0xFFD9 ZBackground::ZBackground(ZFile* nParent) : ZResource(nParent) { } -ZBackground::ZBackground(const std::string& prefix, uint32_t nRawDataIndex, ZFile* nParent) - : ZResource(nParent) -{ - rawDataIndex = nRawDataIndex; - name = GetDefaultName(prefix.c_str(), rawDataIndex); - outName = name; - - ParseRawData(); -} - void ZBackground::ParseRawData() { ZResource::ParseRawData(); @@ -36,7 +28,7 @@ void ZBackground::ParseRawData() uint8_t val = rawData.at(rawDataIndex + i); data.push_back(val); - if (BitConverter::ToUInt16BE(rawData, rawDataIndex + i) == 0xFFD9) + if (BitConverter::ToUInt16BE(rawData, rawDataIndex + i) == MARKER_EOI) { data.push_back(rawData.at(rawDataIndex + i + 1)); break; @@ -60,12 +52,6 @@ void ZBackground::ParseBinaryFile(const std::string& inFolder, bool appendOutNam CheckValidJpeg(filepath.generic_string()); } -void ZBackground::ExtractFromXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex) -{ - ZResource::ExtractFromXML(reader, nRawDataIndex); - DeclareVar("", ""); -} - void ZBackground::CheckValidJpeg(const std::string& filepath) { std::string filename = outName; @@ -132,16 +118,28 @@ size_t ZBackground::GetRawDataSize() const return Globals::Instance->cfg.bgScreenHeight * Globals::Instance->cfg.bgScreenWidth * 2; } -void ZBackground::DeclareVar(const std::string& prefix, const std::string& bodyStr) const +Declaration* ZBackground::DeclareVar(const std::string& prefix, + [[maybe_unused]] const std::string& bodyStr) { std::string auxName = name; + std::string auxOutName = outName; - if (name == "") - auxName = GetDefaultName(prefix, rawDataIndex); + if (auxName == "") + auxName = GetDefaultName(prefix); - parent->AddDeclarationArray(rawDataIndex, DeclarationAlignment::Align8, GetRawDataSize(), - GetSourceTypeName(), auxName, "SCREEN_WIDTH * SCREEN_HEIGHT / 4", - bodyStr); + if (auxOutName == "") + auxOutName = GetDefaultName(prefix); + + auto filepath = Globals::Instance->outputPath / fs::path(auxOutName).stem(); + + std::string incStr = + StringHelper::Sprintf("%s.%s.inc.c", filepath.c_str(), GetExternalExtension().c_str()); + + Declaration* decl = parent->AddDeclarationIncludeArray(rawDataIndex, incStr, GetRawDataSize(), + GetSourceTypeName(), auxName, 0); + decl->arrayItemCntStr = "SCREEN_WIDTH * SCREEN_HEIGHT / 4"; + decl->staticConf = staticConf; + return decl; } bool ZBackground::IsExternalResource() const @@ -160,7 +158,7 @@ void ZBackground::Save(const fs::path& outFolder) File::WriteAllBytes(filepath.string(), data); } -std::string ZBackground::GetBodySourceCode() +std::string ZBackground::GetBodySourceCode() const { std::string bodyStr = " "; @@ -177,23 +175,9 @@ std::string ZBackground::GetBodySourceCode() return bodyStr; } -std::string ZBackground::GetSourceOutputCode(const std::string& prefix) +std::string ZBackground::GetDefaultName(const std::string& prefix) const { - std::string bodyStr = GetBodySourceCode(); - - Declaration* decl = parent->GetDeclaration(rawDataIndex); - - if (decl == nullptr) - DeclareVar(prefix, bodyStr); - else - decl->text = bodyStr; - - return ""; -} - -std::string ZBackground::GetDefaultName(const std::string& prefix, uint32_t address) -{ - return StringHelper::Sprintf("%sBackground_%06X", prefix.c_str(), address); + return StringHelper::Sprintf("%sBackground_%06X", prefix.c_str(), rawDataIndex); } std::string ZBackground::GetSourceTypeName() const @@ -205,3 +189,8 @@ ZResourceType ZBackground::GetResourceType() const { return ZResourceType::Background; } + +DeclarationAlignment ZBackground::GetDeclarationAlignment() const +{ + return DeclarationAlignment::Align8; +} diff --git a/tools/ZAPD/ZAPD/ZBackground.h b/tools/ZAPD/ZAPD/ZBackground.h index 292d8a4363..e3728bd984 100644 --- a/tools/ZAPD/ZAPD/ZBackground.h +++ b/tools/ZAPD/ZAPD/ZBackground.h @@ -11,25 +11,24 @@ protected: public: ZBackground(ZFile* nParent); - ZBackground(const std::string& prefix, uint32_t nRawDataIndex, ZFile* nParent); + + void ParseBinaryFile(const std::string& inFolder, bool appendOutName); void ParseRawData() override; - void ParseBinaryFile(const std::string& inFolder, bool appendOutName); - void ExtractFromXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex) override; - void CheckValidJpeg(const std::string& filepath); + Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override; + std::string GetBodySourceCode() const override; + std::string GetDefaultName(const std::string& prefix) const override; - size_t GetRawDataSize() const override; - - void DeclareVar(const std::string& prefix, const std::string& bodyStr) const; + void Save(const fs::path& outFolder) override; bool IsExternalResource() const override; - std::string GetExternalExtension() const override; - void Save(const fs::path& outFolder) override; - std::string GetBodySourceCode(); - std::string GetSourceOutputCode(const std::string& prefix) override; - static std::string GetDefaultName(const std::string& prefix, uint32_t address); - std::string GetSourceTypeName() const override; ZResourceType GetResourceType() const override; + std::string GetExternalExtension() const override; + + size_t GetRawDataSize() const override; + DeclarationAlignment GetDeclarationAlignment() const override; + + void CheckValidJpeg(const std::string& filepath); }; diff --git a/tools/ZAPD/ZAPD/ZBlob.cpp b/tools/ZAPD/ZAPD/ZBlob.cpp index 6964e4ea99..c1f0788206 100644 --- a/tools/ZAPD/ZAPD/ZBlob.cpp +++ b/tools/ZAPD/ZAPD/ZBlob.cpp @@ -1,11 +1,11 @@ #include "ZBlob.h" -#include "BitConverter.h" -#include "File.h" -#include "Path.h" -#include "StringHelper.h" -#include "ZFile.h" -using namespace tinyxml2; +#include "Globals.h" +#include "Utils/BitConverter.h" +#include "Utils/File.h" +#include "Utils/Path.h" +#include "Utils/StringHelper.h" +#include "ZFile.h" REGISTER_ZFILENODE(Blob, ZBlob); @@ -14,19 +14,6 @@ ZBlob::ZBlob(ZFile* nParent) : ZResource(nParent) RegisterRequiredAttribute("Size"); } -// Build Source File Mode -ZBlob* ZBlob::BuildFromXML(XMLElement* reader, const std::string& inFolder, bool readFile) -{ - ZBlob* blob = new ZBlob(nullptr); - - blob->ParseXML(reader); - - if (readFile) - blob->blobData = File::ReadAllBytes(inFolder + "/" + blob->name + ".bin"); - - return blob; -} - ZBlob* ZBlob::FromFile(const std::string& filePath) { ZBlob* blob = new ZBlob(nullptr); @@ -49,14 +36,38 @@ void ZBlob::ParseRawData() parent->GetRawData().begin() + rawDataIndex + blobSize); } -std::string ZBlob::GetSourceOutputCode(const std::string& prefix) +Declaration* ZBlob::DeclareVar(const std::string& prefix, + [[maybe_unused]] const std::string& bodyStr) { - sourceOutput = ""; + std::string auxName = name; + std::string auxOutName = outName; + + if (auxName == "") + auxName = GetDefaultName(prefix); + + if (auxOutName == "") + auxOutName = GetDefaultName(prefix); + + std::string path = Path::GetFileNameWithoutExtension(auxOutName); + + std::string assetOutDir = + (Globals::Instance->outputPath / Path::GetFileNameWithoutExtension(GetOutName())).string(); + + std::string incStr = + StringHelper::Sprintf("%s.%s.inc.c", assetOutDir.c_str(), GetExternalExtension().c_str()); + + return parent->AddDeclarationIncludeArray(rawDataIndex, incStr, GetRawDataSize(), + GetSourceTypeName(), auxName, blobData.size()); +} + +std::string ZBlob::GetBodySourceCode() const +{ + std::string sourceOutput; for (size_t i = 0; i < blobData.size(); i += 1) { if (i % 16 == 0) - sourceOutput += " "; + sourceOutput += "\t"; sourceOutput += StringHelper::Sprintf("0x%02X, ", blobData[i]); @@ -72,14 +83,14 @@ std::string ZBlob::GetSourceOutputCode(const std::string& prefix) return sourceOutput; } -std::string ZBlob::GetSourceOutputHeader(const std::string& prefix) +std::string ZBlob::GetSourceOutputHeader([[maybe_unused]] const std::string& prefix) { return StringHelper::Sprintf("extern u8 %s[];\n", name.c_str()); } void ZBlob::Save(const fs::path& outFolder) { - File::WriteAllBytes(outFolder / (name + ".bin"), blobData); + File::WriteAllBytes((outFolder / (name + ".bin")).string(), blobData); } bool ZBlob::IsExternalResource() const diff --git a/tools/ZAPD/ZAPD/ZBlob.h b/tools/ZAPD/ZAPD/ZBlob.h index 2f8d315729..86623b5119 100644 --- a/tools/ZAPD/ZAPD/ZBlob.h +++ b/tools/ZAPD/ZAPD/ZBlob.h @@ -8,13 +8,14 @@ class ZBlob : public ZResource public: ZBlob(ZFile* nParent); - static ZBlob* BuildFromXML(tinyxml2::XMLElement* reader, const std::string& inFolder, - bool readFile); static ZBlob* FromFile(const std::string& filePath); void ParseXML(tinyxml2::XMLElement* reader) override; void ParseRawData() override; - std::string GetSourceOutputCode(const std::string& prefix) override; + + Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override; + std::string GetBodySourceCode() const override; + std::string GetSourceOutputHeader(const std::string& prefix) override; void Save(const fs::path& outFolder) override; diff --git a/tools/ZAPD/ZAPD/ZCollision.cpp b/tools/ZAPD/ZAPD/ZCollision.cpp index 822b36584c..f9c0bf7d62 100644 --- a/tools/ZAPD/ZAPD/ZCollision.cpp +++ b/tools/ZAPD/ZAPD/ZCollision.cpp @@ -1,9 +1,11 @@ #include "ZCollision.h" -#include + +#include #include -#include "BitConverter.h" + #include "Globals.h" -#include "StringHelper.h" +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" REGISTER_ZFILENODE(Collision, ZCollisionHeader); @@ -13,9 +15,6 @@ ZCollisionHeader::ZCollisionHeader(ZFile* nParent) : ZResource(nParent) ZCollisionHeader::~ZCollisionHeader() { - for (WaterBoxHeader* waterBox : waterBoxes) - delete waterBox; - delete camData; } @@ -51,8 +50,16 @@ void ZCollisionHeader::ParseRawData() vertices.reserve(numVerts); polygons.reserve(numPolygons); + uint32_t currentPtr = vtxSegmentOffset; + for (uint16_t i = 0; i < numVerts; i++) - vertices.push_back(VertexEntry(rawData, vtxSegmentOffset + (i * 6))); + { + ZVector vec(parent); + vec.ExtractFromBinary(currentPtr, ZScalarType::ZSCALAR_S16, 3); + + currentPtr += vec.GetRawDataSize(); + vertices.push_back(vec); + } for (uint16_t i = 0; i < numPolygons; i++) polygons.push_back(PolygonEntry(rawData, polySegmentOffset + (i * 16))); @@ -74,34 +81,38 @@ void ZCollisionHeader::ParseRawData() polyTypeDefSegmentOffset, polygonTypes.size()); for (uint16_t i = 0; i < numWaterBoxes; i++) - waterBoxes.push_back(new WaterBoxHeader( + waterBoxes.push_back(WaterBoxHeader( rawData, waterBoxSegmentOffset + (i * (Globals::Instance->game == ZGame::OOT_SW97 ? 12 : 16)))); +} - std::string declaration = ""; +void ZCollisionHeader::DeclareReferences(const std::string& prefix) +{ + std::string declaration; + std::string auxName = name; + + if (name == "") + auxName = GetDefaultName(prefix); if (waterBoxes.size() > 0) { for (size_t i = 0; i < waterBoxes.size(); i++) { - declaration += StringHelper::Sprintf("\t{ %i, %i, %i, %i, %i, 0x%08X },", - waterBoxes[i]->xMin, waterBoxes[i]->ySurface, - waterBoxes[i]->zMin, waterBoxes[i]->xLength, - waterBoxes[i]->zLength, waterBoxes[i]->properties); + declaration += + StringHelper::Sprintf("\t{ %s },", waterBoxes[i].GetBodySourceCode().c_str()); if (i + 1 < waterBoxes.size()) declaration += "\n"; } - } - if (waterBoxAddress != 0) parent->AddDeclarationArray( - waterBoxSegmentOffset, DeclarationAlignment::None, 16 * waterBoxes.size(), "WaterBox", - StringHelper::Sprintf("%s_waterBoxes_%06X", name.c_str(), waterBoxSegmentOffset), 0, - declaration); + waterBoxSegmentOffset, DeclarationAlignment::Align4, 16 * waterBoxes.size(), "WaterBox", + StringHelper::Sprintf("%s_waterBoxes_%06X", auxName.c_str(), waterBoxSegmentOffset), + waterBoxes.size(), declaration); + } if (polygons.size() > 0) { - declaration = ""; + declaration.clear(); for (size_t i = 0; i < polygons.size(); i++) { @@ -113,17 +124,13 @@ void ZCollisionHeader::ParseRawData() declaration += "\n"; } - if (polyAddress != 0) - { - parent->AddDeclarationArray( - polySegmentOffset, DeclarationAlignment::None, polygons.size() * 16, - "CollisionPoly", - StringHelper::Sprintf("%s_polygons_%08X", name.c_str(), polySegmentOffset), 0, - declaration); - } + parent->AddDeclarationArray( + polySegmentOffset, DeclarationAlignment::Align4, polygons.size() * 16, "CollisionPoly", + StringHelper::Sprintf("%s_polygons_%08X", auxName.c_str(), polySegmentOffset), + polygons.size(), declaration); } - declaration = ""; + declaration.clear(); for (size_t i = 0; i < polygonTypes.size(); i++) { declaration += StringHelper::Sprintf("\t{ 0x%08lX, 0x%08lX },", polygonTypes[i] >> 32, @@ -135,58 +142,76 @@ void ZCollisionHeader::ParseRawData() if (polyTypeDefAddress != 0) parent->AddDeclarationArray( - polyTypeDefSegmentOffset, DeclarationAlignment::None, polygonTypes.size() * 8, + polyTypeDefSegmentOffset, DeclarationAlignment::Align4, polygonTypes.size() * 8, "SurfaceType", - StringHelper::Sprintf("%s_surfaceType_%08X", name.c_str(), polyTypeDefSegmentOffset), 0, - declaration); + StringHelper::Sprintf("%s_surfaceType_%08X", auxName.c_str(), polyTypeDefSegmentOffset), + polygonTypes.size(), declaration); - declaration = ""; + declaration.clear(); if (vertices.size() > 0) { - declaration = ""; + declaration.clear(); for (size_t i = 0; i < vertices.size(); i++) { - declaration += StringHelper::Sprintf("\t{ %6i, %6i, %6i },", vertices[i].x, - vertices[i].y, vertices[i].z); + declaration += + StringHelper::Sprintf("\t{ %s },", vertices[i].GetBodySourceCode().c_str()); if (i < vertices.size() - 1) declaration += "\n"; } + const auto& first = vertices.front(); if (vtxAddress != 0) parent->AddDeclarationArray( - vtxSegmentOffset, DeclarationAlignment::None, vertices.size() * 6, "Vec3s", - StringHelper::Sprintf("%s_vtx_%08X", name.c_str(), vtxSegmentOffset), 0, - declaration); - - declaration = ""; + vtxSegmentOffset, first.GetDeclarationAlignment(), + vertices.size() * first.GetRawDataSize(), first.GetSourceTypeName(), + StringHelper::Sprintf("%s_vtx_%08X", auxName.c_str(), vtxSegmentOffset), + vertices.size(), declaration); } +} - declaration = ""; - char waterBoxStr[2048]; - - if (waterBoxAddress != 0) - sprintf(waterBoxStr, "%s_waterBoxes_%06X", name.c_str(), waterBoxSegmentOffset); - else - sprintf(waterBoxStr, "NULL"); +std::string ZCollisionHeader::GetBodySourceCode() const +{ + std::string declaration; declaration += "\n"; - declaration += StringHelper::Sprintf(" { %i, %i, %i },\n { %i, %i, %i },\n", absMinX, - absMinY, absMinZ, absMaxX, absMaxY, absMaxZ); + declaration += StringHelper::Sprintf("\t{ %i, %i, %i },\n", absMinX, absMinY, absMinZ); + declaration += StringHelper::Sprintf("\t{ %i, %i, %i },\n", absMaxX, absMaxY, absMaxZ); - declaration += StringHelper::Sprintf( - " %i,\n %s_vtx_%08X,\n %i,\n %s_polygons_%08X,\n %s_surfaceType_%08X,\n " - "%s_camDataList_%08X,\n %i,\n %s\n", - numVerts, name.c_str(), vtxSegmentOffset, numPolygons, name.c_str(), polySegmentOffset, - name.c_str(), polyTypeDefSegmentOffset, name.c_str(), camDataSegmentOffset, numWaterBoxes, - waterBoxStr); + std::string vtxName; + Globals::Instance->GetSegmentedPtrName(vtxAddress, parent, "Vec3s", vtxName); + declaration += StringHelper::Sprintf("\t%i,\n\t%s,\n", numVerts, vtxName.c_str()); - parent->AddDeclaration(rawDataIndex, DeclarationAlignment::None, DeclarationPadding::Pad16, - GetRawDataSize(), "CollisionHeader", - StringHelper::Sprintf("%s", name.c_str(), rawDataIndex), declaration); + std::string polyName; + Globals::Instance->GetSegmentedPtrName(polyAddress, parent, "CollisionPoly", polyName); + declaration += StringHelper::Sprintf("\t%i,\n\t%s,\n", numPolygons, polyName.c_str()); + + std::string surfaceName; + Globals::Instance->GetSegmentedPtrName(polyTypeDefAddress, parent, "SurfaceType", surfaceName); + declaration += StringHelper::Sprintf("\t%s,\n", surfaceName.c_str()); + + std::string camName; + Globals::Instance->GetSegmentedPtrName(camDataAddress, parent, "CamData", camName); + declaration += StringHelper::Sprintf("\t%s,\n", camName.c_str()); + + std::string waterBoxName; + Globals::Instance->GetSegmentedPtrName(waterBoxAddress, parent, "WaterBox", waterBoxName); + declaration += StringHelper::Sprintf("\t%i,\n\t%s\n", numWaterBoxes, waterBoxName.c_str()); + + return declaration; +} + +std::string ZCollisionHeader::GetDefaultName(const std::string& prefix) const +{ + return StringHelper::Sprintf("%sCol_%06X", prefix.c_str(), rawDataIndex); +} + +std::string ZCollisionHeader::GetSourceTypeName() const +{ + return "CollisionHeader"; } ZResourceType ZCollisionHeader::GetResourceType() const @@ -213,15 +238,6 @@ PolygonEntry::PolygonEntry(const std::vector& rawData, uint32_t rawData d = BitConverter::ToUInt16BE(data, rawDataIndex + 14); } -VertexEntry::VertexEntry(const std::vector& rawData, uint32_t rawDataIndex) -{ - const uint8_t* data = rawData.data(); - - x = BitConverter::ToInt16BE(data, rawDataIndex + 0); - y = BitConverter::ToInt16BE(data, rawDataIndex + 2); - z = BitConverter::ToInt16BE(data, rawDataIndex + 4); -} - WaterBoxHeader::WaterBoxHeader(const std::vector& rawData, uint32_t rawDataIndex) { const uint8_t* data = rawData.data(); @@ -238,11 +254,18 @@ WaterBoxHeader::WaterBoxHeader(const std::vector& rawData, uint32_t raw properties = BitConverter::ToInt32BE(data, rawDataIndex + 12); } +std::string WaterBoxHeader::GetBodySourceCode() const +{ + return StringHelper::Sprintf("%i, %i, %i, %i, %i, 0x%08X", xMin, ySurface, zMin, xLength, + zLength, properties); +} + CameraDataList::CameraDataList(ZFile* parent, const std::string& prefix, const std::vector& rawData, uint32_t rawDataIndex, - uint32_t polyTypeDefSegmentOffset, uint32_t polygonTypesCnt) + uint32_t polyTypeDefSegmentOffset, + [[maybe_unused]] uint32_t polygonTypesCnt) { - std::string declaration = ""; + std::string declaration; // Parse CameraDataEntries int32_t numElements = (polyTypeDefSegmentOffset - rawDataIndex) / 8; @@ -257,7 +280,7 @@ CameraDataList::CameraDataList(ZFile* parent, const std::string& prefix, entry->cameraPosDataSeg = BitConverter::ToInt32BE(rawData, rawDataIndex + (entries.size() * 8) + 4); - if (entry->cameraPosDataSeg != 0 && GETSEGNUM(entry->cameraPosDataSeg) != 2) + if (entry->cameraPosDataSeg != 0 && GETSEGNUM(entry->cameraPosDataSeg) != SEGMENT_SCENE) { cameraPosDataSeg = rawDataIndex + (entries.size() * 8); break; @@ -294,7 +317,7 @@ CameraDataList::CameraDataList(ZFile* parent, const std::string& prefix, } parent->AddDeclarationArray( - rawDataIndex, DeclarationAlignment::None, entries.size() * 8, "CamData", + rawDataIndex, DeclarationAlignment::Align4, entries.size() * 8, "CamData", StringHelper::Sprintf("%s_camDataList_%08X", prefix.c_str(), rawDataIndex), entries.size(), declaration); @@ -302,7 +325,7 @@ CameraDataList::CameraDataList(ZFile* parent, const std::string& prefix, if (numDataTotal > 0) { - declaration = ""; + declaration.clear(); for (uint32_t i = 0; i < numDataTotal; i++) { CameraPositionData* data = @@ -317,12 +340,21 @@ CameraDataList::CameraDataList(ZFile* parent, const std::string& prefix, int32_t cameraPosDataIndex = GETSEGOFFSET(cameraPosDataSeg); uint32_t entrySize = numDataTotal * 0x6; parent->AddDeclarationArray( - cameraPosDataIndex, DeclarationAlignment::None, entrySize, "Vec3s", + cameraPosDataIndex, DeclarationAlignment::Align4, entrySize, "Vec3s", StringHelper::Sprintf("%s_camPosData_%08X", prefix.c_str(), cameraPosDataIndex), numDataTotal, declaration); } } +CameraDataList::~CameraDataList() +{ + for (auto entry : entries) + delete entry; + + for (auto camPosData : cameraPositionData) + delete camPosData; +} + CameraPositionData::CameraPositionData(const std::vector& rawData, uint32_t rawDataIndex) { x = BitConverter::ToInt16BE(rawData, rawDataIndex + 0); diff --git a/tools/ZAPD/ZAPD/ZCollision.h b/tools/ZAPD/ZAPD/ZCollision.h index 8b53f25035..0c6710e472 100644 --- a/tools/ZAPD/ZAPD/ZCollision.h +++ b/tools/ZAPD/ZAPD/ZCollision.h @@ -3,6 +3,7 @@ #include "ZFile.h" #include "ZResource.h" #include "ZRoom/ZRoom.h" +#include "ZVector.h" class PolygonEntry { @@ -14,17 +15,14 @@ public: PolygonEntry(const std::vector& rawData, uint32_t rawDataIndex); }; -class VertexEntry -{ -public: - int16_t x, y, z; - - VertexEntry(const std::vector& rawData, uint32_t rawDataIndex); -}; - class WaterBoxHeader { public: + WaterBoxHeader(const std::vector& rawData, uint32_t rawDataIndex); + + std::string GetBodySourceCode() const; + +protected: int16_t xMin; int16_t ySurface; int16_t zMin; @@ -32,8 +30,6 @@ public: int16_t zLength; int16_t pad; int32_t properties; - - WaterBoxHeader(const std::vector& rawData, uint32_t rawDataIndex); }; class CameraPositionData @@ -61,6 +57,7 @@ public: CameraDataList(ZFile* parent, const std::string& prefix, const std::vector& rawData, uint32_t rawDataIndex, uint32_t polyTypeDefSegmentOffset, uint32_t polygonTypesCnt); + ~CameraDataList(); }; class ZCollisionHeader : public ZResource @@ -81,17 +78,22 @@ public: uint32_t vtxSegmentOffset, polySegmentOffset, polyTypeDefSegmentOffset, camDataSegmentOffset, waterBoxSegmentOffset; - std::vector vertices; + std::vector vertices; std::vector polygons; std::vector polygonTypes; - std::vector waterBoxes; + std::vector waterBoxes; CameraDataList* camData; ZCollisionHeader(ZFile* nParent); ~ZCollisionHeader(); void ParseRawData() override; + void DeclareReferences(const std::string& prefix) override; + std::string GetBodySourceCode() const override; + std::string GetDefaultName(const std::string& prefix) const override; + + std::string GetSourceTypeName() const override; ZResourceType GetResourceType() const override; size_t GetRawDataSize() const override; diff --git a/tools/ZAPD/ZAPD/ZCutscene.cpp b/tools/ZAPD/ZAPD/ZCutscene.cpp index 2c0f7d3e33..237481079f 100644 --- a/tools/ZAPD/ZAPD/ZCutscene.cpp +++ b/tools/ZAPD/ZAPD/ZCutscene.cpp @@ -1,6 +1,7 @@ #include "ZCutscene.h" -#include "BitConverter.h" -#include "StringHelper.h" + +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" #include "ZResource.h" REGISTER_ZFILENODE(Cutscene, ZCutscene); @@ -84,10 +85,9 @@ CutsceneCommandSceneTransFX::~CutsceneCommandSceneTransFX() { } -std::string ZCutscene::GetBodySourceCode() +std::string ZCutscene::GetBodySourceCode() const { - std::string output = ""; - size_t size = 0; + std::string output; uint32_t curPtr = 0; output += StringHelper::Sprintf(" CS_BEGIN_CUTSCENE(%i, %i),\n", commands.size(), endFrame); @@ -97,7 +97,6 @@ std::string ZCutscene::GetBodySourceCode() CutsceneCommand* cmd = commands[i]; output += " " + cmd->GenerateSourceCode(curPtr); curPtr += cmd->GetCommandSize(); - size += cmd->GetCommandSize(); } output += StringHelper::Sprintf(" CS_END(),\n", commands.size(), endFrame); @@ -105,32 +104,6 @@ std::string ZCutscene::GetBodySourceCode() return output; } -std::string ZCutscene::GetSourceOutputCode(const std::string& prefix) -{ - std::string bodyStr = GetBodySourceCode(); - - Declaration* decl = parent->GetDeclaration(rawDataIndex); - - if (decl == nullptr) - DeclareVar(prefix, bodyStr); - else - decl->text = bodyStr; - - return ""; -} - -void ZCutscene::DeclareVar(const std::string& prefix, const std::string& bodyStr) const -{ - std::string auxName = name; - - if (auxName == "") - auxName = StringHelper::Sprintf("%sCutsceneData0x%06X", prefix.c_str(), rawDataIndex); - - parent->AddDeclarationArray(getSegmentOffset(), DeclarationAlignment::Align4, - DeclarationPadding::Pad16, GetRawDataSize(), "s32", auxName, 0, - bodyStr); -} - size_t ZCutscene::GetRawDataSize() const { size_t size = 0; @@ -151,12 +124,6 @@ size_t ZCutscene::GetRawDataSize() const return size; } -void ZCutscene::ExtractFromXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex) -{ - ZResource::ExtractFromXML(reader, nRawDataIndex); - DeclareVar(parent->GetName(), ""); -} - void ZCutscene::ParseRawData() { ZResource::ParseRawData(); @@ -447,7 +414,8 @@ ZResourceType ZCutscene::GetResourceType() const return ZResourceType::Cutscene; } -CutsceneCommand::CutsceneCommand(const std::vector& rawData, uint32_t rawDataIndex) +CutsceneCommand::CutsceneCommand([[maybe_unused]] const std::vector& rawData, + [[maybe_unused]] uint32_t rawDataIndex) { } @@ -478,7 +446,7 @@ CutsceneCameraPoint::CutsceneCameraPoint(const std::vector& rawData, ui continueFlag = data[rawDataIndex + 0]; cameraRoll = data[rawDataIndex + 1]; nextPointFrame = BitConverter::ToInt16BE(data, rawDataIndex + 2); - viewAngle = BitConverter::ToInt32BE(data, rawDataIndex + 4); + viewAngle = BitConverter::ToFloatBE(data, rawDataIndex + 4); posX = BitConverter::ToInt16BE(data, rawDataIndex + 8); posY = BitConverter::ToInt16BE(data, rawDataIndex + 10); @@ -522,12 +490,12 @@ std::string CutsceneCommandSetCameraPos::GetCName() return ""; } -std::string CutsceneCommandSetCameraPos::GenerateSourceCode(uint32_t baseAddress) +std::string CutsceneCommandSetCameraPos::GenerateSourceCode([[maybe_unused]] uint32_t baseAddress) { - std::string result = ""; + std::string result; - std::string listStr = ""; - std::string posStr = ""; + std::string listStr; + std::string posStr; if (commandID == (int32_t)CutsceneCommands::SetCameraFocus) { @@ -554,11 +522,14 @@ std::string CutsceneCommandSetCameraPos::GenerateSourceCode(uint32_t baseAddress for (size_t i = 0; i < entries.size(); i++) { - result += StringHelper::Sprintf(" %s(%i, %i, %i, 0x%06X, %i, %i, %i, %i),\n", - posStr.c_str(), entries[i]->continueFlag, + std::string continueMacro = "CS_CMD_CONTINUE"; + if (entries[i]->continueFlag != 0) + continueMacro = "CS_CMD_STOP"; + result += StringHelper::Sprintf(" %s(%s, 0x%02X, %i, %ff, %i, %i, %i, 0x%04X),\n", + posStr.c_str(), continueMacro.c_str(), entries[i]->cameraRoll, entries[i]->nextPointFrame, - *(uint32_t*)&entries[i]->viewAngle, entries[i]->posX, - entries[i]->posY, entries[i]->posZ, entries[i]->unused); + entries[i]->viewAngle, entries[i]->posX, entries[i]->posY, + entries[i]->posZ, entries[i]->unused); } return result; @@ -610,9 +581,9 @@ std::string CutsceneCommandFadeBGM::GetCName() return "CsCmdMusicFade"; } -std::string CutsceneCommandFadeBGM::GenerateSourceCode(uint32_t baseAddress) +std::string CutsceneCommandFadeBGM::GenerateSourceCode([[maybe_unused]] uint32_t baseAddress) { - std::string result = ""; + std::string result; result += StringHelper::Sprintf("CS_FADE_BGM_LIST(%i),\n", entries.size()); @@ -663,9 +634,9 @@ CutsceneCommandPlayBGM::CutsceneCommandPlayBGM(const std::vector& rawDa } } -std::string CutsceneCommandPlayBGM::GenerateSourceCode(uint32_t baseAddress) +std::string CutsceneCommandPlayBGM::GenerateSourceCode([[maybe_unused]] uint32_t baseAddress) { - std::string result = ""; + std::string result; result += StringHelper::Sprintf("CS_PLAY_BGM_LIST(%i),\n", entries.size()); @@ -706,9 +677,9 @@ CutsceneCommandStopBGM::CutsceneCommandStopBGM(const std::vector& rawDa } } -std::string CutsceneCommandStopBGM::GenerateSourceCode(uint32_t baseAddress) +std::string CutsceneCommandStopBGM::GenerateSourceCode([[maybe_unused]] uint32_t baseAddress) { - std::string result = ""; + std::string result; result += StringHelper::Sprintf("CS_STOP_BGM_LIST(%i),\n", entries.size()); @@ -764,9 +735,9 @@ CutsceneCommandEnvLighting::CutsceneCommandEnvLighting(const std::vector& raw } } -std::string CutsceneCommandUnknown9::GenerateSourceCode(uint32_t baseAddress) +std::string CutsceneCommandUnknown9::GenerateSourceCode([[maybe_unused]] uint32_t baseAddress) { - std::string result = ""; + std::string result; result += StringHelper::Sprintf("CS_CMD_09_LIST(%i),\n", entries.size()); @@ -878,9 +849,9 @@ CutsceneCommandUnknown::CutsceneCommandUnknown(const std::vector& rawDa } } -std::string CutsceneCommandUnknown::GenerateSourceCode(uint32_t baseAddress) +std::string CutsceneCommandUnknown::GenerateSourceCode([[maybe_unused]] uint32_t baseAddress) { - std::string result = ""; + std::string result; result += StringHelper::Sprintf("CS_UNK_DATA_LIST(0x%02X, %i),\n", commandID, entries.size()); @@ -936,9 +907,9 @@ std::string CutsceneCommandDayTime::GetCName() return "CsCmdDayTime"; } -std::string CutsceneCommandDayTime::GenerateSourceCode(uint32_t baseAddress) +std::string CutsceneCommandDayTime::GenerateSourceCode([[maybe_unused]] uint32_t baseAddress) { - std::string result = ""; + std::string result; result += StringHelper::Sprintf("CS_TIME_LIST(%i),\n", entries.size()); @@ -987,9 +958,9 @@ std::string CutsceneCommandTextbox::GetCName() return "CsCmdTextbox"; } -std::string CutsceneCommandTextbox::GenerateSourceCode(uint32_t baseAddress) +std::string CutsceneCommandTextbox::GenerateSourceCode([[maybe_unused]] uint32_t baseAddress) { - std::string result = ""; + std::string result; result += StringHelper::Sprintf("CS_TEXT_LIST(%i),\n", entries.size()); @@ -1033,9 +1004,9 @@ ActorAction::ActorAction(const std::vector& rawData, uint32_t rawDataIn endPosX = BitConverter::ToInt32BE(data, rawDataIndex + 24); endPosY = BitConverter::ToInt32BE(data, rawDataIndex + 28); endPosZ = BitConverter::ToInt32BE(data, rawDataIndex + 32); - normalX = BitConverter::ToInt32BE(data, rawDataIndex + 36); - normalY = BitConverter::ToInt32BE(data, rawDataIndex + 40); - normalZ = BitConverter::ToInt32BE(data, rawDataIndex + 44); + normalX = BitConverter::ToFloatBE(data, rawDataIndex + 36); + normalY = BitConverter::ToFloatBE(data, rawDataIndex + 40); + normalZ = BitConverter::ToFloatBE(data, rawDataIndex + 44); } CutsceneCommandActorAction::CutsceneCommandActorAction(const std::vector& rawData, @@ -1053,10 +1024,10 @@ CutsceneCommandActorAction::CutsceneCommandActorAction(const std::vectoraction, entries[i]->startFrame, entries[i]->endFrame, entries[i]->rotX, - entries[i]->rotY, entries[i]->rotZ, entries[i]->startPosX, entries[i]->startPosY, - entries[i]->startPosZ, entries[i]->endPosX, entries[i]->endPosY, entries[i]->endPosZ, - *(int32_t*)&entries[i]->normalX, *(int32_t*)&entries[i]->normalY, - *(int32_t*)&entries[i]->normalZ); + "\t\t%s(0x%04X, %i, %i, 0x%04X, 0x%04X, 0x%04X, %i, %i, %i, %i, %i, %i, %.11ef, " + "%.11ef, %.11ef),\n", + subCommand.c_str(), entries[i]->action, entries[i]->startFrame, entries[i]->endFrame, + entries[i]->rotX, entries[i]->rotY, entries[i]->rotZ, entries[i]->startPosX, + entries[i]->startPosY, entries[i]->startPosZ, entries[i]->endPosX, entries[i]->endPosY, + entries[i]->endPosZ, entries[i]->normalX, entries[i]->normalY, entries[i]->normalZ); } return result; @@ -1111,9 +1081,9 @@ std::string CutsceneCommandTerminator::GetCName() return "CsCmdBase"; } -std::string CutsceneCommandTerminator::GenerateSourceCode(uint32_t baseAddress) +std::string CutsceneCommandTerminator::GenerateSourceCode([[maybe_unused]] uint32_t baseAddress) { - std::string result = ""; + std::string result; result += StringHelper::Sprintf("CS_TERMINATOR(0x%04X, %i, %i),\n", base, startFrame, endFrame); @@ -1133,9 +1103,9 @@ CutsceneCommandEnd::CutsceneCommandEnd(const std::vector& rawData, uint endFrame = (uint16_t)BitConverter::ToInt16BE(rawData, rawDataIndex + 4); } -std::string CutsceneCommandEnd::GenerateSourceCode(uint32_t baseAddress) +std::string CutsceneCommandEnd::GenerateSourceCode([[maybe_unused]] uint32_t baseAddress) { - std::string result = ""; + std::string result; result += StringHelper::Sprintf("CS_END(),\n"); @@ -1187,9 +1157,9 @@ CutsceneCommandSpecialAction::CutsceneCommandSpecialAction(const std::vectorAddDeclarationArray(rawDataIndex, GetDeclarationAlignment(), GetRawDataSize(), + GetSourceTypeName(), auxName, 0, bodyStr); + decl->staticConf = staticConf; + return decl; +} + +std::string ZCutsceneBase::GetSourceTypeName() const +{ + return "CutsceneData"; +} diff --git a/tools/ZAPD/ZAPD/ZCutscene.h b/tools/ZAPD/ZAPD/ZCutscene.h index 2167379589..cbb6a78b02 100644 --- a/tools/ZAPD/ZAPD/ZCutscene.h +++ b/tools/ZAPD/ZAPD/ZCutscene.h @@ -49,7 +49,7 @@ public: int8_t continueFlag; int8_t cameraRoll; int16_t nextPointFrame; - uint32_t viewAngle; + float viewAngle; int16_t posX, posY, posZ; int16_t unused; @@ -352,7 +352,7 @@ public: int16_t rotX, rotY, rotZ; int32_t startPosX, startPosY, startPosZ; int32_t endPosX, endPosY, endPosZ; - int32_t normalX, normalY, normalZ; + float normalX, normalY, normalZ; ActorAction(const std::vector& rawData, uint32_t rawDataIndex); }; @@ -412,9 +412,10 @@ class ZCutsceneBase : public ZResource { public: ZCutsceneBase(ZFile* nParent); - virtual std::string GetBodySourceCode() = 0; - virtual void DeclareVar(const std::string& prefix, const std::string& bodyStr) const = 0; - virtual uint32_t getSegmentOffset() const = 0; + + Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override; + + std::string GetSourceTypeName() const override; }; class ZCutscene : public ZCutsceneBase @@ -425,18 +426,14 @@ public: void ParseRawData() override; - std::string GetBodySourceCode() override; - void DeclareVar(const std::string& prefix, const std::string& bodyStr) const override; - std::string GetSourceOutputCode(const std::string& prefix) override; + std::string GetBodySourceCode() const override; + size_t GetRawDataSize() const override; - CutsceneCommands GetCommandFromID(int32_t id); - uint32_t getSegmentOffset() const override { return rawDataIndex; } ZResourceType GetResourceType() const override; - void ExtractFromXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex) override; + CutsceneCommands GetCommandFromID(int32_t id); -protected: int32_t numCommands; int32_t endFrame; std::vector commands; diff --git a/tools/ZAPD/ZAPD/ZCutsceneMM.cpp b/tools/ZAPD/ZAPD/ZCutsceneMM.cpp index ed663da81b..d0208bc070 100644 --- a/tools/ZAPD/ZAPD/ZCutsceneMM.cpp +++ b/tools/ZAPD/ZAPD/ZCutsceneMM.cpp @@ -1,6 +1,7 @@ #include "ZCutsceneMM.h" -#include "BitConverter.h" -#include "StringHelper.h" + +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" ZCutsceneMM::ZCutsceneMM(ZFile* nParent) : ZCutsceneBase(nParent) { @@ -12,9 +13,9 @@ ZCutsceneMM::~ZCutsceneMM() delete cmd; } -std::string ZCutsceneMM::GetBodySourceCode() +std::string ZCutsceneMM::GetBodySourceCode() const { - std::string output = ""; + std::string output; output += StringHelper::Sprintf(" CS_BEGIN_CUTSCENE(%i, %i),", numCommands, endFrame); @@ -22,51 +23,19 @@ std::string ZCutsceneMM::GetBodySourceCode() { if ((i % 4) == 0) output += "\n "; - output += StringHelper::Sprintf("0x%08X,", data[i]); + output += StringHelper::Sprintf("0x%08X, ", data[i]); } return output; } -std::string ZCutsceneMM::GetSourceOutputCode(const std::string& prefix) -{ - std::string bodyStr = GetBodySourceCode(); - - Declaration* decl = parent->GetDeclaration(rawDataIndex); - - if (decl == nullptr) - DeclareVar(prefix, bodyStr); - else - decl->text = bodyStr; - - return ""; -} - -void ZCutsceneMM::DeclareVar(const std::string& prefix, const std::string& bodyStr) const -{ - std::string auxName = name; - - if (auxName == "") - auxName = StringHelper::Sprintf("%sCutsceneData0x%06X", prefix.c_str(), rawDataIndex); - - parent->AddDeclarationArray(getSegmentOffset(), DeclarationAlignment::Align4, GetRawDataSize(), - "s32", auxName, 0, bodyStr); -} - size_t ZCutsceneMM::GetRawDataSize() const { return 8 + data.size() * 4; } -void ZCutsceneMM::ExtractFromXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex) -{ - ZResource::ExtractFromXML(reader, nRawDataIndex); - DeclareVar(parent->GetName(), ""); -} - void ZCutsceneMM::ParseRawData() { - segmentOffset = rawDataIndex; const auto& rawData = parent->GetRawData(); numCommands = BitConverter::ToInt32BE(rawData, rawDataIndex + 0); diff --git a/tools/ZAPD/ZAPD/ZCutsceneMM.h b/tools/ZAPD/ZAPD/ZCutsceneMM.h index 5cda5a1eeb..41b7de37f3 100644 --- a/tools/ZAPD/ZAPD/ZCutsceneMM.h +++ b/tools/ZAPD/ZAPD/ZCutsceneMM.h @@ -10,22 +10,16 @@ class ZCutsceneMM : public ZCutsceneBase { public: - uint32_t segmentOffset; - ZCutsceneMM(ZFile* nParent); virtual ~ZCutsceneMM(); - std::string GetBodySourceCode() override; - void DeclareVar(const std::string& prefix, const std::string& bodyStr) const override; - std::string GetSourceOutputCode(const std::string& prefix) override; + std::string GetBodySourceCode() const override; + size_t GetRawDataSize() const override; - uint32_t getSegmentOffset() const override { return segmentOffset; } void ParseRawData() override; ZResourceType GetResourceType() const override; - void ExtractFromXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex) override; - protected: int32_t numCommands; int32_t endFrame; diff --git a/tools/ZAPD/ZAPD/ZDisplayList.cpp b/tools/ZAPD/ZAPD/ZDisplayList.cpp index 9d9cca3fe9..f7be34a22d 100644 --- a/tools/ZAPD/ZAPD/ZDisplayList.cpp +++ b/tools/ZAPD/ZAPD/ZDisplayList.cpp @@ -1,26 +1,22 @@ #include "ZDisplayList.h" -#include -#include #include #include #include -#include -#include "BitConverter.h" -#include "Globals.h" -#include "HighLevel/HLModelIntermediette.h" -#include "OutputFormatter.h" -#include "StringHelper.h" -#include "gfxd.h" +#include -using namespace tinyxml2; +#include "Globals.h" +#include "OutputFormatter.h" +#include "Utils/BitConverter.h" +#include "Utils/File.h" +#include "Utils/Path.h" +#include "Utils/StringHelper.h" +#include "gfxd.h" REGISTER_ZFILENODE(DList, ZDisplayList); ZDisplayList::ZDisplayList(ZFile* nParent) : ZResource(nParent) { - defines = ""; - sceneSegName = ""; lastTexWidth = 0; lastTexHeight = 0; lastTexAddr = 0; @@ -30,7 +26,6 @@ ZDisplayList::ZDisplayList(ZFile* nParent) : ZResource(nParent) lastTexLoaded = false; lastTexIsPalette = false; name = ""; - scene = nullptr; dListType = Globals::Instance->game == ZGame::OOT_SW97 ? DListType::F3DEX : DListType::F3DZEX; } @@ -48,21 +43,30 @@ void ZDisplayList::ExtractFromXML(tinyxml2::XMLElement* reader, uint32_t nRawDat rawDataIndex = nRawDataIndex; ParseXML(reader); - int32_t rawDataSize = ZDisplayList::GetDListLength( - parent->GetRawData(), rawDataIndex, - Globals::Instance->game == ZGame::OOT_SW97 ? DListType::F3DEX : DListType::F3DZEX); - numInstructions = rawDataSize / 8; - ParseRawData(); + // Don't parse raw data of external files + if (parent->GetMode() != ZFileMode::ExternalFile) + { + int32_t rawDataSize = ZDisplayList::GetDListLength( + parent->GetRawData(), rawDataIndex, + Globals::Instance->game == ZGame::OOT_SW97 ? DListType::F3DEX : DListType::F3DZEX); + numInstructions = rawDataSize / 8; + ParseRawData(); + } - DeclareVar("", ""); + Declaration* decl = DeclareVar("", ""); + decl->declaredInXml = true; } -ZDisplayList::ZDisplayList(uint32_t nRawDataIndex, int32_t rawDataSize, ZFile* nParent) - : ZDisplayList(nParent) +void ZDisplayList::ExtractFromBinary(uint32_t nRawDataIndex, int32_t rawDataSize) { rawDataIndex = nRawDataIndex; - name = StringHelper::Sprintf("DL_%06X", rawDataIndex); + name = GetDefaultName(parent->GetName()); numInstructions = rawDataSize / 8; + + // Don't parse raw data of external files + if (parent->GetMode() == ZFileMode::ExternalFile) + return; + ParseRawData(); } @@ -79,14 +83,24 @@ void ZDisplayList::ParseRawData() } } -Declaration* ZDisplayList::DeclareVar(const std::string& prefix, const std::string& bodyStr) +Declaration* ZDisplayList::DeclareVar([[maybe_unused]] const std::string& prefix, + const std::string& bodyStr) { - return parent->AddDeclarationArray(rawDataIndex, DeclarationAlignment::Align8, GetRawDataSize(), - GetSourceTypeName(), name, 0, bodyStr, true); + Declaration* decl = + parent->AddDeclarationArray(rawDataIndex, GetDeclarationAlignment(), GetRawDataSize(), + GetSourceTypeName(), name, numInstructions, bodyStr); + decl->isExternal = true; + decl->staticConf = staticConf; + return decl; } -void ZDisplayList::ParseF3DZEX(F3DZEXOpcode opcode, uint64_t data, int32_t i, std::string prefix, - char* line) +std::string ZDisplayList::GetDefaultName(const std::string& prefix) const +{ + return StringHelper::Sprintf("%sDL_%06X", prefix.c_str(), rawDataIndex); +} + +void ZDisplayList::ParseF3DZEX(F3DZEXOpcode opcode, uint64_t data, int32_t i, + const std::string& prefix, char* line) { switch (opcode) { @@ -258,10 +272,10 @@ void ZDisplayList::ParseF3DZEX(F3DZEXOpcode opcode, uint64_t data, int32_t i, st sprintf(line, "gsSPBranchLessZraw(%sDlist0x%06X, 0x%02X, 0x%02X),", prefix.c_str(), h & 0x00FFFFFF, (a / 5) | (b / 2), z); - ZDisplayList* nList = new ZDisplayList( - h & 0x00FFFFFF, GetDListLength(parent->GetRawData(), h & 0x00FFFFFF, dListType), - parent); - nList->scene = scene; + ZDisplayList* nList = new ZDisplayList(parent); + nList->ExtractFromBinary( + h & 0x00FFFFFF, GetDListLength(parent->GetRawData(), h & 0x00FFFFFF, dListType)); + nList->SetName(nList->GetDefaultName(prefix)); otherDLists.push_back(nList); i++; @@ -277,7 +291,8 @@ void ZDisplayList::ParseF3DZEX(F3DZEXOpcode opcode, uint64_t data, int32_t i, st } } -void ZDisplayList::ParseF3DEX(F3DEXOpcode opcode, uint64_t data, std::string prefix, char* line) +void ZDisplayList::ParseF3DEX(F3DEXOpcode opcode, uint64_t data, const std::string& prefix, + char* line) { switch (opcode) { @@ -411,31 +426,40 @@ int32_t ZDisplayList::GetDListLength(const std::vector& rawData, uint32 DListType dListType) { uint8_t endDLOpcode; + uint8_t branchListOpcode; if (dListType == DListType::F3DZEX) - endDLOpcode = (uint8_t)F3DZEXOpcode::G_ENDDL; + { + endDLOpcode = static_cast(F3DZEXOpcode::G_ENDDL); + branchListOpcode = static_cast(F3DZEXOpcode::G_DL); + } else - endDLOpcode = (uint8_t)F3DEXOpcode::G_ENDDL; + { + endDLOpcode = static_cast(F3DEXOpcode::G_ENDDL); + branchListOpcode = static_cast(F3DEXOpcode::G_DL); + } uint32_t ptr = rawDataIndex; size_t rawDataSize = rawData.size(); while (true) { - if (ptr > rawDataSize) + if (ptr >= rawDataSize) { - throw std::runtime_error( - StringHelper::Sprintf("%s: Fatal error.\n" - "\t End of file found when trying to find the end of the " - "DisplayList at offset: '0x%X'.\n", - __PRETTY_FUNCTION__, rawDataIndex)); - throw std::runtime_error(""); + throw std::runtime_error(StringHelper::Sprintf( + "%s: Fatal error.\n" + "\t End of file found when trying to find the end of the " + "DisplayList at offset: '0x%X'.\n", + "Raw data size: 0x%zX.\n", __PRETTY_FUNCTION__, rawDataIndex, rawDataSize)); } uint8_t opcode = rawData.at(ptr); + bool dlNoPush = rawData.at(ptr + 1) == 1; ptr += 8; - if (opcode == endDLOpcode) + if (opcode == endDLOpcode || (opcode == branchListOpcode && dlNoPush)) + { return ptr - rawDataIndex; + } } } @@ -461,7 +485,7 @@ bool ZDisplayList::SequenceCheck(std::vector sequence, int32_t sta } int32_t ZDisplayList::OptimizationChecks(int32_t startIndex, std::string& output, - std::string prefix) + const std::string& prefix) { int32_t result = -1; @@ -474,13 +498,8 @@ int32_t ZDisplayList::OptimizationChecks(int32_t startIndex, std::string& output } int32_t ZDisplayList::OptimizationCheck_LoadTextureBlock(int32_t startIndex, std::string& output, - std::string prefix) + [[maybe_unused]] const std::string& prefix) { - if (scene == nullptr) - { - return -1; - } - std::vector sequence = {F3DZEXOpcode::G_SETTIMG, F3DZEXOpcode::G_SETTILE, F3DZEXOpcode::G_RDPLOADSYNC, F3DZEXOpcode::G_LOADBLOCK, F3DZEXOpcode::G_RDPPIPESYNC, F3DZEXOpcode::G_SETTILE, @@ -498,7 +517,7 @@ int32_t ZDisplayList::OptimizationCheck_LoadTextureBlock(int32_t startIndex, std uint32_t texAddr, tmem, rtile, fmt, siz, sizB, width, height, width2, height2, pal, cms, cmt, masks, maskt, shifts, shiftt; - std::string texStr = ""; + std::string texStr; // gsDPSetTextureImage { @@ -514,17 +533,7 @@ int32_t ZDisplayList::OptimizationCheck_LoadTextureBlock(int32_t startIndex, std lastTexSeg = segmentNumber; - ZFile* auxParent = parent; - if (parent->segment != segmentNumber && Globals::Instance->HasSegment(segmentNumber)) - auxParent = Globals::Instance->segmentRefFiles.at(segmentNumber); - - Declaration* decl = auxParent->GetDeclaration(texAddr); - if (Globals::Instance->HasSegment(segmentNumber) && decl != nullptr) - texStr = decl->varName; - else if (lastTexture != nullptr) - texStr = lastTexture->GetName(); - else - texStr = auxParent->GetDeclarationPtrName(data & 0xFFFFFFFF); + Globals::Instance->GetSegmentedPtrName(data & 0xFFFFFFFF, parent, "", texStr); } // gsDPSetTile @@ -593,12 +602,12 @@ int32_t ZDisplayList::OptimizationCheck_LoadTextureBlock(int32_t startIndex, std height2 = (vvv >> 2) + 1; } - std::string fmtTbl[] = {"G_IM_FMT_RGBA", "G_IM_FMT_YUV", "G_IM_FMT_CI", "G_IM_FMT_IA", + const char* fmtTbl[] = {"G_IM_FMT_RGBA", "G_IM_FMT_YUV", "G_IM_FMT_CI", "G_IM_FMT_IA", "G_IM_FMT_I"}; - std::string sizTbl[] = {"G_IM_SIZ_4b", "G_IM_SIZ_8b", "G_IM_SIZ_16b", "G_IM_SIZ_32b"}; + const char* sizTbl[] = {"G_IM_SIZ_4b", "G_IM_SIZ_8b", "G_IM_SIZ_16b", "G_IM_SIZ_32b"}; // output += StringHelper::Sprintf("gsDPLoadTextureBlock(%s, %s, %s, %i, %i, %i, %i, %i, %i, - // %i, %i, %i),", texStr.c_str(), fmtTbl[fmt].c_str(), sizTbl[siz].c_str(), width, height, + // %i, %i, %i),", texStr.c_str(), fmtTbl[fmt], sizTbl[siz].c_str(), width, height, // pal, cms, cmt, masks, maskt, shifts, shiftt); if (siz == 2 && sizB == 0) @@ -606,26 +615,26 @@ int32_t ZDisplayList::OptimizationCheck_LoadTextureBlock(int32_t startIndex, std if (tmem != 0) output += StringHelper::Sprintf( "gsDPLoadMultiBlock_4b(%s, %i, %i, %s, %i, %i, %i, %i, %i, %i, %i, %i, %i),", - texStr.c_str(), tmem, rtile, fmtTbl[fmt].c_str(), width2, height2, pal, cms, - cmt, masks, maskt, shifts, shiftt); + texStr.c_str(), tmem, rtile, fmtTbl[fmt], width2, height2, pal, cms, cmt, masks, + maskt, shifts, shiftt); else output += StringHelper::Sprintf( "gsDPLoadTextureBlock_4b(%s, %s, %i, %i, %i, %i, %i, %i, %i, %i, %i),", - texStr.c_str(), fmtTbl[fmt].c_str(), width2, height2, pal, cms, cmt, masks, - maskt, shifts, shiftt); + texStr.c_str(), fmtTbl[fmt], width2, height2, pal, cms, cmt, masks, maskt, + shifts, shiftt); } else if (siz == 2 && sizB != 0) { if (tmem != 0) output += StringHelper::Sprintf( "gsDPLoadMultiBlock(%s, %i, %i, %s, %s, %i, %i, %i, %i, %i, %i, %i, %i, %i),", - texStr.c_str(), tmem, rtile, fmtTbl[fmt].c_str(), sizTbl[sizB].c_str(), width2, - height2, pal, cms, cmt, masks, maskt, shifts, shiftt); + texStr.c_str(), tmem, rtile, fmtTbl[fmt], sizTbl[sizB], width2, height2, pal, + cms, cmt, masks, maskt, shifts, shiftt); else output += StringHelper::Sprintf( "gsDPLoadTextureBlock(%s, %s, %s, %i, %i, %i, %i, %i, %i, %i, %i, %i),", - texStr.c_str(), fmtTbl[fmt].c_str(), sizTbl[sizB].c_str(), width2, height2, pal, - cms, cmt, masks, maskt, shifts, shiftt); + texStr.c_str(), fmtTbl[fmt], sizTbl[sizB], width2, height2, pal, cms, cmt, + masks, maskt, shifts, shiftt); } else { @@ -638,15 +647,15 @@ int32_t ZDisplayList::OptimizationCheck_LoadTextureBlock(int32_t startIndex, std lastTexSiz = (F3DZEXTexSizes)siz; lastTexLoaded = true; - TextureGenCheck(prefix); + TextureGenCheck(); return -1; } output += StringHelper::Sprintf( "gsDPLoadMultiBlock(%s, %i, %i, %s, %s, %i, %i, %i, %i, %i, %i, %i, %i, %i),", - texStr.c_str(), tmem, rtile, fmtTbl[fmt].c_str(), sizTbl[siz].c_str(), width, - height, pal, cms, cmt, masks, maskt, shifts, shiftt); + texStr.c_str(), tmem, rtile, fmtTbl[fmt], sizTbl[siz], width, height, pal, cms, cmt, + masks, maskt, shifts, shiftt); } lastTexAddr = texAddr; @@ -656,7 +665,7 @@ int32_t ZDisplayList::OptimizationCheck_LoadTextureBlock(int32_t startIndex, std lastTexSiz = (F3DZEXTexSizes)siz; lastTexLoaded = true; - TextureGenCheck(prefix); + TextureGenCheck(); return (int32_t)sequence.size(); } @@ -664,7 +673,7 @@ int32_t ZDisplayList::OptimizationCheck_LoadTextureBlock(int32_t startIndex, std return -1; } -void ZDisplayList::Opcode_G_DL(uint64_t data, std::string prefix, char* line) +void ZDisplayList::Opcode_G_DL(uint64_t data, const std::string& prefix, char* line) { int32_t pp = (data & 0x00FF000000000000) >> 56; int32_t segNum = GETSEGNUM(data); @@ -704,20 +713,12 @@ void ZDisplayList::Opcode_G_DL(uint64_t data, std::string prefix, char* line) } else { - ZDisplayList* nList = new ZDisplayList( - GETSEGOFFSET(data), GetDListLength(parent->GetRawData(), GETSEGOFFSET(data), dListType), - parent); + ZDisplayList* nList = new ZDisplayList(parent); + nList->ExtractFromBinary(GETSEGOFFSET(data), GetDListLength(parent->GetRawData(), + GETSEGOFFSET(data), dListType)); + nList->SetName(nList->GetDefaultName(prefix)); - // if (scene != nullptr) - { - nList->scene = scene; - otherDLists.push_back(nList); - } - // else - //{ - // nList->SetName(StringHelper::Sprintf("%sDlist0x%06lX", prefix.c_str(), - // SEG2FILESPACE(data))); nList->GetSourceOutputCode(prefix); - //} + otherDLists.push_back(nList); } } @@ -780,10 +781,10 @@ void ZDisplayList::Opcode_G_MTX(uint64_t data, char* line) else pp = (data & 0x000000FF00000000) >> 32; - std::string matrixRef = ""; + std::string matrixRef; - if (Globals::Instance->symbolMap.find(mm) != Globals::Instance->symbolMap.end()) - matrixRef = StringHelper::Sprintf("&%s", Globals::Instance->symbolMap[mm].c_str()); + if (Globals::Instance->cfg.symbolMap.find(mm) != Globals::Instance->cfg.symbolMap.end()) + matrixRef = StringHelper::Sprintf("&%s", Globals::Instance->cfg.symbolMap[mm].c_str()); else matrixRef = StringHelper::Sprintf("0x%08X", mm); @@ -832,29 +833,28 @@ void ZDisplayList::Opcode_G_VTX(uint64_t data, char* line) StringHelper::Sprintf("0x%08X", segmented), ""); return; } - references.push_back(vtxAddr); + references.push_back(data); { uint32_t currentPtr = Seg2Filespace(data, parent->baseAddress); + Declaration* decl; // Check for vertex intersections from other display lists // TODO: These two could probably be condenced to one... - if (parent->GetDeclarationRanged(vtxAddr + (nn * 16)) != nullptr) + decl = parent->GetDeclarationRanged(vtxAddr + (nn * 16)); + if (decl != nullptr) { - // Declaration* decl = parent->GetDeclarationRanged(vtxAddr + (nn * 16)); - uint32_t addr = parent->GetDeclarationRangedAddress(vtxAddr + (nn * 16)); - int32_t diff = addr - vtxAddr; + int32_t diff = decl->address - vtxAddr; if (diff > 0) nn = diff / 16; else nn = 0; } - if (parent->GetDeclarationRanged(vtxAddr) != nullptr) + decl = parent->GetDeclarationRanged(vtxAddr); + if (decl != nullptr) { - // Declaration* decl = parent->GetDeclarationRanged(vtxAddr); - uint32_t addr = parent->GetDeclarationRangedAddress(vtxAddr); - int32_t diff = addr - vtxAddr; + int32_t diff = decl->address - vtxAddr; if (diff > 0) nn = diff / 16; else @@ -869,8 +869,7 @@ void ZDisplayList::Opcode_G_VTX(uint64_t data, char* line) for (int32_t i = 0; i < nn; i++) { ZVtx vtx(parent); - vtx.SetRawDataIndex(currentPtr); - vtx.ParseRawData(); + vtx.ExtractFromFile(currentPtr); vtxList.push_back(vtx); currentPtr += 16; @@ -899,13 +898,13 @@ void ZDisplayList::Opcode_G_TEXTURE(uint64_t data, char* line) nnnnnnn == 1 ? "G_ON" : "G_OFF"); } -void ZDisplayList::Opcode_G_SETTIMG(uint64_t data, std::string prefix, char* line) +void ZDisplayList::Opcode_G_SETTIMG(uint64_t data, const std::string& prefix, char* line) { int32_t __ = (data & 0x00FF000000000000) >> 48; int32_t www = (data & 0x00000FFF00000000) >> 32; - std::string fmtTbl[] = {"G_IM_FMT_RGBA", "G_IM_FMT_YUV", "G_IM_FMT_CI", "G_IM_FMT_IA", + const char* fmtTbl[] = {"G_IM_FMT_RGBA", "G_IM_FMT_YUV", "G_IM_FMT_CI", "G_IM_FMT_IA", "G_IM_FMT_I"}; - std::string sizTbl[] = {"G_IM_SIZ_4b", "G_IM_SIZ_8b", "G_IM_SIZ_16b", "G_IM_SIZ_32b"}; + const char* sizTbl[] = {"G_IM_SIZ_4b", "G_IM_SIZ_8b", "G_IM_SIZ_16b", "G_IM_SIZ_32b"}; uint32_t fmt = (__ & 0xE0) >> 5; uint32_t siz = (__ & 0x18) >> 3; @@ -913,7 +912,7 @@ void ZDisplayList::Opcode_G_SETTIMG(uint64_t data, std::string prefix, char* lin if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_DEBUG) printf("TextureGenCheck G_SETTIMG\n"); - TextureGenCheck(prefix); // HOTSPOT + TextureGenCheck(); // HOTSPOT lastTexFmt = (F3DZEXTexFormats)fmt; lastTexSiz = (F3DZEXTexSizes)siz; @@ -945,13 +944,15 @@ void ZDisplayList::Opcode_G_SETTIMG(uint64_t data, std::string prefix, char* lin sprintf(texStr, "0x%08lX", data & 0xFFFFFFFF); } - sprintf(line, "gsDPSetTextureImage(%s, %s, %i, %s),", fmtTbl[fmt].c_str(), - sizTbl[siz].c_str(), www + 1, texStr); + sprintf(line, "gsDPSetTextureImage(%s, %s, %i, %s),", fmtTbl[fmt], sizTbl[siz], www + 1, + texStr); } else { - sprintf(line, "gsDPSetTextureImage(%s, %s, %i, %sTex_%06lX),", fmtTbl[fmt].c_str(), - sizTbl[siz].c_str(), www + 1, scene->GetName().c_str(), GETSEGOFFSET(data)); + std::string texName; + Globals::Instance->GetSegmentedPtrName(data, parent, "", texName); + sprintf(line, "gsDPSetTextureImage(%s, %s, %i, %s),", fmtTbl[fmt], sizTbl[siz], www + 1, + texName.c_str()); } } @@ -975,21 +976,21 @@ void ZDisplayList::Opcode_G_SETTILE(uint64_t data, char* line) int32_t bbbb = (data & 0b0000000000000000000000000000000000000000000000000000000011110000) >> 4; int32_t uuuu = (data & 0b0000000000000000000000000000000000000000000000000000000000001111); - std::string fmtTbl[] = {"G_IM_FMT_RGBA", "G_IM_FMT_YUV", "G_IM_FMT_CI", "G_IM_FMT_IA", + const char* fmtTbl[] = {"G_IM_FMT_RGBA", "G_IM_FMT_YUV", "G_IM_FMT_CI", "G_IM_FMT_IA", "G_IM_FMT_I"}; - std::string sizTbl[] = {"G_IM_SIZ_4b", "G_IM_SIZ_8b", "G_IM_SIZ_16b", "G_IM_SIZ_32b"}; + const char* sizTbl[] = {"G_IM_SIZ_4b", "G_IM_SIZ_8b", "G_IM_SIZ_16b", "G_IM_SIZ_32b"}; if (fff == (int32_t)F3DZEXTexFormats::G_IM_FMT_CI) lastCISiz = (F3DZEXTexSizes)ii; lastTexSizTest = (F3DZEXTexSizes)ii; - sprintf(line, "gsDPSetTile(%s, %s, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i),", - fmtTbl[fff].c_str(), sizTbl[ii].c_str(), nnnnnnnnn, mmmmmmmmm, ttt, pppp, cc, aaaa, - ssss, dd, bbbb, uuuu); + sprintf(line, "gsDPSetTile(%s, %s, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i),", fmtTbl[fff], + sizTbl[ii], nnnnnnnnn, mmmmmmmmm, ttt, pppp, cc, aaaa, ssss, dd, bbbb, uuuu); } -void ZDisplayList::Opcode_G_SETTILESIZE(uint64_t data, std::string prefix, char* line) +void ZDisplayList::Opcode_G_SETTILESIZE(uint64_t data, [[maybe_unused]] const std::string& prefix, + char* line) { int32_t sss = (data & 0x00FFF00000000000) >> 44; int32_t ttt = (data & 0x00000FFF00000000) >> 32; @@ -1023,7 +1024,7 @@ void ZDisplayList::Opcode_G_SETTILESIZE(uint64_t data, std::string prefix, char* if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_DEBUG) printf("TextureGenCheck G_SETTILESIZE\n"); - TextureGenCheck(prefix); + TextureGenCheck(); sprintf(line, "gsDPSetTileSize(%i, %i, %i, %i, %i),", i, sss, ttt, uuu, vvv); } @@ -1060,13 +1061,13 @@ void ZDisplayList::Opcode_G_SETCOMBINE(uint64_t data, char* line) int32_t ab1 = (data & 0b00000000000000000000000000000000000000000000000000000000111000) >> 3; int32_t ad1 = (data & 0b00000000000000000000000000000000000000000000000000000000000111) >> 0; - std::string modesA[] = {"COMBINED", "TEXEL0", "TEXEL1", "PRIMITIVE", "SHADE", "ENVIRONMENT", + const char* modesA[] = {"COMBINED", "TEXEL0", "TEXEL1", "PRIMITIVE", "SHADE", "ENVIRONMENT", "1", "NOISE", "0", "9", "10", "11", "12", "13", "14", "0"}; - std::string modesB[] = {"COMBINED", "TEXEL0", "TEXEL1", "PRIMITIVE", "SHADE", "ENVIRONMENT", + const char* modesB[] = {"COMBINED", "TEXEL0", "TEXEL1", "PRIMITIVE", "SHADE", "ENVIRONMENT", "CENTER", "K4", "8", "9", "10", "11", "12", "13", "14", "0"}; - std::string modesC[] = {"COMBINED", + const char* modesC[] = {"COMBINED", "TEXEL0", "TEXEL1", "PRIMITIVE", @@ -1098,21 +1099,20 @@ void ZDisplayList::Opcode_G_SETCOMBINE(uint64_t data, char* line) "29", "30", "0"}; - std::string modesD[] = {"COMBINED", "TEXEL0", "TEXEL1", "PRIMITIVE", + const char* modesD[] = {"COMBINED", "TEXEL0", "TEXEL1", "PRIMITIVE", "SHADE", "ENVIRONMENT", "1", "0"}; - std::string modes2[] = {"COMBINED", "TEXEL0", "TEXEL1", "PRIMITIVE", + const char* modes2[] = {"COMBINED", "TEXEL0", "TEXEL1", "PRIMITIVE", "SHADE", "ENVIRONMENT", "1", "0"}; - std::string modes2C[] = {"LOD_FRACTION", "TEXEL0", "TEXEL1", "PRIMITIVE", + const char* modes2C[] = {"LOD_FRACTION", "TEXEL0", "TEXEL1", "PRIMITIVE", "SHADE", "ENVIRONMENT", "PRIM_LOD_FRAC", "0"}; sprintf(line, "gsDPSetCombineLERP(%s, %s, %s, %s, %s, %s, %s, %s,\n %s, %s, " "%s, %s, %s, %s, %s, %s),", - modesA[a0].c_str(), modesB[b0].c_str(), modesC[c0].c_str(), modesD[d0].c_str(), - modes2[aa0].c_str(), modes2[ab0].c_str(), modes2C[ac0].c_str(), modes2[ad0].c_str(), - modesA[a1].c_str(), modesB[b1].c_str(), modesC[c1].c_str(), modesD[d1].c_str(), - modes2[aa1].c_str(), modes2[ab1].c_str(), modes2C[ac1].c_str(), modes2[ad1].c_str()); + modesA[a0], modesB[b0], modesC[c0], modesD[d0], modes2[aa0], modes2[ab0], modes2C[ac0], + modes2[ad0], modesA[a1], modesB[b1], modesC[c1], modesD[d1], modes2[aa1], modes2[ab1], + modes2C[ac1], modes2[ad1]); } void ZDisplayList::Opcode_G_SETPRIMCOLOR(uint64_t data, char* line) @@ -1257,7 +1257,7 @@ void ZDisplayList::Opcode_G_SETOTHERMODE_L(uint64_t data, char* line) G_RM_VISCVG2, G_RM_OPA_CI2}; - std::map str = { + std::map str = { {G_RM_FOG_SHADE_A, "G_RM_FOG_SHADE_A"}, {G_RM_FOG_PRIM_A, "G_RM_FOG_PRIM_A"}, {G_RM_PASS, "G_RM_PASS"}, @@ -1383,60 +1383,49 @@ void ZDisplayList::Opcode_G_SETOTHERMODE_L(uint64_t data, char* line) if (mode2Str == "") { - int32_t remainingFlags = mode2; - if (mode2 & AA_EN) { mode2Str += "AA_EN | "; - remainingFlags ^= AA_EN; } if (mode2 & Z_CMP) { mode2Str += "Z_CMP | "; - remainingFlags ^= Z_CMP; } if (mode2 & Z_UPD) { mode2Str += "Z_UPD | "; - remainingFlags ^= Z_UPD; } if (mode2 & IM_RD) { mode2Str += "IM_RD | "; - remainingFlags ^= IM_RD; } if (mode2 & CLR_ON_CVG) { mode2Str += "CLR_ON_CVG | "; - remainingFlags ^= CLR_ON_CVG; } if (mode2 & CVG_DST_CLAMP) { mode2Str += "CVG_DST_CLAMP | "; - remainingFlags ^= CVG_DST_CLAMP; } if (mode2 & CVG_DST_WRAP) { mode2Str += "CVG_DST_WRAP | "; - remainingFlags ^= CVG_DST_WRAP; } if (mode2 & CVG_DST_FULL) { mode2Str += "CVG_DST_FULL | "; - remainingFlags ^= CVG_DST_FULL; } if (mode2 & CVG_DST_SAVE) { mode2Str += "CVG_DST_SAVE | "; - remainingFlags ^= CVG_DST_SAVE; } int32_t zMode = mode2 & 0xC00; @@ -1444,35 +1433,29 @@ void ZDisplayList::Opcode_G_SETOTHERMODE_L(uint64_t data, char* line) if (zMode == ZMODE_INTER) { mode2Str += "ZMODE_INTER | "; - remainingFlags ^= ZMODE_INTER; } else if (zMode == ZMODE_XLU) { mode2Str += "ZMODE_XLU | "; - remainingFlags ^= ZMODE_XLU; } else if (zMode == ZMODE_DEC) { mode2Str += "ZMODE_DEC | "; - remainingFlags ^= ZMODE_DEC; } if (mode2 & CVG_X_ALPHA) { mode2Str += "CVG_X_ALPHA | "; - remainingFlags ^= CVG_X_ALPHA; } if (mode2 & ALPHA_CVG_SEL) { mode2Str += "ALPHA_CVG_SEL | "; - remainingFlags ^= ALPHA_CVG_SEL; } if (mode2 & FORCE_BL) { mode2Str += "FORCE_BL | "; - remainingFlags ^= FORCE_BL; } int32_t bp = (mode2 >> 28) & 0b11; @@ -1502,14 +1485,15 @@ void ZDisplayList::Opcode_G_SETOTHERMODE_H(uint64_t data, char* line) if (sft == 14) // G_MDSFT_TEXTLUT { - std::string types[] = {"G_TT_NONE", "G_TT_NONE", "G_TT_RGBA16", "G_TT_IA16"}; - sprintf(line, "gsDPSetTextureLUT(%s),", types[dd >> 14].c_str()); + const char* types[] = {"G_TT_NONE", "G_TT_NONE", "G_TT_RGBA16", "G_TT_IA16"}; + sprintf(line, "gsDPSetTextureLUT(%s),", types[dd >> 14]); } else sprintf(line, "gsSPSetOtherMode(0xE3, %i, %i, 0x%08X),", sft, nn + 1, dd); } -void ZDisplayList::Opcode_G_LOADTLUT(uint64_t data, std::string prefix, char* line) +void ZDisplayList::Opcode_G_LOADTLUT(uint64_t data, [[maybe_unused]] const std::string& prefix, + char* line) { int32_t t = (data & 0x0000000007000000) >> 24; int32_t ccc = (data & 0x00000000003FF000) >> 14; @@ -1523,27 +1507,27 @@ void ZDisplayList::Opcode_G_LOADTLUT(uint64_t data, std::string prefix, char* li if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_DEBUG) printf("TextureGenCheck G_LOADTLUT (lastCISiz: %i)\n", (uint32_t)lastCISiz); - TextureGenCheck(prefix); + TextureGenCheck(); sprintf(line, "gsDPLoadTLUTCmd(%i, %i),", t, ccc); } -void ZDisplayList::Opcode_G_ENDDL(std::string prefix, char* line) +void ZDisplayList::Opcode_G_ENDDL([[maybe_unused]] const std::string& prefix, char* line) { sprintf(line, "gsSPEndDisplayList(),"); if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_DEBUG) printf("TextureGenCheck G_ENDDL\n"); - TextureGenCheck(prefix); + TextureGenCheck(); } -std::string ZDisplayList::GetSourceOutputHeader(const std::string& prefix) +std::string ZDisplayList::GetSourceOutputHeader([[maybe_unused]] const std::string& prefix) { return ""; } -static int32_t GfxdCallback_FormatSingleEntry(void) +static int32_t GfxdCallback_FormatSingleEntry() { ZDisplayList* self = static_cast(gfxd_udata_get()); gfxd_puts("\t"); @@ -1580,9 +1564,15 @@ static int32_t GfxdCallback_FormatSingleEntry(void) } // dont print a new line after the last command - if (macroId != gfxd_SPEndDisplayList) + switch (macroId) { + case gfxd_SPEndDisplayList: + case gfxd_SPBranchList: + break; + + default: gfxd_puts("\n"); + break; } return 0; @@ -1592,24 +1582,17 @@ static int32_t GfxdCallback_Vtx(uint32_t seg, int32_t count) { ZDisplayList* self = static_cast(gfxd_udata_get()); uint32_t vtxOffset = Seg2Filespace(seg, self->parent->baseAddress); - std::string vtxName = ""; - // Probably an external asset we are unable to track - if (!Globals::Instance->HasSegment(GETSEGNUM(seg))) + if (GETSEGNUM(seg) == self->parent->segment) { - vtxName = StringHelper::Sprintf("0x%08X", seg); - } - else - { - self->references.push_back(vtxOffset); + Declaration* decl; // Check for vertex intersections from other display lists // TODO: These two could probably be condenced to one... - if (self->parent->GetDeclarationRanged(vtxOffset + (count * 16)) != nullptr) + decl = self->parent->GetDeclarationRanged(vtxOffset + (count * 16)); + if (decl != nullptr) { - // Declaration* decl = self->parent->GetDeclarationRanged(vtxOffset + (count * 16)); - uint32_t addr = self->parent->GetDeclarationRangedAddress(vtxOffset + (count * 16)); - int32_t diff = addr - vtxOffset; + int32_t diff = decl->address - vtxOffset; if (diff > 0) count = diff / 16; @@ -1617,11 +1600,10 @@ static int32_t GfxdCallback_Vtx(uint32_t seg, int32_t count) count = 0; } - if (self->parent->GetDeclarationRanged(vtxOffset) != nullptr) + decl = self->parent->GetDeclarationRanged(vtxOffset); + if (decl != nullptr) { - // Declaration* decl = self->parent->GetDeclarationRanged(vtxOffset); - uint32_t addr = self->parent->GetDeclarationRangedAddress(vtxOffset); - int32_t diff = addr - vtxOffset; + int32_t diff = decl->address - vtxOffset; if (diff > 0) count = diff / 16; @@ -1638,29 +1620,26 @@ static int32_t GfxdCallback_Vtx(uint32_t seg, int32_t count) for (int32_t i = 0; i < count; i++) { ZVtx vtx(self->parent); - vtx.SetRawDataIndex(currentPtr); - vtx.ParseRawData(); + vtx.ExtractFromFile(currentPtr); vtxList.push_back(vtx); currentPtr += 16; } self->vertices[vtxOffset] = vtxList; } - - vtxName = "@r"; } - gfxd_puts(vtxName.c_str()); + self->references.push_back(seg); + gfxd_puts("@r"); return 1; } static int32_t GfxdCallback_Texture(segptr_t seg, int32_t fmt, int32_t siz, int32_t width, - int32_t height, int32_t pal) + int32_t height, [[maybe_unused]] int32_t pal) { ZDisplayList* self = static_cast(gfxd_udata_get()); uint32_t texOffset = Seg2Filespace(seg, self->parent->baseAddress); - uint32_t texSegNum = GETSEGNUM(seg); self->lastTexWidth = width; self->lastTexHeight = height; @@ -1671,32 +1650,20 @@ static int32_t GfxdCallback_Texture(segptr_t seg, int32_t fmt, int32_t siz, int3 self->lastTexLoaded = true; self->lastTexIsPalette = false; - self->TextureGenCheck(self->curPrefix); + self->TextureGenCheck(); - std::string texName = ""; - - ZFile* auxParent = self->parent; - if (self->parent->segment != texSegNum && Globals::Instance->HasSegment(texSegNum)) - auxParent = Globals::Instance->segmentRefFiles.at(texSegNum); - - Declaration* decl = auxParent->GetDeclaration(texOffset); - if (Globals::Instance->HasSegment(texSegNum) && decl != nullptr) - texName = decl->varName; - else if (self->lastTexture != nullptr) - texName = self->lastTexture->GetName(); - else - texName = auxParent->GetDeclarationPtrName(seg); + std::string texName; + Globals::Instance->GetSegmentedPtrName(seg, self->parent, "", texName); gfxd_puts(texName.c_str()); return 1; } -static int32_t GfxdCallback_Palette(uint32_t seg, int32_t idx, int32_t count) +static int32_t GfxdCallback_Palette(uint32_t seg, [[maybe_unused]] int32_t idx, int32_t count) { ZDisplayList* self = static_cast(gfxd_udata_get()); uint32_t palOffset = Seg2Filespace(seg, self->parent->baseAddress); - uint32_t palSegNum = GETSEGNUM(seg); self->lastTexWidth = sqrt(count); self->lastTexHeight = sqrt(count); @@ -1707,21 +1674,10 @@ static int32_t GfxdCallback_Palette(uint32_t seg, int32_t idx, int32_t count) self->lastTexLoaded = true; self->lastTexIsPalette = true; - self->TextureGenCheck(self->curPrefix); + self->TextureGenCheck(); - std::string palName = ""; - - ZFile* auxParent = self->parent; - if (self->parent->segment != palSegNum && Globals::Instance->HasSegment(palSegNum)) - auxParent = Globals::Instance->segmentRefFiles.at(palSegNum); - - Declaration* decl = auxParent->GetDeclaration(palOffset); - if (Globals::Instance->HasSegment(palSegNum) && decl != nullptr) - palName = decl->varName; - else if (self->lastTlut != nullptr) - palName = self->lastTlut->GetName(); - else - palName = auxParent->GetDeclarationPtrName(seg); + std::string palName; + Globals::Instance->GetSegmentedPtrName(seg, self->parent, "", palName); gfxd_puts(palName.c_str()); @@ -1734,23 +1690,20 @@ static int32_t GfxdCallback_DisplayList(uint32_t seg) uint32_t dListOffset = GETSEGOFFSET(seg); uint32_t dListSegNum = GETSEGNUM(seg); - if ((dListSegNum <= 6) && Globals::Instance->HasSegment(dListSegNum)) + std::string dListName = ""; + bool addressFound = Globals::Instance->GetSegmentedPtrName(seg, self->parent, "Gfx", dListName); + + if (!addressFound && self->parent->segment == dListSegNum) { - ZDisplayList* newDList = new ZDisplayList( + ZDisplayList* newDList = new ZDisplayList(self->parent); + newDList->ExtractFromBinary( dListOffset, - self->GetDListLength(self->parent->GetRawData(), dListOffset, self->dListType), - self->parent); - newDList->scene = self->scene; - newDList->parent = self->parent; + self->GetDListLength(self->parent->GetRawData(), dListOffset, self->dListType)); + newDList->SetName(newDList->GetDefaultName(self->parent->GetName())); self->otherDLists.push_back(newDList); + dListName = newDList->GetName(); } - ZFile* auxParent = self->parent; - if (self->parent->segment != dListSegNum && Globals::Instance->HasSegment(dListSegNum)) - auxParent = Globals::Instance->segmentRefFiles.at(dListSegNum); - - std::string dListName = auxParent->GetDeclarationPtrName(seg); - gfxd_puts(dListName.c_str()); return 1; @@ -1758,30 +1711,26 @@ static int32_t GfxdCallback_DisplayList(uint32_t seg) static int32_t GfxdCallback_Matrix(uint32_t seg) { - std::string mtxName = ""; + std::string mtxName; ZDisplayList* self = static_cast(gfxd_udata_get()); - if (Globals::Instance->symbolMap.find(seg) != Globals::Instance->symbolMap.end()) - mtxName = StringHelper::Sprintf("&%s", Globals::Instance->symbolMap[seg].c_str()); - else if (Globals::Instance->HasSegment(GETSEGNUM(seg))) + bool addressFound = Globals::Instance->GetSegmentedPtrName(seg, self->parent, "Mtx", mtxName); + if (!addressFound && GETSEGNUM(seg) == self->parent->segment) { Declaration* decl = self->parent->GetDeclaration(Seg2Filespace(seg, self->parent->baseAddress)); if (decl == nullptr) { - ZMtx mtx(self->GetName(), Seg2Filespace(seg, self->parent->baseAddress), self->parent); + ZMtx mtx(self->parent); + mtx.SetName(mtx.GetDefaultName(self->GetName())); + mtx.ExtractFromFile(Seg2Filespace(seg, self->parent->baseAddress)); + mtx.DeclareVar(self->GetName(), ""); mtx.GetSourceOutputCode(self->GetName()); self->mtxList.push_back(mtx); mtxName = "&" + mtx.GetName(); } - else - { - mtxName = "&" + decl->varName; - } } - else - mtxName = StringHelper::Sprintf("0x%08X", seg); gfxd_puts(mtxName.c_str()); @@ -1790,7 +1739,7 @@ static int32_t GfxdCallback_Matrix(uint32_t seg) std::string ZDisplayList::GetSourceOutputCode(const std::string& prefix) { - std::string sourceOutput = ""; + std::string sourceOutput; if (Globals::Instance->useLegacyZDList) sourceOutput += ProcessLegacy(prefix); @@ -1823,49 +1772,29 @@ std::string ZDisplayList::GetSourceOutputCode(const std::string& prefix) } } - if (scene == nullptr) // TODO: Bit of a hack but it works for now... - parent->defines += defines; - // Generate Vertex Declarations for (auto& item : vertices) { - std::string declaration = ""; + std::string declaration; - uint32_t curAddr = item.first; + offset_t curAddr = item.first; + auto& firstVtx = item.second.at(0); for (auto vtx : item.second) { - if (curAddr != item.first) - declaration += "\n"; - - declaration += vtx.GetBodySourceCode(); - - curAddr += 16; + declaration += StringHelper::Sprintf("\t%s,\n", vtx.GetBodySourceCode().c_str()); } - vtxDeclarations[item.first] = declaration; - - if (parent != nullptr) - { - parent->AddDeclarationArray(item.first, DeclarationAlignment::None, - item.second.size() * 16, "static Vtx", - StringHelper::Sprintf("%sVtx_%06X", prefix.c_str(), - item.first, item.second.size()), - item.second.size(), declaration); - } + Declaration* decl = parent->AddDeclarationArray( + curAddr, firstVtx.GetDeclarationAlignment(), + item.second.size() * firstVtx.GetRawDataSize(), firstVtx.GetSourceTypeName(), + firstVtx.GetDefaultName(name), item.second.size(), declaration); + decl->isExternal = true; } } - if (scene != nullptr) - defines += scene->extDefines; - - if (parent != nullptr) - { - Declaration* decl = DeclareVar("", sourceOutput); - decl->references = references; - // return ""; - // return sourceOutput; - } + Declaration* decl = DeclareVar("", sourceOutput); + decl->references = references; // Iterate through our vertex lists, connect intersecting lists. if (vertices.size() > 0) @@ -1894,9 +1823,6 @@ std::string ZDisplayList::GetSourceOutputCode(const std::string& prefix) } } - if (scene == nullptr) // TODO: Bit of a hack but it works for now... - parent->defines += defines; - // Generate Vertex Declarations std::vector vtxKeys; @@ -1908,18 +1834,13 @@ std::string ZDisplayList::GetSourceOutputCode(const std::string& prefix) { auto& item = vertices[vtxKeys[i]]; - std::string declaration = ""; + std::string declaration; int32_t curAddr = vtxKeys[i]; for (auto& vtx : item) { - if (curAddr != vtxKeys[i]) - declaration += "\n"; - - declaration += - StringHelper::Sprintf(" VTX(%i, %i, %i, %i, %i, %i, %i, %i, %i),", vtx.x, - vtx.y, vtx.z, vtx.s, vtx.t, vtx.r, vtx.g, vtx.b, vtx.a); + declaration += StringHelper::Sprintf("\t%s,\n", vtx.GetBodySourceCode().c_str()); curAddr += 16; } @@ -1929,22 +1850,21 @@ std::string ZDisplayList::GetSourceOutputCode(const std::string& prefix) // that warning when building the OoT repo. declaration += "\n"; - vtxDeclarations[vtxKeys[i]] = declaration; - if (parent != nullptr) { - std::string vtxName = - StringHelper::Sprintf("%sVtx_%06X", prefix.c_str(), vtxKeys[i]); + std::string vtxName; + ZResource* vtxRes = parent->FindResource(vtxKeys[i]); + + if (vtxRes != nullptr) + vtxName = vtxRes->GetName(); + else + vtxName = StringHelper::Sprintf("%sVtx_%06X", prefix.c_str(), vtxKeys[i]); auto filepath = Globals::Instance->outputPath / vtxName; std::string incStr = StringHelper::Sprintf("%s.%s.inc", filepath.c_str(), "vtx"); - parent->AddDeclarationArray(vtxKeys[i], DeclarationAlignment::None, - item.size() * 16, "static Vtx", vtxName, item.size(), - declaration); - Declaration* vtxDecl = parent->AddDeclarationIncludeArray( - vtxKeys[i], incStr, item.size() * 16, "static Vtx", vtxName, item.size()); + vtxKeys[i], incStr, item.size() * 16, "Vtx", vtxName, item.size()); vtxDecl->isExternal = true; } } @@ -1959,7 +1879,7 @@ std::string ZDisplayList::GetSourceOutputCode(const std::string& prefix) std::string ZDisplayList::ProcessLegacy(const std::string& prefix) { char line[4096]; - std::string sourceOutput = ""; + std::string sourceOutput; for (size_t i = 0; i < instructions.size(); i++) { @@ -1999,9 +1919,9 @@ std::string ZDisplayList::ProcessLegacy(const std::string& prefix) return sourceOutput; } -std::string ZDisplayList::ProcessGfxDis(const std::string& prefix) +std::string ZDisplayList::ProcessGfxDis([[maybe_unused]] const std::string& prefix) { - std::string sourceOutput = ""; + std::string sourceOutput; OutputFormatter outputformatter; int32_t dListSize = instructions.size() * sizeof(instructions[0]); @@ -2026,7 +1946,6 @@ std::string ZDisplayList::ProcessGfxDis(const std::string& prefix) else gfxd_target(gfxd_f3dex); - this->curPrefix = prefix; gfxd_udata_set(this); gfxd_execute(); // generate display list sourceOutput += outputformatter.GetOutput(); // write formatted display list @@ -2034,10 +1953,10 @@ std::string ZDisplayList::ProcessGfxDis(const std::string& prefix) return sourceOutput; } -void ZDisplayList::TextureGenCheck(std::string prefix) +void ZDisplayList::TextureGenCheck() { - if (TextureGenCheck(scene, parent, prefix, lastTexWidth, lastTexHeight, lastTexAddr, lastTexSeg, - lastTexFmt, lastTexSiz, lastTexLoaded, lastTexIsPalette, this)) + if (TextureGenCheck(lastTexWidth, lastTexHeight, lastTexAddr, lastTexSeg, lastTexFmt, + lastTexSiz, lastTexLoaded, lastTexIsPalette, this)) { lastTexAddr = 0; lastTexLoaded = false; @@ -2045,12 +1964,11 @@ void ZDisplayList::TextureGenCheck(std::string prefix) } } -bool ZDisplayList::TextureGenCheck(ZRoom* scene, ZFile* parent, std::string prefix, - int32_t texWidth, int32_t texHeight, uint32_t texAddr, +bool ZDisplayList::TextureGenCheck(int32_t texWidth, int32_t texHeight, uint32_t texAddr, uint32_t texSeg, F3DZEXTexFormats texFmt, F3DZEXTexSizes texSiz, bool texLoaded, bool texIsPalette, ZDisplayList* self) { - int32_t segmentNumber = GETSEGNUM(texSeg); + uint32_t segmentNumber = GETSEGNUM(texSeg); if (!texIsPalette) self->lastTexture = nullptr; @@ -2064,58 +1982,53 @@ bool ZDisplayList::TextureGenCheck(ZRoom* scene, ZFile* parent, std::string pref if ((texSeg != 0 || texAddr != 0) && texWidth > 0 && texHeight > 0 && texLoaded && Globals::Instance->HasSegment(segmentNumber)) { - if (segmentNumber != SEGMENT_SCENE) + ZFile* auxParent = nullptr; + if (segmentNumber == self->parent->segment) { - if (texAddr < parent->GetRawData().size()) + auxParent = self->parent; + } + else + { + // Try to find a non-external file (ie, one we are actually extracting) + // which has the same segment number we are looking for. + for (auto& otherFile : Globals::Instance->cfg.segmentRefFiles[segmentNumber]) { - ZTexture* tex = parent->GetTextureResource(texAddr); - if (tex != nullptr) - tex->isPalette = texIsPalette; - else + if (!otherFile->isExternalFile) { - tex = new ZTexture(parent); - tex->FromBinary(texAddr, texWidth, texHeight, - TexFormatToTexType(texFmt, texSiz), texIsPalette); - parent->AddTextureResource(texAddr, tex); + auxParent = otherFile; } - - if (!texIsPalette) - self->lastTexture = tex; - else - self->lastTlut = tex; - - return true; } } - else if (scene != nullptr) + + if (auxParent == nullptr) { - if (scene->parent->GetDeclaration(texAddr) == nullptr) + // We can't declare the texture in any of the files we are extracting. + return false; + } + + if (auxParent->IsOffsetInFileRange(texAddr)) + { + ZTexture* tex = auxParent->GetTextureResource(texAddr); + if (tex != nullptr) + tex->isPalette = texIsPalette; + else { - ZTexture* tex = scene->parent->GetTextureResource(texAddr); - if (tex != nullptr) - tex->isPalette = texIsPalette; - else - { - tex = new ZTexture(scene->parent); - tex->FromBinary(texAddr, texWidth, texHeight, - TexFormatToTexType(texFmt, texSiz), texIsPalette); - - scene->parent->AddTextureResource(texAddr, tex); - } - - if (!texIsPalette) - self->lastTexture = tex; - else - self->lastTlut = tex; - - auto filepath = Globals::Instance->outputPath / - Path::GetFileNameWithoutExtension(tex->GetName()); - auto filename = StringHelper::Sprintf("%s.%s.inc.c", filepath.c_str(), - tex->GetExternalExtension().c_str()); - scene->parent->AddDeclarationIncludeArray(texAddr, filename, tex->GetRawDataSize(), - tex->GetSourceTypeName(), tex->GetName(), - 0); + tex = new ZTexture(auxParent); + tex->ExtractFromBinary(texAddr, texWidth, texHeight, + TexFormatToTexType(texFmt, texSiz), texIsPalette); + auxParent->AddTextureResource(texAddr, tex); } + + if (!texIsPalette) + self->lastTexture = tex; + else + self->lastTlut = tex; + + if (auxParent->GetDeclaration(texAddr) == nullptr) + { + tex->DeclareVar(self->GetName(), ""); + } + return true; } } @@ -2166,13 +2079,6 @@ TextureType ZDisplayList::TexFormatToTexType(F3DZEXTexFormats fmt, F3DZEXTexSize return TextureType::RGBA16bpp; } -void ZDisplayList::GenerateHLIntermediette(HLFileIntermediette& hlFile) -{ - HLModelIntermediette* mdl = (HLModelIntermediette*)&hlFile; - HLModelIntermediette::FromZDisplayList(mdl, this); - mdl->blocks.push_back(new HLTerminator()); -} - bool ZDisplayList::IsExternalResource() const { return false; @@ -2197,3 +2103,8 @@ size_t ZDisplayList::GetRawDataSize() const { return instructions.size() * 8; } + +DeclarationAlignment ZDisplayList::GetDeclarationAlignment() const +{ + return DeclarationAlignment::Align8; +} diff --git a/tools/ZAPD/ZAPD/ZDisplayList.h b/tools/ZAPD/ZAPD/ZDisplayList.h index 09394b263e..d538666750 100644 --- a/tools/ZAPD/ZAPD/ZDisplayList.h +++ b/tools/ZAPD/ZAPD/ZDisplayList.h @@ -288,14 +288,15 @@ class ZDisplayList : public ZResource protected: static TextureType TexFormatToTexType(F3DZEXTexFormats fmt, F3DZEXTexSizes siz); - void ParseF3DZEX(F3DZEXOpcode opcode, uint64_t data, int32_t i, std::string prefix, char* line); - void ParseF3DEX(F3DEXOpcode opcode, uint64_t data, std::string prefix, char* line); + void ParseF3DZEX(F3DZEXOpcode opcode, uint64_t data, int32_t i, const std::string& prefix, + char* line); + void ParseF3DEX(F3DEXOpcode opcode, uint64_t data, const std::string& prefix, char* line); // Various Instruction Optimizations bool SequenceCheck(std::vector sequence, int32_t startIndex); - int32_t OptimizationChecks(int32_t startIndex, std::string& output, std::string prefix); + int32_t OptimizationChecks(int32_t startIndex, std::string& output, const std::string& prefix); int32_t OptimizationCheck_LoadTextureBlock(int32_t startIndex, std::string& output, - std::string prefix); + const std::string& prefix); // int32_t OptimizationCheck_LoadMultiBlock(int32_t startIndex, std::string& output, std::string // prefix); @@ -303,7 +304,7 @@ protected: void Opcode_F3DEX_G_SETOTHERMODE_L(uint64_t data, char* line); // Shared Opcodes between F3DZEX and F3DEX - void Opcode_G_DL(uint64_t data, std::string prefix, char* line); + void Opcode_G_DL(uint64_t data, const std::string& prefix, char* line); void Opcode_G_MODIFYVTX(uint64_t data, char* line); void Opcode_G_CULLDL(uint64_t data, char* line); void Opcode_G_TRI1(uint64_t data, char* line); @@ -311,22 +312,19 @@ protected: void Opcode_G_MTX(uint64_t data, char* line); void Opcode_G_VTX(uint64_t data, char* line); void Opcode_G_TEXTURE(uint64_t data, char* line); - void Opcode_G_SETTIMG(uint64_t data, std::string prefix, char* line); + void Opcode_G_SETTIMG(uint64_t data, const std::string& prefix, char* line); void Opcode_G_SETTILE(uint64_t data, char* line); - void Opcode_G_SETTILESIZE(uint64_t data, std::string prefix, char* line); + void Opcode_G_SETTILESIZE(uint64_t data, const std::string& prefix, char* line); void Opcode_G_LOADBLOCK(uint64_t data, char* line); void Opcode_G_SETCOMBINE(uint64_t data, char* line); void Opcode_G_SETPRIMCOLOR(uint64_t data, char* line); void Opcode_G_SETOTHERMODE_L(uint64_t data, char* line); void Opcode_G_SETOTHERMODE_H(uint64_t data, char* line); - void Opcode_G_LOADTLUT(uint64_t data, std::string prefix, char* line); - void Opcode_G_ENDDL(std::string prefix, char* line); + void Opcode_G_LOADTLUT(uint64_t data, const std::string& prefix, char* line); + void Opcode_G_ENDDL(const std::string& prefix, char* line); public: - std::string sceneSegName; - ZRoom* scene; std::vector instructions; - std::string curPrefix; int32_t lastTexWidth, lastTexHeight, lastTexAddr, lastTexSeg; F3DZEXTexFormats lastTexFmt; @@ -337,44 +335,41 @@ public: DListType dListType; std::map> vertices; - std::map vtxDeclarations; std::vector otherDLists; ZTexture* lastTexture = nullptr; ZTexture* lastTlut = nullptr; - std::vector references; - - std::string defines; // Hack for special cases where vertex arrays intersect... + std::vector references; std::vector mtxList; ZDisplayList(ZFile* nParent); - ZDisplayList(uint32_t rawDataIndex, int32_t rawDataSize, ZFile* nParent); ~ZDisplayList(); void ExtractFromXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex) override; + void ExtractFromBinary(uint32_t nRawDataIndex, int32_t rawDataSize); void ParseRawData() override; - Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr); + Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override; + std::string GetDefaultName(const std::string& prefix) const override; - void TextureGenCheck(std::string prefix); - static bool TextureGenCheck(ZRoom* scene, ZFile* parent, std::string prefix, int32_t texWidth, - int32_t texHeight, uint32_t texAddr, uint32_t texSeg, - F3DZEXTexFormats texFmt, F3DZEXTexSizes texSiz, bool texLoaded, - bool texIsPalette, ZDisplayList* self); + void TextureGenCheck(); + static bool TextureGenCheck(int32_t texWidth, int32_t texHeight, uint32_t texAddr, + uint32_t texSeg, F3DZEXTexFormats texFmt, F3DZEXTexSizes texSiz, + bool texLoaded, bool texIsPalette, ZDisplayList* self); static int32_t GetDListLength(const std::vector& rawData, uint32_t rawDataIndex, DListType dListType); size_t GetRawDataSize() const override; + DeclarationAlignment GetDeclarationAlignment() const override; std::string GetSourceOutputHeader(const std::string& prefix) override; std::string GetSourceOutputCode(const std::string& prefix) override; std::string ProcessLegacy(const std::string& prefix); std::string ProcessGfxDis(const std::string& prefix); - virtual void GenerateHLIntermediette(HLFileIntermediette& hlFile) override; bool IsExternalResource() const override; - virtual std::string GetExternalExtension() const override; + std::string GetExternalExtension() const override; std::string GetSourceTypeName() const override; ZResourceType GetResourceType() const override; diff --git a/tools/ZAPD/ZAPD/ZFile.cpp b/tools/ZAPD/ZAPD/ZFile.cpp index b09dc55c32..82cb84f83f 100644 --- a/tools/ZAPD/ZAPD/ZFile.cpp +++ b/tools/ZAPD/ZAPD/ZFile.cpp @@ -1,13 +1,17 @@ #include "ZFile.h" + #include #include +#include #include -#include "Directory.h" -#include "File.h" + +#include +#include #include "Globals.h" -#include "HighLevel/HLModelIntermediette.h" #include "OutputFormatter.h" -#include "Path.h" +#include "Utils/Directory.h" +#include "Utils/File.h" +#include "Utils/Path.h" #include "ZAnimation.h" #include "ZArray.h" #include "ZBackground.h" @@ -25,8 +29,6 @@ #include "ZVector.h" #include "ZVtx.h" -using namespace tinyxml2; - ZFile::ZFile() { resources = std::vector(); @@ -38,13 +40,15 @@ ZFile::ZFile() rangeEnd = 0xFFFFFFFF; } -ZFile::ZFile(std::string nName) : ZFile() +ZFile::ZFile(const fs::path& nOutPath, const std::string& nName) : ZFile() { name = nName; + outName = nName; + outputPath = nOutPath; } -ZFile::ZFile(ZFileMode mode, tinyxml2::XMLElement* reader, const fs::path& nBasePath, - std::string filename, const fs::path& nXmlFilePath, bool placeholderMode) +ZFile::ZFile(ZFileMode nMode, tinyxml2::XMLElement* reader, const fs::path& nBasePath, + const fs::path& nOutPath, const std::string& filename, const fs::path& nXmlFilePath) : ZFile() { xmlFilePath = nXmlFilePath; @@ -53,8 +57,16 @@ ZFile::ZFile(ZFileMode mode, tinyxml2::XMLElement* reader, const fs::path& nBase else basePath = nBasePath; - ParseXML(mode, reader, filename, placeholderMode); - DeclareResourceSubReferences(); + if (nOutPath == "") + outputPath = Directory::GetCurrentDirectory(); + else + outputPath = nOutPath; + + mode = nMode; + + ParseXML(reader, filename); + if (mode != ZFileMode::ExternalFile) + DeclareResourceSubReferences(); } ZFile::~ZFile() @@ -68,10 +80,17 @@ ZFile::~ZFile() { delete d.second; } + + for (auto sym : symbolResources) + { + delete sym.second; + } } -void ZFile::ParseXML(ZFileMode mode, XMLElement* reader, std::string filename, bool placeholderMode) +void ZFile::ParseXML(tinyxml2::XMLElement* reader, const std::string& filename) { + assert(mode != ZFileMode::Invalid); + if (filename == "") name = reader->Attribute("Name"); else @@ -87,11 +106,11 @@ void ZFile::ParseXML(ZFileMode mode, XMLElement* reader, std::string filename, b const char* gameStr = reader->Attribute("Game"); if (reader->Attribute("Game") != nullptr) { - if (std::string(gameStr) == "MM") + if (std::string_view(gameStr) == "MM") Globals::Instance->game = ZGame::MM_RETAIL; - else if (std::string(gameStr) == "SW97" || std::string(gameStr) == "OOTSW97") + else if (std::string_view(gameStr) == "SW97" || std::string_view(gameStr) == "OOTSW97") Globals::Instance->game = ZGame::OOT_SW97; - else if (std::string(gameStr) == "OOT") + else if (std::string_view(gameStr) == "OOT") Globals::Instance->game = ZGame::OOT_RETAIL; else throw std::runtime_error( @@ -107,14 +126,15 @@ void ZFile::ParseXML(ZFileMode mode, XMLElement* reader, std::string filename, b if (reader->Attribute("RangeEnd") != nullptr) rangeEnd = StringHelper::StrToL(reader->Attribute("RangeEnd"), 16); - // Commented until ZArray doesn't use a ZFile to parse it's contents anymore. - /* - if (reader->Attribute("Segment") == nullptr) - throw std::runtime_error(StringHelper::Sprintf( - "ZFile::ParseXML: Error in '%s'.\n" - "\t Missing 'Segment' attribute in File node. \n", - name.c_str())); - */ + if (rangeStart > rangeEnd) + throw std::runtime_error("Error: RangeStart must be before than RangeEnd."); + + // Not every XML may have a segment number, so this doesn't make much sense anymore. + // if (reader->Attribute("Segment") == nullptr) + // throw std::runtime_error( + // StringHelper::Sprintf("ZFile::ParseXML: Error in '%s'.\n" + // "\t Missing 'Segment' attribute in File node. \n", + // name.c_str())); if (reader->Attribute("Segment") != nullptr) { @@ -122,13 +142,21 @@ void ZFile::ParseXML(ZFileMode mode, XMLElement* reader, std::string filename, b Globals::Instance->AddSegment(segment, this); } - if (mode == ZFileMode::Extract) + if (mode == ZFileMode::Extract || mode == ZFileMode::ExternalFile) { if (!File::Exists((basePath / name).string())) throw std::runtime_error( StringHelper::Sprintf("Error! File %s does not exist.", (basePath / name).c_str())); rawData = File::ReadAllBytes((basePath / name).string()); + + /* + * TODO: In OoT repo ovl_Boss_Sst has a wrong RangeEnd (0xAD40 instead of 0xAD70), + * so uncommenting the following produces wrong behavior. + * If somebody fixes that in OoT repo, uncomment this. I'm too tired of fixing XMLs. + */ + // if (reader->Attribute("RangeEnd") == nullptr) + // rangeEnd = rawData.size(); } std::unordered_set nameSet; @@ -138,16 +166,13 @@ void ZFile::ParseXML(ZFileMode mode, XMLElement* reader, std::string filename, b auto nodeMap = *GetNodeMap(); uint32_t rawDataIndex = 0; - for (XMLElement* child = reader->FirstChildElement(); child != nullptr; + for (tinyxml2::XMLElement* child = reader->FirstChildElement(); child != nullptr; child = child->NextSiblingElement()) { const char* nameXml = child->Attribute("Name"); const char* outNameXml = child->Attribute("OutName"); const char* offsetXml = child->Attribute("Offset"); - if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_INFO) - printf("%s: 0x%06X\n", nameXml, rawDataIndex); - // Check for repeated attributes. if (offsetXml != nullptr) { @@ -170,6 +195,10 @@ void ZFile::ParseXML(ZFileMode mode, XMLElement* reader, std::string filename, b throw std::runtime_error( StringHelper::Sprintf("Error no offset specified for %s", nameXml)); } + + if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_INFO) + printf("%s: 0x%06X\n", nameXml, rawDataIndex); + if (outNameXml != nullptr) { if (outNameSet.find(outNameXml) != outNameSet.end()) @@ -197,18 +226,27 @@ void ZFile::ParseXML(ZFileMode mode, XMLElement* reader, std::string filename, b { ZResource* nRes = nodeMap[nodeName](this); - if (mode == ZFileMode::Extract) + if (mode == ZFileMode::Extract || mode == ZFileMode::ExternalFile) nRes->ExtractFromXML(child, rawDataIndex); - auto resType = nRes->GetResourceType(); - if (resType == ZResourceType::Texture) + switch (nRes->GetResourceType()) + { + case ZResourceType::Texture: AddTextureResource(rawDataIndex, static_cast(nRes)); - else - resources.push_back(nRes); + break; + + case ZResourceType::Symbol: + AddSymbolResource(rawDataIndex, static_cast(nRes)); + break; + + default: + AddResource(nRes); + break; + } rawDataIndex += nRes->GetRawDataSize(); } - else if (std::string(child->Name()) == "File") + else if (std::string_view(child->Name()) == "File") { throw std::runtime_error(StringHelper::Sprintf( "ZFile::ParseXML: Error in '%s'.\n\t Can't declare a File inside a File.\n", @@ -234,21 +272,13 @@ void ZFile::DeclareResourceSubReferences() void ZFile::BuildSourceFile() { - if (!Directory::Exists(Globals::Instance->outputPath)) - Directory::CreateDirectory(Globals::Instance->outputPath); + if (mode == ZFileMode::ExternalFile) + return; - GenerateSourceFiles(Globals::Instance->outputPath); -} + if (!Directory::Exists(outputPath)) + Directory::CreateDirectory(outputPath); -std::string ZFile::GetVarName(uint32_t address) -{ - for (std::pair pair : declarations) - { - if (pair.first == address) - return pair.second->varName; - } - - return ""; + GenerateSourceFiles(); } std::string ZFile::GetName() const @@ -256,6 +286,11 @@ std::string ZFile::GetName() const return name; } +ZFileMode ZFile::GetMode() const +{ + return mode; +} + const fs::path& ZFile::GetXmlFilePath() const { return xmlFilePath; @@ -268,28 +303,56 @@ const std::vector& ZFile::GetRawData() const void ZFile::ExtractResources() { - if (!Directory::Exists(Globals::Instance->outputPath)) - Directory::CreateDirectory(Globals::Instance->outputPath); + if (mode == ZFileMode::ExternalFile) + return; - if (!Directory::Exists(GetSourceOutputFolderPath().string())) - Directory::CreateDirectory(GetSourceOutputFolderPath().string()); + if (!Directory::Exists(outputPath)) + Directory::CreateDirectory(outputPath); - for (ZResource* res : resources) - res->PreGenSourceFiles(); + if (!Directory::Exists(GetSourceOutputFolderPath())) + Directory::CreateDirectory(GetSourceOutputFolderPath()); + + for (size_t i = 0; i < resources.size(); i++) + resources[i]->ParseRawDataLate(); + for (size_t i = 0; i < resources.size(); i++) + resources[i]->DeclareReferencesLate(name); if (Globals::Instance->genSourceFile) - GenerateSourceFiles(Globals::Instance->outputPath); + GenerateSourceFiles(); + + MemoryStream* memStream = new MemoryStream(); + BinaryWriter writer = BinaryWriter(memStream); + + ExporterSet* exporterSet = Globals::Instance->GetExporterSet(); + + if (exporterSet != nullptr && exporterSet->beginFileFunc != nullptr) + exporterSet->beginFileFunc(this); for (ZResource* res : resources) { if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_INFO) printf("Saving resource %s\n", res->GetName().c_str()); - res->Save(Globals::Instance->outputPath); + res->Save(outputPath); + + // Check if we have an exporter "registered" for this resource type + ZResourceExporter* exporter = Globals::Instance->GetExporter(res->GetResourceType()); + if (exporter != nullptr) + exporter->Save(res, Globals::Instance->outputPath.string(), &writer); } - if (Globals::Instance->testMode) - GenerateHLIntermediette(); + if (memStream->GetLength() > 0) + { + File::WriteAllBytes(StringHelper::Sprintf("%s%s.bin", + Globals::Instance->outputPath.string().c_str(), + GetName().c_str()), + memStream->ToVector()); + } + + writer.Close(); + + if (exporterSet != nullptr && exporterSet->endFileFunc != nullptr) + exporterSet->endFileFunc(this); } void ZFile::AddResource(ZResource* res) @@ -321,87 +384,101 @@ std::vector ZFile::GetResourcesOfType(ZResourceType resType) return resList; } -Declaration* ZFile::AddDeclaration(uint32_t address, DeclarationAlignment alignment, size_t size, - std::string varType, std::string varName, std::string body) +Declaration* ZFile::AddDeclaration(offset_t address, DeclarationAlignment alignment, size_t size, + const std::string& varType, const std::string& varName, + const std::string& body) { - assert(GETSEGNUM(address) == 0); - AddDeclarationDebugChecks(address); + bool validOffset = AddDeclarationChecks(address, varName); + if (!validOffset) + return nullptr; - Declaration* decl = new Declaration(alignment, size, varType, varName, false, body); - declarations[address] = decl; + Declaration* decl = GetDeclaration(address); + if (decl == nullptr) + { + decl = new Declaration(address, alignment, size, varType, varName, false, body); + declarations[address] = decl; + } + else + { + decl->alignment = alignment; + decl->size = size; + decl->varType = varType; + decl->varName = varName; + decl->text = body; + } return decl; } -Declaration* ZFile::AddDeclaration(uint32_t address, DeclarationAlignment alignment, - DeclarationPadding padding, size_t size, std::string varType, - std::string varName, std::string body) +Declaration* ZFile::AddDeclarationArray(offset_t address, DeclarationAlignment alignment, + size_t size, const std::string& varType, + const std::string& varName, size_t arrayItemCnt, + const std::string& body) { - assert(GETSEGNUM(address) == 0); - AddDeclarationDebugChecks(address); + bool validOffset = AddDeclarationChecks(address, varName); + if (!validOffset) + return nullptr; - declarations[address] = - new Declaration(alignment, padding, size, varType, varName, false, body); - return declarations[address]; + Declaration* decl = GetDeclaration(address); + if (decl == nullptr) + { + decl = + new Declaration(address, alignment, size, varType, varName, true, arrayItemCnt, body); + declarations[address] = decl; + } + else + { + if (decl->isPlaceholder) + decl->varName = varName; + decl->alignment = alignment; + decl->size = size; + decl->varType = varType; + decl->isArray = true; + decl->arrayItemCnt = arrayItemCnt; + decl->text = body; + } + + return decl; } -Declaration* ZFile::AddDeclarationArray(uint32_t address, DeclarationAlignment alignment, - size_t size, std::string varType, std::string varName, - size_t arrayItemCnt, std::string body) +Declaration* ZFile::AddDeclarationArray(offset_t address, DeclarationAlignment alignment, + size_t size, const std::string& varType, + const std::string& varName, + const std::string& arrayItemCntStr, const std::string& body) { - assert(GETSEGNUM(address) == 0); - AddDeclarationDebugChecks(address); + bool validOffset = AddDeclarationChecks(address, varName); + if (!validOffset) + return nullptr; - declarations[address] = - new Declaration(alignment, size, varType, varName, true, arrayItemCnt, body); - return declarations[address]; + Declaration* decl = GetDeclaration(address); + if (decl == nullptr) + { + decl = new Declaration(address, alignment, size, varType, varName, true, arrayItemCntStr, + body); + declarations[address] = decl; + } + else + { + decl->alignment = alignment; + decl->size = size; + decl->varType = varType; + decl->varName = varName; + decl->isArray = true; + decl->arrayItemCntStr = arrayItemCntStr; + decl->text = body; + } + return decl; } -Declaration* ZFile::AddDeclarationArray(uint32_t address, DeclarationAlignment alignment, - size_t size, std::string varType, std::string varName, - std::string arrayItemCntStr, std::string body) +Declaration* ZFile::AddDeclarationPlaceholder(offset_t address, const std::string& varName) { - assert(GETSEGNUM(address) == 0); - AddDeclarationDebugChecks(address); + bool validOffset = AddDeclarationChecks(address, varName); + if (!validOffset) + return nullptr; - declarations[address] = - new Declaration(alignment, size, varType, varName, true, arrayItemCntStr, body); - return declarations[address]; -} - -Declaration* ZFile::AddDeclarationArray(uint32_t address, DeclarationAlignment alignment, - size_t size, std::string varType, std::string varName, - size_t arrayItemCnt, std::string body, bool isExternal) -{ - assert(GETSEGNUM(address) == 0); - AddDeclarationDebugChecks(address); - - declarations[address] = - new Declaration(alignment, size, varType, varName, true, arrayItemCnt, body, isExternal); - return declarations[address]; -} - -Declaration* ZFile::AddDeclarationArray(uint32_t address, DeclarationAlignment alignment, - DeclarationPadding padding, size_t size, - std::string varType, std::string varName, - size_t arrayItemCnt, std::string body) -{ - assert(GETSEGNUM(address) == 0); - AddDeclarationDebugChecks(address); - - declarations[address] = - new Declaration(alignment, padding, size, varType, varName, true, arrayItemCnt, body); - return declarations[address]; -} - -Declaration* ZFile::AddDeclarationPlaceholder(uint32_t address) -{ - assert(GETSEGNUM(address) == 0); - AddDeclarationDebugChecks(address); Declaration* decl; - if (declarations.find(address) == declarations.end()) { - decl = new Declaration(DeclarationAlignment::None, 0, "", "", false, ""); + decl = new Declaration(address, DeclarationAlignment::Align4, 0, "", varName, false, ""); decl->isPlaceholder = true; declarations[address] = decl; } @@ -411,114 +488,165 @@ Declaration* ZFile::AddDeclarationPlaceholder(uint32_t address) return decl; } -Declaration* ZFile::AddDeclarationPlaceholder(uint32_t address, std::string varName) +Declaration* ZFile::AddDeclarationInclude(offset_t address, const std::string& includePath, + size_t size, const std::string& varType, + const std::string& varName) { - assert(GETSEGNUM(address) == 0); - AddDeclarationDebugChecks(address); - Declaration* decl; + bool validOffset = AddDeclarationChecks(address, varName); + if (!validOffset) + return nullptr; - if (declarations.find(address) == declarations.end()) + Declaration* decl = GetDeclaration(address); + if (decl == nullptr) { - decl = new Declaration(DeclarationAlignment::None, 0, "", varName, false, ""); - decl->isPlaceholder = true; + decl = new Declaration(address, includePath, size, varType, varName); declarations[address] = decl; } else - decl = declarations[address]; - + { + decl->includePath = includePath; + decl->size = size; + decl->varType = varType; + decl->varName = varName; + } return decl; } -Declaration* ZFile::AddDeclarationInclude(uint32_t address, std::string includePath, size_t size, - std::string varType, std::string varName) +Declaration* ZFile::AddDeclarationIncludeArray(offset_t address, std::string& includePath, + size_t size, const std::string& varType, + const std::string& varName, size_t arrayItemCnt) { - assert(GETSEGNUM(address) == 0); - AddDeclarationDebugChecks(address); - - if (declarations.find(address) == declarations.end()) - declarations[address] = new Declaration(includePath, size, varType, varName); - - return declarations[address]; -} - -Declaration* ZFile::AddDeclarationIncludeArray(uint32_t address, std::string includePath, - size_t size, std::string varType, - std::string varName, size_t arrayItemCnt) -{ - assert(GETSEGNUM(address) == 0); - AddDeclarationDebugChecks(address); + bool validOffset = AddDeclarationChecks(address, varName); + if (!validOffset) + return nullptr; if (StringHelper::StartsWith(includePath, "assets/extracted/")) includePath = "assets/" + StringHelper::Split(includePath, "assets/extracted/")[1]; if (StringHelper::StartsWith(includePath, "assets/custom/")) includePath = "assets/" + StringHelper::Split(includePath, "assets/custom/")[1]; - auto declCheck = declarations.find(address); - - if (declCheck != declarations.end()) + Declaration* decl = GetDeclaration(address); + if (decl == nullptr) { - declCheck->second->includePath = includePath; - declCheck->second->varType = varType; - declCheck->second->varName = varName; - declCheck->second->size = size; - declCheck->second->isArray = true; - declCheck->second->arrayItemCnt = arrayItemCnt; - - return declCheck->second; - } - else - { - Declaration* decl = new Declaration(includePath, size, varType, varName); + decl = new Declaration(address, includePath, size, varType, varName); decl->isArray = true; decl->arrayItemCnt = arrayItemCnt; declarations[address] = decl; - return declarations[address]; } + else + { + decl->includePath = includePath; + decl->varType = varType; + decl->varName = varName; + decl->size = size; + decl->isArray = true; + decl->arrayItemCnt = arrayItemCnt; + } + return decl; } -void ZFile::AddDeclarationDebugChecks(uint32_t address) +bool ZFile::AddDeclarationChecks(uint32_t address, const std::string& varName) { assert(GETSEGNUM(address) == 0); -#ifdef _DEBUG + assert(varName != ""); +#ifdef DEVELOPMENT if (address == 0x0000) { - int32_t bp = 0; + [[maybe_unused]] int32_t bp = 0; } #endif + + if (!IsOffsetInFileRange(address)) + { + fprintf(stderr, + "%s: Warning in %s\n" + "\t Tried to declare a variable outside of this file's range. Ignoring...\n" + "\t\t Variable's name: %s\n" + "\t\t Variable's offset: 0x%06X\n", + __PRETTY_FUNCTION__, name.c_str(), varName.c_str(), address); + return false; + } + + return true; } -std::string ZFile::GetDeclarationName(uint32_t address) const -{ - return GetDeclarationName(address, - "ERROR_COULD_NOT_FIND_DECLARATION"); // Note: For now that default - // message is just for testing -} - -std::string ZFile::GetDeclarationName(uint32_t address, std::string defaultResult) const -{ - Declaration* decl = GetDeclaration(address); - if (decl != nullptr) - return decl->varName; - - return defaultResult; -} - -std::string ZFile::GetDeclarationPtrName(segptr_t segAddress) const +bool ZFile::GetDeclarationPtrName(segptr_t segAddress, const std::string& expectedType, + std::string& declName) const { if (segAddress == 0) - return "NULL"; + { + declName = "NULL"; + return true; + } - Declaration* decl = GetDeclaration(Seg2Filespace(segAddress, baseAddress)); + uint32_t offset = Seg2Filespace(segAddress, baseAddress); + Declaration* decl = GetDeclaration(offset); + if (GETSEGNUM(segAddress) != segment || decl == nullptr) + { + declName = StringHelper::Sprintf("0x%08X", segAddress); + return false; + } - if (!Globals::Instance->HasSegment(GETSEGNUM(segAddress)) || decl == nullptr) - return StringHelper::Sprintf("0x%08X", segAddress); + if (expectedType != "" && expectedType != "void*") + { + if (expectedType != decl->varType && "static " + expectedType != decl->varType) + { + declName = StringHelper::Sprintf("0x%08X", segAddress); + return false; + } + } if (!decl->isArray) - return "&" + decl->varName; + declName = "&" + decl->varName; + else + declName = decl->varName; + return true; +} - return decl->varName; +bool ZFile::GetDeclarationArrayIndexedName(segptr_t segAddress, size_t elementSize, + const std::string& expectedType, + std::string& declName) const +{ + if (segAddress == 0) + { + declName = "NULL"; + return true; + } + + uint32_t address = Seg2Filespace(segAddress, baseAddress); + Declaration* decl = GetDeclarationRanged(address); + if (GETSEGNUM(segAddress) != segment || decl == nullptr || !decl->isArray) + { + declName = StringHelper::Sprintf("0x%08X", segAddress); + return false; + } + + if (expectedType != "" && expectedType != "void*") + { + if (expectedType != decl->varType && "static " + expectedType != decl->varType) + { + declName = StringHelper::Sprintf("0x%08X", segAddress); + return false; + } + } + + if (decl->address == address) + { + declName = decl->varName; + return true; + } + + if ((address - decl->address) % elementSize != 0 || !(address < decl->address + decl->size)) + { + declName = StringHelper::Sprintf("0x%08X", segAddress); + return false; + } + + uint32_t index = (address - decl->address) / elementSize; + declName = StringHelper::Sprintf("&%s[%u]", decl->varName.c_str(), index); + return true; } Declaration* ZFile::GetDeclaration(uint32_t address) const @@ -540,86 +668,47 @@ Declaration* ZFile::GetDeclarationRanged(uint32_t address) const return nullptr; } -uint32_t ZFile::GetDeclarationRangedAddress(uint32_t address) const -{ - for (const auto decl : declarations) - { - if (address >= decl.first && address < decl.first + decl.second->size) - return decl.first; - } - - return 0xFFFFFFFF; -} - bool ZFile::HasDeclaration(uint32_t address) { assert(GETSEGNUM(address) == 0); return declarations.find(address) != declarations.end(); } -void ZFile::GenerateSourceFiles(fs::path outputDir) +void ZFile::GenerateSourceFiles() { - std::string sourceOutput = ""; + std::string sourceOutput; sourceOutput += "#include \"ultra64.h\"\n"; sourceOutput += "#include \"z64.h\"\n"; sourceOutput += "#include \"macros.h\"\n"; sourceOutput += GetHeaderInclude(); + bool hasZRoom = false; + for (const auto& res : resources) + { + ZResourceType resType = res->GetResourceType(); + if (resType == ZResourceType::Room || resType == ZResourceType::Scene || + resType == ZResourceType::AltHeader) + { + hasZRoom = true; + break; + } + } + + if (hasZRoom) + { + sourceOutput += GetZRoomHeaderInclude(); + } + + sourceOutput += GetExternalFileHeaderInclude(); + GeneratePlaceholderDeclarations(); // Generate Code for (size_t i = 0; i < resources.size(); i++) { ZResource* res = resources.at(i); - std::string resSrc = res->GetSourceOutputCode(name); - - if (res->IsExternalResource()) - { - std::string path = Path::GetFileNameWithoutExtension(res->GetName()).c_str(); - - std::string assetOutDir = - (outputDir / Path::GetFileNameWithoutExtension(res->GetOutName())).string(); - std::string declType = res->GetSourceTypeName(); - - std::string incStr = StringHelper::Sprintf("%s.%s.inc", assetOutDir.c_str(), - res->GetExternalExtension().c_str()); - - if (res->GetResourceType() == ZResourceType::Texture) - { - ZTexture* tex = static_cast(res); - - if (!Globals::Instance->cfg.texturePool.empty()) - { - tex->CalcHash(); - - // TEXTURE POOL CHECK - if (Globals::Instance->cfg.texturePool.find(tex->hash) != - Globals::Instance->cfg.texturePool.end()) - { - incStr = Globals::Instance->cfg.texturePool[tex->hash].path.string() + "." + - res->GetExternalExtension() + ".inc"; - } - } - - incStr += ".c"; - } - else if (res->GetResourceType() == ZResourceType::Blob || - res->GetResourceType() == ZResourceType::Background) - { - incStr += ".c"; - } - - AddDeclarationIncludeArray(res->GetRawDataIndex(), incStr, res->GetRawDataSize(), - declType, res->GetName(), 0); - } - else - { - sourceOutput += resSrc; - } - - if (resSrc != "" && !res->IsExternalResource()) - sourceOutput += "\n"; + res->GetSourceOutputCode(name); } sourceOutput += ProcessDeclarations(); @@ -650,6 +739,11 @@ void ZFile::GenerateSourceHeaderFiles() formatter.Write("\n"); } + for (auto& sym : symbolResources) + { + formatter.Write(sym.second->GetSourceOutputHeader("")); + } + formatter.Write(ProcessExterns()); fs::path headerFilename = GetSourceOutputFolderPath() / outName.stem().concat(".h"); @@ -660,26 +754,48 @@ void ZFile::GenerateSourceHeaderFiles() File::WriteAllText(headerFilename, formatter.GetOutput()); } -void ZFile::GenerateHLIntermediette() +std::string ZFile::GetHeaderInclude() const { - // This is kinda hacky but it gets the job done for now... - HLModelIntermediette* mdl = new HLModelIntermediette(); + std::string headers = StringHelper::Sprintf("#include \"%s.h\"\n", + (outName.parent_path() / outName.stem()).c_str()); - for (ZResource* res : resources) - { - if (res->GetResourceType() == ZResourceType::DisplayList || - res->GetResourceType() == ZResourceType::Skeleton) - res->GenerateHLIntermediette(*mdl); - } - - // std::string test = mdl->ToOBJFile(); - // std::string test2 = mdl->ToAssimpFile(); + return headers; } -std::string ZFile::GetHeaderInclude() +std::string ZFile::GetZRoomHeaderInclude() const { - return StringHelper::Sprintf("#include \"%s\"\n\n", - (outName.parent_path() / outName.stem().concat(".h")).c_str()); + std::string headers; + headers += "#include \"segment_symbols.h\"\n"; + headers += "#include \"command_macros_base.h\"\n"; + headers += "#include \"z64cutscene_commands.h\"\n"; + headers += "#include \"variables.h\"\n"; + return headers; +} + +std::string ZFile::GetExternalFileHeaderInclude() const +{ + std::string externalFilesIncludes = ""; + + for (ZFile* externalFile : Globals::Instance->files) + { + if (externalFile != this) + { + fs::path outputFolderPath = externalFile->GetSourceOutputFolderPath(); + if (outputFolderPath == this->GetSourceOutputFolderPath()) + { + outputFolderPath = externalFile->outName.stem(); + } + else + { + outputFolderPath /= externalFile->outName.stem(); + } + + externalFilesIncludes += + StringHelper::Sprintf("#include \"%s.h\"\n", outputFolderPath.c_str()); + } + } + + return externalFilesIncludes; } void ZFile::GeneratePlaceholderDeclarations() @@ -687,8 +803,17 @@ void ZFile::GeneratePlaceholderDeclarations() // Generate placeholder declarations for (ZResource* res : resources) { - if (GetDeclaration(res->GetRawDataIndex()) == nullptr) - AddDeclarationPlaceholder(res->GetRawDataIndex(), res->GetName()); + if (GetDeclaration(res->GetRawDataIndex()) != nullptr) + { + continue; + } + + Declaration* decl = res->DeclareVar(GetName(), ""); + decl->staticConf = res->GetStaticConf(); + if (res->GetResourceType() == ZResourceType::Symbol) + { + decl->staticConf = StaticConfig::Off; + } } } @@ -710,9 +835,52 @@ ZTexture* ZFile::GetTextureResource(uint32_t offset) const return nullptr; } +void ZFile::AddSymbolResource(uint32_t offset, ZSymbol* sym) +{ + symbolResources[offset] = sym; +} + +ZSymbol* ZFile::GetSymbolResource(uint32_t offset) const +{ + auto sym = symbolResources.find(offset); + if (sym != symbolResources.end()) + return sym->second; + + return nullptr; +} + +ZSymbol* ZFile::GetSymbolResourceRanged(uint32_t offset) const +{ + for (const auto decl : symbolResources) + { + if (offset >= decl.first && offset < decl.first + decl.second->GetRawDataSize()) + return decl.second; + } + + return nullptr; +} + fs::path ZFile::GetSourceOutputFolderPath() const { - return Globals::Instance->sourceOutputPath / outName.parent_path(); + return outputPath / outName.parent_path(); +} + +bool ZFile::IsOffsetInFileRange(uint32_t offset) const +{ + if (!(offset < rawData.size())) + return false; + + return rangeStart <= offset && offset < rangeEnd; +} +bool ZFile::IsSegmentedInFilespaceRange(segptr_t segAddress) const +{ + uint8_t segnum = GETSEGNUM(segAddress); + uint32_t offset = Seg2Filespace(segAddress, baseAddress); + + if (segment != segnum) + return false; + + return IsOffsetInFileRange(offset); } std::map* ZFile::GetNodeMap() @@ -729,7 +897,7 @@ void ZFile::RegisterNode(std::string nodeName, ZResourceFactoryFunc* nodeFunc) std::string ZFile::ProcessDeclarations() { - std::string output = ""; + std::string output; if (declarations.size() == 0) return output; @@ -738,7 +906,6 @@ std::string ZFile::ProcessDeclarations() // Account for padding/alignment uint32_t lastAddr = 0; - uint32_t lastSize = 0; // printf("RANGE START: 0x%06X - RANGE END: 0x%06X\n", rangeStart, rangeEnd); @@ -756,21 +923,24 @@ std::string ZFile::ProcessDeclarations() { if (curItem.second->varType == lastItem.second->varType) { - // TEST: For now just do Vtx declarations... - if (lastItem.second->varType == "static Vtx") + if (!curItem.second->declaredInXml && !lastItem.second->declaredInXml) { - int32_t sizeDiff = curItem.first - (lastItem.first + lastItem.second->size); - - // Make sure there isn't an unaccounted inbetween these two - if (sizeDiff == 0) + // TEST: For now just do Vtx declarations... + if (lastItem.second->varType == "Vtx") { - lastItem.second->size += curItem.second->size; - lastItem.second->arrayItemCnt += curItem.second->arrayItemCnt; - lastItem.second->text += "\n" + curItem.second->text; - declarations.erase(curItem.first); - declarationKeys.erase(declarationKeys.begin() + i); - i--; - continue; + int32_t sizeDiff = curItem.first - (lastItem.first + lastItem.second->size); + + // Make sure there isn't an unaccounted inbetween these two + if (sizeDiff == 0) + { + lastItem.second->size += curItem.second->size; + lastItem.second->arrayItemCnt += curItem.second->arrayItemCnt; + lastItem.second->text += "\n" + curItem.second->text; + declarations.erase(curItem.first); + declarationKeys.erase(declarationKeys.begin() + i); + i--; + continue; + } } } } @@ -791,35 +961,21 @@ std::string ZFile::ProcessDeclarations() { if (item.second->alignment == DeclarationAlignment::Align16) { - // int32_t lastAddrSizeTest = declarations[lastAddr]->size; int32_t curPtr = lastAddr + declarations[lastAddr]->size; while (curPtr % 4 != 0) { declarations[lastAddr]->size++; - // item.second->size++; curPtr++; } - - /*while (curPtr % 16 != 0) - { - char buffer[2048]; - - sprintf(buffer, "static u32 align%02X = 0;\n", curPtr); - item.second->text = buffer + item.second->text; - - declarations[lastAddr]->size += 4; - curPtr += 4; - }*/ } else if (item.second->alignment == DeclarationAlignment::Align8) { - int32_t curPtr = lastAddr + declarations[lastAddr]->size; + size_t curPtr = lastAddr + declarations[lastAddr]->size; while (curPtr % 4 != 0) { declarations[lastAddr]->size++; - // item.second->size++; curPtr++; } @@ -827,299 +983,58 @@ std::string ZFile::ProcessDeclarations() { char buffer[2048]; - sprintf(buffer, "static u32 align%02X = 0;\n", curPtr); + sprintf(buffer, "u32 %s_align%02zX = 0;\n", name.c_str(), curPtr); item.second->preText = buffer + item.second->preText; declarations[lastAddr]->size += 4; - // item.second->size += 4; curPtr += 4; } } } - if (item.second->padding == DeclarationPadding::Pad16) - { - int32_t curPtr = item.first + item.second->size; - - while (curPtr % 4 != 0) - { - item.second->size++; - curPtr++; - } - - while (curPtr % 16 != 0) - { - item.second->postText += StringHelper::Sprintf("static u32 pad%02X = 0;\n", curPtr); - - item.second->size += 4; - curPtr += 4; - } - } - lastAddr = item.first; } - // Handle unaccounted data - lastAddr = 0; - lastSize = 0; - std::vector declsAddresses; - for (const auto& item : declarations) - { - declsAddresses.push_back(item.first); - } - declsAddresses.push_back(rawData.size()); - - for (uint32_t currentAddress : declsAddresses) - { - if (currentAddress >= rangeEnd) - { - break; - } - - if (currentAddress < rangeStart) - { - lastAddr = currentAddress; - continue; - } - - if (currentAddress != lastAddr && declarations.find(lastAddr) != declarations.end()) - { - Declaration* lastDecl = declarations.at(lastAddr); - lastSize = lastDecl->size; - - if (lastAddr + lastSize > currentAddress) - { - Declaration* currentDecl = declarations.at(currentAddress); - - fprintf(stderr, - "WARNING: Intersection detected from 0x%06X:0x%06X (%s), conflicts with " - "0x%06X (%s)\n", - lastAddr, lastAddr + lastSize, lastDecl->varName.c_str(), currentAddress, - currentDecl->varName.c_str()); - } - } - - uint32_t unaccountedAddress = lastAddr + lastSize; - - if (unaccountedAddress != currentAddress && lastAddr >= rangeStart && - unaccountedAddress < rangeEnd) - { - int diff = currentAddress - unaccountedAddress; - bool nonZeroUnaccounted = false; - - std::string src = " "; - - for (int i = 0; i < diff; i++) - { - uint8_t val = rawData.at(unaccountedAddress + i); - src += StringHelper::Sprintf("0x%02X, ", val); - if (val != 0x00) - { - nonZeroUnaccounted = true; - } - - if (Globals::Instance->verboseUnaccounted) - { - if ((i % 4 == 3)) - { - src += StringHelper::Sprintf(" // 0x%06X", unaccountedAddress + i - 3); - if (i != (diff - 1)) - { - src += "\n\t"; - } - } - } - else - { - if ((i % 16 == 15) && (i != (diff - 1))) - src += "\n "; - } - } - - if (declarations.find(unaccountedAddress) == declarations.end()) - { - if (diff > 0) - { - std::string unaccountedPrefix = "unaccounted"; - - if (diff < 16 && !nonZeroUnaccounted) - { - unaccountedPrefix = "possiblePadding"; - - // Strip unnecessary padding at the end of the file. - if (unaccountedAddress + diff >= rawData.size()) - break; - } - - Declaration* decl = AddDeclarationArray( - unaccountedAddress, DeclarationAlignment::None, diff, "static u8", - StringHelper::Sprintf("%s_%06X", unaccountedPrefix.c_str(), - unaccountedAddress), - diff, src); - decl->isUnaccounted = true; - - if (Globals::Instance->warnUnaccounted) - { - if (nonZeroUnaccounted) - { - fprintf( - stderr, - "Warning in file: %s (%s)\n" - "\t A non-zero unaccounted block was found at address '0x%06X'.\n" - "\t Block size: '0x%X'.\n", - xmlFilePath.c_str(), name.c_str(), unaccountedAddress, diff); - } - else if (diff >= 16) - { - fprintf(stderr, - "Warning in file: %s (%s)\n" - "\t A big (size>=0x10) zero-only unaccounted block was found " - "at address '0x%06X'.\n" - "\t Block size: '0x%X'.\n", - xmlFilePath.c_str(), name.c_str(), unaccountedAddress, diff); - } - } - } - } - } - - lastAddr = currentAddress; - } + HandleUnaccountedData(); // Go through include declarations // First, handle the prototypes (static only for now) - int32_t protoCnt = 0; for (std::pair item : declarations) { - if (StringHelper::StartsWith(item.second->varType, "static ") && - !item.second->isUnaccounted) - { - if (item.second->isArray) - { - if (item.second->arrayItemCntStr != "") - { - output += StringHelper::Sprintf("%s %s[%s];\n", item.second->varType.c_str(), - item.second->varName.c_str(), - item.second->arrayItemCntStr.c_str()); - } - else if (item.second->arrayItemCnt == 0) - { - output += StringHelper::Sprintf("%s %s[];\n", item.second->varType.c_str(), - item.second->varName.c_str()); - } - else - { - output += StringHelper::Sprintf("%s %s[%i];\n", item.second->varType.c_str(), - item.second->varName.c_str(), - item.second->arrayItemCnt); - } - } - else - output += StringHelper::Sprintf("%s %s;\n", item.second->varType.c_str(), - item.second->varName.c_str()); - - protoCnt++; - } + output += item.second->GetStaticForwardDeclarationStr(); } - if (protoCnt > 0) - output += "\n"; + output += "\n"; // Next, output the actual declarations - for (std::pair item : declarations) + for (const auto& item : declarations) { - if (item.first < rangeStart || item.first >= rangeEnd) - { + if (!IsOffsetInFileRange(item.first)) continue; - } if (item.second->includePath != "") { if (item.second->isExternal) { // HACK - std::string extType = ""; + std::string extType; if (item.second->varType == "Gfx") extType = "dlist"; - else if (item.second->varType == "Vtx" || item.second->varType == "static Vtx") + else if (item.second->varType == "Vtx") extType = "vtx"; - auto filepath = Globals::Instance->outputPath / item.second->varName; + auto filepath = outputPath / item.second->varName; File::WriteAllText( StringHelper::Sprintf("%s.%s.inc", filepath.c_str(), extType.c_str()), item.second->text); } - // Do not asm_process vertex arrays. They have no practical use being overridden. - // if (item.second->varType == "Vtx" || item.second->varType == "static Vtx") - if (item.second->varType != "u64" && item.second->varType != "static u64" && - item.second->varType != "u8" && item.second->varType != "static u8") - { - output += StringHelper::Sprintf( - "%s %s[] = {\n #include \"%s\"\n};\n\n", item.second->varType.c_str(), - item.second->varName.c_str(), - StringHelper::Replace(item.second->includePath, "assets/", "../assets/") - .c_str()); - } - else - { - if (item.second->arrayItemCntStr != "") - output += StringHelper::Sprintf( - "%s %s[%s] = {\n #include \"%s\"\n};\n\n", item.second->varType.c_str(), - item.second->varName.c_str(), item.second->arrayItemCntStr.c_str(), - item.second->includePath.c_str()); - else - output += StringHelper::Sprintf( - "%s %s[] = {\n #include \"%s\"\n};\n\n", item.second->varType.c_str(), - item.second->varName.c_str(), item.second->includePath.c_str()); - } + output += item.second->GetExternalDeclarationStr(); } else if (item.second->varType != "") { - if (item.second->preText != "") - output += item.second->preText + "\n"; - - { - if (item.second->isArray) - { - if (item.second->arrayItemCntStr != "") - { - output += StringHelper::Sprintf( - "%s %s[%s];\n", item.second->varType.c_str(), - item.second->varName.c_str(), item.second->arrayItemCntStr.c_str()); - } - else - { - if (item.second->arrayItemCnt == 0) - output += - StringHelper::Sprintf("%s %s[] = {\n", item.second->varType.c_str(), - item.second->varName.c_str()); - else - output += StringHelper::Sprintf( - "%s %s[%i] = {\n", item.second->varType.c_str(), - item.second->varName.c_str(), item.second->arrayItemCnt); - } - - output += item.second->text + "\n"; - } - else - { - output += StringHelper::Sprintf("%s %s = { ", item.second->varType.c_str(), - item.second->varName.c_str()); - output += item.second->text; - } - - if (output.back() == '\n') - output += "};"; - else - output += " };"; - } - - output += " " + item.second->rightText + "\n\n"; - - if (item.second->postText != "") - output += item.second->postText + "\n"; + output += item.second->GetNormalDeclarationStr(); } } @@ -1132,84 +1047,41 @@ void ZFile::ProcessDeclarationText(Declaration* decl) { size_t refIndex = 0; - if (decl->references.size() > 0) + if (!(decl->references.size() > 0)) + return; + + for (size_t i = 0; i < decl->text.size() - 1; i++) { - for (size_t i = 0; i < decl->text.size() - 1; i++) + char c = decl->text[i]; + char c2 = decl->text[i + 1]; + + if (c == '@' && c2 == 'r') { - char c = decl->text[i]; - char c2 = decl->text[i + 1]; + std::string vtxName; + Globals::Instance->GetSegmentedArrayIndexedName(decl->references[refIndex], 0x10, this, + "Vtx", vtxName); + decl->text.replace(i, 2, vtxName); - if (c == '@' && c2 == 'r') - { - if (refIndex >= decl->references.size()) - break; + refIndex++; - Declaration* refDecl = GetDeclarationRanged(decl->references[refIndex]); - uint32_t refDeclAddr = GetDeclarationRangedAddress(decl->references[refIndex]); - - if (refDecl != nullptr) - { - if (refDecl->isArray) - { - if (refDecl->arrayItemCnt != 0) - { - int32_t itemSize = refDecl->size / refDecl->arrayItemCnt; - int32_t itemIndex = - (decl->references[refIndex] - refDeclAddr) / itemSize; - - decl->text.replace(i, 2, - StringHelper::Sprintf( - "&%s[%i]", refDecl->varName.c_str(), itemIndex)); - } - else - { - decl->text.replace(i, 2, - StringHelper::Sprintf("ERROR ARRAYITEMCNT = 0")); - } - } - else - { - decl->text.replace(i, 2, refDecl->varName); - } - } - else - decl->text.replace(i, 2, "ERROR"); - - refIndex++; - } + if (refIndex >= decl->references.size()) + break; } } } std::string ZFile::ProcessExterns() { - std::string output = ""; + std::string output; - for (std::pair item : declarations) + for (const auto& item : declarations) { - if (item.first < rangeStart || item.first >= rangeEnd) + if (!IsOffsetInFileRange(item.first)) { continue; } - if (!StringHelper::StartsWith(item.second->varType, "static ") && - item.second->varType != "") // && item.second->includePath == "") - { - if (item.second->isArray) - { - if (item.second->arrayItemCnt == 0) - output += - StringHelper::Sprintf("extern %s %s[];\n", item.second->varType.c_str(), - item.second->varName.c_str()); - else - output += StringHelper::Sprintf( - "extern %s %s[%i];\n", item.second->varType.c_str(), - item.second->varName.c_str(), item.second->arrayItemCnt); - } - else - output += StringHelper::Sprintf("extern %s %s;\n", item.second->varType.c_str(), - item.second->varName.c_str()); - } + output += item.second->GetExternStr(); } output += "\n"; @@ -1219,12 +1091,12 @@ std::string ZFile::ProcessExterns() return output; } -std::string ZFile::ProcessTextureIntersections(std::string prefix) +std::string ZFile::ProcessTextureIntersections([[maybe_unused]] const std::string& prefix) { if (texturesResources.empty()) return ""; - std::string defines = ""; + std::string defines; std::vector> texturesSorted(texturesResources.begin(), texturesResources.end()); @@ -1249,11 +1121,13 @@ std::string ZFile::ProcessTextureIntersections(std::string prefix) // Shrink palette so it doesn't overlap currentTex->SetDimensions(offsetDiff / currentTex->GetPixelMultiplyer(), 1); declarations.at(currentOffset)->size = currentTex->GetRawDataSize(); + currentTex->DeclareVar(GetName(), ""); } else { - std::string texName = GetDeclarationPtrName(currentOffset); + std::string texName; std::string texNextName; + GetDeclarationPtrName(currentOffset, "", texName); Declaration* nextDecl = GetDeclaration(nextOffset); if (nextDecl == nullptr) @@ -1264,6 +1138,7 @@ std::string ZFile::ProcessTextureIntersections(std::string prefix) defines += StringHelper::Sprintf("#define %s ((u32)%s + 0x%06X)\n", texNextName.c_str(), texName.c_str(), offsetDiff); + delete declarations[nextOffset]; declarations.erase(nextOffset); texturesResources.erase(nextOffset); texturesSorted.erase(texturesSorted.begin() + i + 1); @@ -1275,3 +1150,155 @@ std::string ZFile::ProcessTextureIntersections(std::string prefix) return defines; } + +void ZFile::HandleUnaccountedData() +{ + uint32_t lastAddr = 0; + uint32_t lastSize = 0; + std::vector declsAddresses; + for (const auto& item : declarations) + { + declsAddresses.push_back(item.first); + } + + bool breakLoop = false; + for (uint32_t currentAddress : declsAddresses) + { + if (currentAddress >= rangeEnd) + { + breakLoop = true; + break; + } + + if (currentAddress < rangeStart) + { + lastAddr = currentAddress; + continue; + } + + breakLoop = HandleUnaccountedAddress(currentAddress, lastAddr, lastSize); + if (breakLoop) + break; + + lastAddr = currentAddress; + } + + if (!breakLoop) + { + // TODO: change rawData.size() to rangeEnd + // HandleUnaccountedAddress(rangeEnd, lastAddr, lastSize); + HandleUnaccountedAddress(rawData.size(), lastAddr, lastSize); + } +} + +bool ZFile::HandleUnaccountedAddress(uint32_t currentAddress, uint32_t lastAddr, uint32_t& lastSize) +{ + if (currentAddress != lastAddr && declarations.find(lastAddr) != declarations.end()) + { + Declaration* lastDecl = declarations.at(lastAddr); + lastSize = lastDecl->size; + + if (lastAddr + lastSize > currentAddress) + { + Declaration* currentDecl = declarations.at(currentAddress); + + fprintf(stderr, + "WARNING: Intersection detected from 0x%06X:0x%06X (%s), conflicts with " + "0x%06X (%s)\n", + lastAddr, lastAddr + lastSize, lastDecl->varName.c_str(), currentAddress, + currentDecl->varName.c_str()); + } + } + + uint32_t unaccountedAddress = lastAddr + lastSize; + + if (unaccountedAddress != currentAddress && lastAddr >= rangeStart && + unaccountedAddress < rangeEnd) + { + int diff = currentAddress - unaccountedAddress; + bool nonZeroUnaccounted = false; + + std::string src = " "; + + if (currentAddress > rawData.size()) + { + throw std::runtime_error(StringHelper::Sprintf( + "ZFile::ProcessDeclarations(): Fatal error while processing XML '%s'.\n" + "\t Offset '0x%X' is outside of the limits of file '%s', which has a size of " + "'0x%X'.\n" + "\t Aborting...", + xmlFilePath.c_str(), currentAddress, name.c_str(), rawData.size())); + } + + for (int i = 0; i < diff; i++) + { + uint8_t val = rawData.at(unaccountedAddress + i); + src += StringHelper::Sprintf("0x%02X, ", val); + if (val != 0x00) + { + nonZeroUnaccounted = true; + } + + if (Globals::Instance->verboseUnaccounted) + { + if ((i % 4 == 3)) + { + src += StringHelper::Sprintf(" // 0x%06X", unaccountedAddress + i - 3); + if (i != (diff - 1)) + { + src += "\n\t"; + } + } + } + else + { + if ((i % 16 == 15) && (i != (diff - 1))) + src += "\n "; + } + } + + if (declarations.find(unaccountedAddress) == declarations.end() && diff > 0) + { + std::string unaccountedPrefix = "unaccounted"; + + if (diff < 16 && !nonZeroUnaccounted) + { + unaccountedPrefix = "possiblePadding"; + + // Strip unnecessary padding at the end of the file. + if (unaccountedAddress + diff >= rawData.size()) + return true; + } + + Declaration* decl = AddDeclarationArray( + unaccountedAddress, DeclarationAlignment::Align4, diff, "u8", + StringHelper::Sprintf("%s_%s_%06X", name.c_str(), unaccountedPrefix.c_str(), + unaccountedAddress), + diff, src); + decl->isUnaccounted = true; + + if (Globals::Instance->warnUnaccounted) + { + if (nonZeroUnaccounted) + { + fprintf(stderr, + "Warning in file: %s (%s)\n" + "\t A non-zero unaccounted block was found at offset '0x%06X'.\n" + "\t Block size: '0x%X'.\n", + xmlFilePath.c_str(), name.c_str(), unaccountedAddress, diff); + } + else if (diff >= 16) + { + fprintf(stderr, + "Warning in file: %s (%s)\n" + "\t A big (size>=0x10) zero-only unaccounted block was found " + "at offset '0x%06X'.\n" + "\t Block size: '0x%X'.\n", + xmlFilePath.c_str(), name.c_str(), unaccountedAddress, diff); + } + } + } + } + + return false; +} diff --git a/tools/ZAPD/ZAPD/ZFile.h b/tools/ZAPD/ZAPD/ZFile.h index 8ea976e8c3..93234761d0 100644 --- a/tools/ZAPD/ZAPD/ZFile.h +++ b/tools/ZAPD/ZAPD/ZFile.h @@ -1,9 +1,10 @@ #pragma once +#include #include #include -#include "Directory.h" -#include "ZResource.h" + +#include "ZSymbol.h" #include "ZTexture.h" #include "tinyxml2.h" @@ -11,13 +12,13 @@ enum class ZFileMode { BuildTexture, BuildOverlay, - BuildModelIntermediette, - BuildAnimationIntermediette, BuildBlob, BuildSourceFile, BuildBackground, Extract, - Invalid + ExternalFile, + Invalid, + Custom = 1000, // Used for exporter file modes }; enum class ZGame @@ -30,19 +31,20 @@ enum class ZGame class ZFile { public: - std::map declarations; + std::map declarations; std::string defines; std::vector resources; uint32_t segment; uint32_t baseAddress, rangeStart, rangeEnd; + bool isExternalFile = false; - ZFile(std::string nName); - ZFile(ZFileMode mode, tinyxml2::XMLElement* reader, const fs::path& nBasePath, - std::string filename, const fs::path& nXmlFilePath, bool placeholderMode); + ZFile(const fs::path& nOutPath, const std::string& nName); + ZFile(ZFileMode nMode, tinyxml2::XMLElement* reader, const fs::path& nBasePath, + const fs::path& nOutPath, const std::string& filename, const fs::path& nXmlFilePath); ~ZFile(); - std::string GetVarName(uint32_t address); std::string GetName() const; + ZFileMode GetMode() const; const fs::path& GetXmlFilePath() const; const std::vector& GetRawData() const; void ExtractResources(); @@ -51,45 +53,54 @@ public: ZResource* FindResource(uint32_t rawDataIndex); std::vector GetResourcesOfType(ZResourceType resType); - Declaration* AddDeclaration(uint32_t address, DeclarationAlignment alignment, size_t size, - std::string varType, std::string varName, std::string body); - Declaration* AddDeclaration(uint32_t address, DeclarationAlignment alignment, - DeclarationPadding padding, size_t size, std::string varType, - std::string varName, std::string body); - Declaration* AddDeclarationArray(uint32_t address, DeclarationAlignment alignment, size_t size, - std::string varType, std::string varName, size_t arrayItemCnt, - std::string body); - Declaration* AddDeclarationArray(uint32_t address, DeclarationAlignment alignment, size_t size, - std::string varType, std::string varName, size_t arrayItemCnt, - std::string body, bool isExternal); - Declaration* AddDeclarationArray(uint32_t address, DeclarationAlignment alignment, size_t size, - std::string varType, std::string varName, - std::string arrayItemCntStr, std::string body); - Declaration* AddDeclarationArray(uint32_t address, DeclarationAlignment alignment, - DeclarationPadding padding, size_t size, std::string varType, - std::string varName, size_t arrayItemCnt, std::string body); - Declaration* AddDeclarationPlaceholder(uint32_t address); - Declaration* AddDeclarationPlaceholder(uint32_t address, std::string varName); - Declaration* AddDeclarationInclude(uint32_t address, std::string includePath, size_t size, - std::string varType, std::string varName); - Declaration* AddDeclarationIncludeArray(uint32_t address, std::string includePath, size_t size, - std::string varType, std::string varName, + Declaration* AddDeclaration(offset_t address, DeclarationAlignment alignment, size_t size, + const std::string& varType, const std::string& varName, + const std::string& body); + + Declaration* AddDeclarationArray(offset_t address, DeclarationAlignment alignment, size_t size, + const std::string& varType, const std::string& varName, + size_t arrayItemCnt, const std::string& body); + Declaration* AddDeclarationArray(offset_t address, DeclarationAlignment alignment, size_t size, + const std::string& varType, const std::string& varName, + const std::string& arrayItemCntStr, const std::string& body); + + Declaration* AddDeclarationPlaceholder(offset_t address, const std::string& varName); + + Declaration* AddDeclarationInclude(offset_t address, const std::string& includePath, + size_t size, const std::string& varType, + const std::string& varName); + Declaration* AddDeclarationIncludeArray(offset_t address, std::string& includePath, size_t size, + const std::string& varType, const std::string& varName, size_t arrayItemCnt); - std::string GetDeclarationName(uint32_t address) const; - std::string GetDeclarationName(uint32_t address, std::string defaultResult) const; - std::string GetDeclarationPtrName(segptr_t segAddress) const; + + bool GetDeclarationPtrName(segptr_t segAddress, const std::string& expectedType, + std::string& declName) const; + bool GetDeclarationArrayIndexedName(segptr_t segAddress, size_t elementSize, + const std::string& expectedType, + std::string& declName) const; + Declaration* GetDeclaration(uint32_t address) const; Declaration* GetDeclarationRanged(uint32_t address) const; - uint32_t GetDeclarationRangedAddress(uint32_t address) const; bool HasDeclaration(uint32_t address); - std::string GetHeaderInclude(); + + std::string GetHeaderInclude() const; + std::string GetZRoomHeaderInclude() const; + std::string GetExternalFileHeaderInclude() const; + void GeneratePlaceholderDeclarations(); void AddTextureResource(uint32_t offset, ZTexture* tex); ZTexture* GetTextureResource(uint32_t offset) const; + void AddSymbolResource(uint32_t offset, ZSymbol* sym); + ZSymbol* GetSymbolResource(uint32_t offset) const; + ZSymbol* GetSymbolResourceRanged(uint32_t offset) const; + fs::path GetSourceOutputFolderPath() const; + bool IsOffsetInFileRange(uint32_t offset) const; + bool IsSegmentedInFilespaceRange(segptr_t segAddress) const; + static std::map* GetNodeMap(); static void RegisterNode(std::string nodeName, ZResourceFactoryFunc* nodeFunc); @@ -98,23 +109,27 @@ protected: std::string name; fs::path outName = ""; fs::path basePath; + fs::path outputPath; fs::path xmlFilePath; + // Keep track of every texture of this ZFile. // The pointers declared here are "borrowed" (somebody else is the owner), // so ZFile shouldn't delete/free those textures. std::map texturesResources; + std::map symbolResources; + ZFileMode mode = ZFileMode::Invalid; ZFile(); - void ParseXML(ZFileMode mode, tinyxml2::XMLElement* reader, std::string filename, - bool placeholderMode); + void ParseXML(tinyxml2::XMLElement* reader, const std::string& filename); void DeclareResourceSubReferences(); - void GenerateSourceFiles(fs::path outputDir); + void GenerateSourceFiles(); void GenerateSourceHeaderFiles(); - void GenerateHLIntermediette(); - void AddDeclarationDebugChecks(uint32_t address); + bool AddDeclarationChecks(uint32_t address, const std::string& varName); std::string ProcessDeclarations(); void ProcessDeclarationText(Declaration* decl); std::string ProcessExterns(); - std::string ProcessTextureIntersections(std::string prefix); + std::string ProcessTextureIntersections(const std::string& prefix); + void HandleUnaccountedData(); + bool HandleUnaccountedAddress(uint32_t currentAddress, uint32_t lastAddr, uint32_t& lastSize); }; diff --git a/tools/ZAPD/ZAPD/ZLimb.cpp b/tools/ZAPD/ZAPD/ZLimb.cpp index ce62bac272..77c66871fe 100644 --- a/tools/ZAPD/ZAPD/ZLimb.cpp +++ b/tools/ZAPD/ZAPD/ZLimb.cpp @@ -1,379 +1,31 @@ #include "ZLimb.h" + #include -#include "BitConverter.h" + #include "Globals.h" -#include "StringHelper.h" +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" REGISTER_ZFILENODE(Limb, ZLimb); -Struct_800A57C0::Struct_800A57C0(const std::vector& rawData, uint32_t fileOffset) +ZLimb::ZLimb(ZFile* nParent) : ZResource(nParent), segmentStruct(nParent) { - unk_0 = BitConverter::ToUInt16BE(rawData, fileOffset + 0x00); - unk_2 = BitConverter::ToInt16BE(rawData, fileOffset + 0x02); - unk_4 = BitConverter::ToInt16BE(rawData, fileOffset + 0x04); - unk_6 = BitConverter::ToInt8BE(rawData, fileOffset + 0x06); - unk_7 = BitConverter::ToInt8BE(rawData, fileOffset + 0x07); - unk_8 = BitConverter::ToInt8BE(rawData, fileOffset + 0x08); - unk_9 = BitConverter::ToUInt8BE(rawData, fileOffset + 0x09); -} -Struct_800A57C0::Struct_800A57C0(const std::vector& rawData, uint32_t fileOffset, - size_t index) - : Struct_800A57C0(rawData, fileOffset + index * GetRawDataSize()) -{ -} - -std::string Struct_800A57C0::GetSourceOutputCode() const -{ - return StringHelper::Sprintf("0x%02X, %i, %i, %i, %i, %i, 0x%02X", unk_0, unk_2, unk_4, unk_6, - unk_7, unk_8, unk_9); -} - -size_t Struct_800A57C0::GetRawDataSize() -{ - return 0x0A; -} - -std::string Struct_800A57C0::GetSourceTypeName() -{ - return "Struct_800A57C0"; -} - -Struct_800A598C_2::Struct_800A598C_2(const std::vector& rawData, uint32_t fileOffset) -{ - unk_0 = BitConverter::ToUInt8BE(rawData, fileOffset + 0x00); - x = BitConverter::ToInt16BE(rawData, fileOffset + 0x02); - y = BitConverter::ToInt16BE(rawData, fileOffset + 0x04); - z = BitConverter::ToInt16BE(rawData, fileOffset + 0x06); - unk_8 = BitConverter::ToUInt8BE(rawData, fileOffset + 0x08); -} -Struct_800A598C_2::Struct_800A598C_2(const std::vector& rawData, uint32_t fileOffset, - size_t index) - : Struct_800A598C_2(rawData, fileOffset + index * GetRawDataSize()) -{ -} - -std::string Struct_800A598C_2::GetSourceOutputCode() const -{ - return StringHelper::Sprintf("0x%02X, %i, %i, %i, 0x%02X", unk_0, x, y, z, unk_8); -} - -size_t Struct_800A598C_2::GetRawDataSize() -{ - return 0x0A; -} - -std::string Struct_800A598C_2::GetSourceTypeName() -{ - return "Struct_800A598C_2"; -} - -Struct_800A598C::Struct_800A598C(ZFile* parent, const std::vector& rawData, - uint32_t fileOffset) - : parent(parent) -{ - unk_0 = BitConverter::ToUInt16BE(rawData, fileOffset + 0x00); - unk_2 = BitConverter::ToUInt16BE(rawData, fileOffset + 0x02); - unk_4 = BitConverter::ToUInt16BE(rawData, fileOffset + 0x04); - unk_8 = BitConverter::ToUInt32BE(rawData, fileOffset + 0x08); - unk_C = BitConverter::ToUInt32BE(rawData, fileOffset + 0x0C); - - if (unk_8 != 0) - { - uint32_t unk_8_Offset = Seg2Filespace(unk_8, parent->baseAddress); - for (size_t i = 0; i < unk_0; i++) - { - unk_8_arr.emplace_back(rawData, unk_8_Offset, i); - } - } - - if (unk_C != 0) - { - uint32_t unk_C_Offset = Seg2Filespace(unk_C, parent->baseAddress); - for (size_t i = 0; i < unk_2; i++) - { - unk_C_arr.emplace_back(rawData, unk_C_Offset, i); - } - } -} -Struct_800A598C::Struct_800A598C(ZFile* parent, const std::vector& rawData, - uint32_t fileOffset, size_t index) - : Struct_800A598C(parent, rawData, fileOffset + index * GetRawDataSize()) -{ -} - -void Struct_800A598C::PreGenSourceFiles(const std::string& prefix) -{ - std::string entryStr; - - if (unk_8 != 0) - { - uint32_t unk_8_Offset = Seg2Filespace(unk_8, parent->baseAddress); - std::string unk_8_Str = - StringHelper::Sprintf("%sSkinLimb_%s_%06X", prefix.c_str(), - Struct_800A57C0::GetSourceTypeName().c_str(), unk_8_Offset); - - size_t arrayItemCnt = unk_8_arr.size(); - entryStr = ""; - size_t i = 0; - - for (auto& child : unk_8_arr) - { - entryStr += StringHelper::Sprintf(" { %s },%s", child.GetSourceOutputCode().c_str(), - (++i < arrayItemCnt) ? "\n" : ""); - } - - Declaration* decl = parent->GetDeclaration(unk_8_Offset); - - if (decl == nullptr) - { - parent->AddDeclarationArray(unk_8_Offset, DeclarationAlignment::None, - arrayItemCnt * Struct_800A57C0::GetRawDataSize(), - Struct_800A57C0::GetSourceTypeName(), unk_8_Str, - arrayItemCnt, entryStr); - } - else - { - decl->text = entryStr; - } - } - - if (unk_C != 0) - { - uint32_t unk_C_Offset = Seg2Filespace(unk_C, parent->baseAddress); - std::string unk_C_Str = - StringHelper::Sprintf("%sSkinLimb_%s_%06X", prefix.c_str(), - Struct_800A598C_2::GetSourceTypeName().c_str(), unk_C_Offset); - - size_t arrayItemCnt = unk_C_arr.size(); - entryStr = ""; - size_t i = 0; - - for (auto& child : unk_C_arr) - { - entryStr += StringHelper::Sprintf(" { %s },%s", child.GetSourceOutputCode().c_str(), - (++i < arrayItemCnt) ? "\n" : ""); - } - - Declaration* decl = parent->GetDeclaration(unk_C_Offset); - if (decl == nullptr) - { - parent->AddDeclarationArray(unk_C_Offset, DeclarationAlignment::None, - arrayItemCnt * Struct_800A598C_2::GetRawDataSize(), - Struct_800A598C_2::GetSourceTypeName(), unk_C_Str, - arrayItemCnt, entryStr); - } - else - { - decl->text = entryStr; - } - } -} - -std::string Struct_800A598C::GetSourceOutputCode(const std::string& prefix) const -{ - std::string entryStr; - - std::string unk_8_Str = "NULL"; - - if (unk_8 != 0) - { - uint32_t unk_8_Offset = Seg2Filespace(unk_8, parent->baseAddress); - unk_8_Str = - StringHelper::Sprintf("%sSkinLimb_%s_%06X", prefix.c_str(), - Struct_800A57C0::GetSourceTypeName().c_str(), unk_8_Offset); - } - - std::string unk_C_Str = "NULL"; - - if (unk_C != 0) - { - uint32_t unk_C_Offset = Seg2Filespace(unk_C, parent->baseAddress); - unk_C_Str = - StringHelper::Sprintf("%sSkinLimb_%s_%06X", prefix.c_str(), - Struct_800A598C_2::GetSourceTypeName().c_str(), unk_C_Offset); - } - - entryStr = StringHelper::Sprintf("\n ARRAY_COUNTU(%s), ARRAY_COUNTU(%s),\n", - unk_8_Str.c_str(), unk_C_Str.c_str()); - entryStr += StringHelper::Sprintf(" %i, %s, %s\n ", unk_4, unk_8_Str.c_str(), - unk_C_Str.c_str()); - entryStr = StringHelper::Sprintf("\n ARRAY_COUNTU(%s), ARRAY_COUNTU(%s),\n", - unk_8_Str.c_str(), unk_C_Str.c_str()); - entryStr += StringHelper::Sprintf(" %i, %s, %s\n ", unk_4, unk_8_Str.c_str(), - unk_C_Str.c_str()); - - return entryStr; -} - -size_t Struct_800A598C::GetRawDataSize() -{ - return 0x10; -} - -std::string Struct_800A598C::GetSourceTypeName() -{ - return "Struct_800A598C"; -} - -Struct_800A5E28::Struct_800A5E28(ZFile* parent, const std::vector& nRawData, - uint32_t fileOffset) - : parent(parent) -{ - unk_0 = BitConverter::ToUInt16BE(nRawData, fileOffset + 0x00); - unk_2 = BitConverter::ToUInt16BE(nRawData, fileOffset + 0x02); - unk_4 = BitConverter::ToUInt32BE(nRawData, fileOffset + 0x04); - unk_8 = BitConverter::ToUInt32BE(nRawData, fileOffset + 0x08); - - if (unk_4 != 0) - { - uint32_t unk_4_Offset = Seg2Filespace(unk_4, parent->baseAddress); - - for (size_t i = 0; i < unk_2; i++) - { - unk_4_arr.emplace_back(parent, nRawData, unk_4_Offset, i); - } - } -} - -Struct_800A5E28::~Struct_800A5E28() -{ - delete unk_8_dlist; -} - -void Struct_800A5E28::PreGenSourceFiles(const std::string& prefix) -{ - if (unk_4 != 0) - { - uint32_t unk_4_Offset = Seg2Filespace(unk_4, parent->baseAddress); - std::string unk_4_Str = - StringHelper::Sprintf("%sSkinLimb_%s_%06X", prefix.c_str(), - Struct_800A598C::GetSourceTypeName().c_str(), unk_4_Offset); - - std::string entryStr = ""; - uint16_t arrayItemCnt = unk_4_arr.size(); - - size_t i = 0; - - for (auto& child : unk_4_arr) - { - child.PreGenSourceFiles(prefix); - entryStr += - StringHelper::Sprintf(" { %s },%s", child.GetSourceOutputCode(prefix).c_str(), - (++i < arrayItemCnt) ? "\n" : ""); - } - - Declaration* decl = parent->GetDeclaration(unk_4_Offset); - - if (decl == nullptr) - { - parent->AddDeclarationArray(unk_4_Offset, DeclarationAlignment::None, - arrayItemCnt * Struct_800A598C::GetRawDataSize(), - Struct_800A598C::GetSourceTypeName(), unk_4_Str, - arrayItemCnt, entryStr); - } - else - { - decl->text = entryStr; - } - } - - if (unk_8 != 0) - { - uint32_t unk_8_Offset = Seg2Filespace(unk_8, parent->baseAddress); - - int32_t dlistLength = ZDisplayList::GetDListLength( - parent->GetRawData(), unk_8_Offset, - Globals::Instance->game == ZGame::OOT_SW97 ? DListType::F3DEX : DListType::F3DZEX); - unk_8_dlist = new ZDisplayList(unk_8_Offset, dlistLength, parent); - - std::string dListStr = - StringHelper::Sprintf("%sSkinLimbDL_%06X", prefix.c_str(), unk_8_Offset); - unk_8_dlist->SetName(dListStr); - unk_8_dlist->GetSourceOutputCode(prefix); - } -} - -std::string Struct_800A5E28::GetSourceOutputCode(const std::string& prefix) const -{ - std::string entryStr = ""; - - std::string unk_4_Str = "NULL"; - - if (unk_4 != 0) - { - uint32_t unk_4_Offset = Seg2Filespace(unk_4, parent->baseAddress); - Declaration* decl = parent->GetDeclaration(unk_4_Offset); - - if (decl == nullptr) - { - unk_4_Str = - StringHelper::Sprintf("%sSkinLimb_%s_%06X", prefix.c_str(), - Struct_800A598C::GetSourceTypeName().c_str(), unk_4_Offset); - } - else - { - unk_4_Str = decl->varName; - } - } - - std::string unk_8_Str = "NULL"; - if (unk_8 != 0) - { - uint32_t unk_8_Offset = Seg2Filespace(unk_8, parent->baseAddress); - Declaration* decl = parent->GetDeclaration(unk_8_Offset); - if (decl == nullptr) - { - // Something went wrong... - unk_8_Str = StringHelper::Sprintf("0x%08X", unk_8); - } - else - { - unk_8_Str = decl->varName; - } - } - - return StringHelper::Sprintf("\n %i, ARRAY_COUNTU(%s),\n %s, %s\n", unk_0, - unk_4_Str.c_str(), unk_4_Str.c_str(), unk_8_Str.c_str()); -} - -size_t Struct_800A5E28::GetRawDataSize() -{ - return 0x0C; -} - -std::string Struct_800A5E28::GetSourceTypeName() -{ - return "Struct_800A5E28"; -} - -ZLimb::ZLimb(ZFile* nParent) : ZResource(nParent) -{ - dListPtr = 0; - dList2Ptr = 0; RegisterOptionalAttribute("LimbType"); RegisterOptionalAttribute("Type"); } -ZLimb::ZLimb(ZLimbType limbType, const std::string& prefix, uint32_t nRawDataIndex, ZFile* nParent) - : ZLimb(nParent) +void ZLimb::ExtractFromBinary(uint32_t nRawDataIndex, ZLimbType nType) { rawDataIndex = nRawDataIndex; - parent = nParent; - type = limbType; + type = nType; - name = StringHelper::Sprintf("%sLimb_%06X", prefix.c_str(), GetFileAddress()); + // Don't parse raw data of external files + if (parent->GetMode() == ZFileMode::ExternalFile) + return; ParseRawData(); } -void ZLimb::ExtractFromXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex) -{ - ZResource::ExtractFromXML(reader, nRawDataIndex); - - parent->AddDeclaration(GetFileAddress(), DeclarationAlignment::None, GetRawDataSize(), - GetSourceTypeName(), name, ""); -} - void ZLimb::ParseXML(tinyxml2::XMLElement* reader) { ZResource::ParseXML(reader); @@ -385,37 +37,29 @@ void ZLimb::ParseXML(tinyxml2::XMLElement* reader) if (limbType == "") { - fprintf(stderr, - "ZLimb::ParseXML: Warning in '%s'.\n" - "\t Missing 'LimbType' attribute in xml.\n" - "\t Defaulting to 'Standard'.\n", - name.c_str()); - type = ZLimbType::Standard; + throw std::runtime_error(StringHelper::Sprintf("ZLimb::ParseXML: Error in '%s'.\n" + "\t Missing 'LimbType' attribute in xml.\n", + name.c_str())); } - else + + type = GetTypeByAttributeName(limbType); + if (type == ZLimbType::Invalid) { - type = GetTypeByAttributeName(limbType); - if (type == ZLimbType::Invalid) - { - fprintf(stderr, - "ZLimb::ParseXML: Warning in '%s'.\n" - "\t Invalid LimbType found: '%s'.\n" - "\t Defaulting to 'Standard'.\n", - name.c_str(), limbType.c_str()); - type = ZLimbType::Standard; - } + throw std::runtime_error(StringHelper::Sprintf("ZLimb::ParseXML: Error in '%s'.\n" + "\t Invalid 'LimbType' found: '%s'.\n", + name.c_str(), limbType.c_str())); } } void ZLimb::ParseRawData() { ZResource::ParseRawData(); - const auto& rawData = parent->GetRawData(); + if (type == ZLimbType::Curve) { - childIndex = rawData.at(rawDataIndex + 0); - siblingIndex = rawData.at(rawDataIndex + 1); + childIndex = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0); + siblingIndex = BitConverter::ToUInt8BE(rawData, rawDataIndex + 1); dListPtr = BitConverter::ToUInt32BE(rawData, rawDataIndex + 4); dList2Ptr = BitConverter::ToUInt32BE(rawData, rawDataIndex + 8); @@ -446,7 +90,7 @@ void ZLimb::ParseRawData() { case ZLimbType::LOD: dList2Ptr = BitConverter::ToUInt32BE(rawData, rawDataIndex + 12); - // Intended fallthrough + [[fallthrough]]; case ZLimbType::Standard: dListPtr = BitConverter::ToUInt32BE(rawData, rawDataIndex + 8); break; @@ -455,12 +99,16 @@ void ZLimb::ParseRawData() skinSegmentType = static_cast(BitConverter::ToInt32BE(rawData, rawDataIndex + 8)); skinSegment = BitConverter::ToUInt32BE(rawData, rawDataIndex + 12); - if (skinSegmentType == ZLimbSkinType::SkinType_4 && skinSegment != 0) + if (skinSegmentType == ZLimbSkinType::SkinType_4) { - uint32_t skinSegmentOffset = Seg2Filespace(skinSegment, parent->baseAddress); - segmentStruct = Struct_800A5E28(parent, rawData, skinSegmentOffset); + if (skinSegment != 0 && GETSEGNUM(skinSegment) == parent->segment) + { + uint32_t skinSegmentOffset = Seg2Filespace(skinSegment, parent->baseAddress); + segmentStruct.ExtractFromFile(skinSegmentOffset); + } } break; + default: throw std::runtime_error("Invalid ZLimb type"); break; @@ -469,8 +117,13 @@ void ZLimb::ParseRawData() void ZLimb::DeclareReferences(const std::string& prefix) { - ZResource::DeclareReferences(prefix); + std::string varPrefix = name; + if (varPrefix == "") + varPrefix = prefix; + ZResource::DeclareReferences(varPrefix); + + std::string suffix; switch (type) { case ZLimbType::Legacy: @@ -479,8 +132,10 @@ void ZLimb::DeclareReferences(const std::string& prefix) uint32_t childOffset = Seg2Filespace(childPtr, parent->baseAddress); if (!parent->HasDeclaration(childOffset)) { - ZLimb* child = new ZLimb(ZLimbType::Legacy, prefix, childOffset, parent); - child->GetSourceOutputCode(prefix); + ZLimb* child = new ZLimb(parent); + child->ExtractFromBinary(childOffset, ZLimbType::Legacy); + child->DeclareVar(varPrefix, ""); + child->DeclareReferences(varPrefix); parent->AddResource(child); } } @@ -489,18 +144,47 @@ void ZLimb::DeclareReferences(const std::string& prefix) uint32_t siblingdOffset = Seg2Filespace(siblingPtr, parent->baseAddress); if (!parent->HasDeclaration(siblingdOffset)) { - ZLimb* sibling = new ZLimb(ZLimbType::Legacy, prefix, siblingdOffset, parent); - sibling->GetSourceOutputCode(prefix); + ZLimb* sibling = new ZLimb(parent); + sibling->ExtractFromBinary(siblingdOffset, ZLimbType::Legacy); + sibling->DeclareVar(varPrefix, ""); + sibling->DeclareReferences(varPrefix); parent->AddResource(sibling); } } break; - // TODO - case ZLimbType::Standard: - case ZLimbType::LOD: - case ZLimbType::Skin: case ZLimbType::Curve: + case ZLimbType::LOD: + suffix = "Far"; + if (type == ZLimbType::Curve) + suffix = "Curve2"; + DeclareDList(dList2Ptr, varPrefix, suffix); + [[fallthrough]]; + case ZLimbType::Standard: + suffix = ""; + if (type == ZLimbType::Curve) + suffix = "Curve"; + DeclareDList(dListPtr, varPrefix, suffix); + break; + + case ZLimbType::Skin: + switch (skinSegmentType) + { + case ZLimbSkinType::SkinType_4: + if (skinSegment != 0 && GETSEGNUM(skinSegment) == parent->segment) + { + segmentStruct.DeclareReferences(varPrefix); + segmentStruct.GetSourceOutputCode(varPrefix); + } + break; + + case ZLimbSkinType::SkinType_DList: + DeclareDList(skinSegment, varPrefix, ""); + break; + + default: + break; + } break; case ZLimbType::Invalid: @@ -530,18 +214,20 @@ size_t ZLimb::GetRawDataSize() const return 0x0C; } -std::string ZLimb::GetSourceOutputCode(const std::string& prefix) +std::string ZLimb::GetBodySourceCode() const { - std::string limbPrefix = type == ZLimbType::Curve ? "Curve" : ""; - std::string dListStr = GetLimbDListSourceOutputCode(prefix, limbPrefix, dListPtr); - limbPrefix = type == ZLimbType::Curve ? "Curve" : "Far"; - std::string dListStr2 = GetLimbDListSourceOutputCode(prefix, limbPrefix, dList2Ptr); + std::string dListStr; + std::string dListStr2; + Globals::Instance->GetSegmentedArrayIndexedName(dListPtr, 8, parent, "Gfx", dListStr); + Globals::Instance->GetSegmentedArrayIndexedName(dList2Ptr, 8, parent, "Gfx", dListStr2); std::string entryStr = "\n\t"; if (type == ZLimbType::Legacy) { - std::string childName = parent->GetDeclarationPtrName(childPtr); - std::string siblingName = parent->GetDeclarationPtrName(siblingPtr); + std::string childName; + std::string siblingName; + Globals::Instance->GetSegmentedPtrName(childPtr, parent, "Gfx", childName); + Globals::Instance->GetSegmentedPtrName(siblingPtr, parent, "Gfx", siblingName); entryStr += StringHelper::Sprintf("%s,\n", dListStr.c_str()); entryStr += @@ -556,24 +242,28 @@ std::string ZLimb::GetSourceOutputCode(const std::string& prefix) { entryStr += StringHelper::Sprintf("{ %i, %i, %i }, ", transX, transY, transZ); } - entryStr += StringHelper::Sprintf("0x%02X, 0x%02X,\n", childIndex, siblingIndex); switch (type) { case ZLimbType::Standard: - entryStr += StringHelper::Sprintf(" %s\n", dListStr.c_str()); + entryStr += StringHelper::Sprintf("\t%s\n", dListStr.c_str()); break; case ZLimbType::LOD: case ZLimbType::Curve: entryStr += - StringHelper::Sprintf(" { %s, %s }\n", dListStr.c_str(), dListStr2.c_str()); + StringHelper::Sprintf("\t{ %s, %s }\n", dListStr.c_str(), dListStr2.c_str()); break; case ZLimbType::Skin: - entryStr += GetSourceOutputCodeSkin(prefix); - break; + { + std::string skinSegmentStr; + Globals::Instance->GetSegmentedPtrName(skinSegment, parent, "", skinSegmentStr); + entryStr += + StringHelper::Sprintf("\t0x%02X, %s\n", skinSegmentType, skinSegmentStr.c_str()); + } + break; case ZLimbType::Legacy: break; @@ -583,15 +273,12 @@ std::string ZLimb::GetSourceOutputCode(const std::string& prefix) } } - Declaration* decl = parent->GetDeclaration(GetFileAddress()); + return entryStr; +} - if (decl == nullptr) - parent->AddDeclaration(GetFileAddress(), DeclarationAlignment::None, GetRawDataSize(), - GetSourceTypeName(), name, entryStr); - else - decl->text = entryStr; - - return ""; +std::string ZLimb::GetDefaultName(const std::string& prefix) const +{ + return StringHelper::Sprintf("%sLimb_%06X", prefix.c_str(), rawDataIndex); } std::string ZLimb::GetSourceTypeName() const @@ -663,126 +350,34 @@ ZLimbType ZLimb::GetTypeByAttributeName(const std::string& attrName) return ZLimbType::Invalid; } -uint32_t ZLimb::GetFileAddress() +void ZLimb::DeclareDList(segptr_t dListSegmentedPtr, const std::string& prefix, + const std::string& limbSuffix) { - return Seg2Filespace(rawDataIndex, parent->baseAddress); -} + if (dListSegmentedPtr == 0 || GETSEGNUM(dListSegmentedPtr) != parent->segment) + return; -// Returns the ptrname of a dlist. Declares it if it has not been declared yet. -std::string ZLimb::GetLimbDListSourceOutputCode(const std::string& prefix, - const std::string& limbPrefix, segptr_t dListPtr) -{ - if (dListPtr == 0) - return "NULL"; + uint32_t dlistOffset = Seg2Filespace(dListSegmentedPtr, parent->baseAddress); + if (parent->HasDeclaration(dlistOffset)) + return; - uint32_t dListOffset = Seg2Filespace(dListPtr, parent->baseAddress); + if (!parent->IsOffsetInFileRange(dlistOffset) || dlistOffset >= parent->GetRawData().size()) + return; - // Check if pointing past the object's size - if (dListOffset > parent->GetRawData().size()) - return StringHelper::Sprintf("0x%08X", dListPtr); - - // Check if it is already declared - Declaration* decl = parent->GetDeclaration(dListOffset); - if (decl != nullptr) - return decl->varName; - - // Check if it points to the middle of a DList - decl = parent->GetDeclarationRanged(dListOffset); - if (decl != nullptr) - { - // TODO: Figure out a way to not hardcode the "Gfx" type. - if (decl->varType == "Gfx") - { - uint32_t declAddress = parent->GetDeclarationRangedAddress(dListOffset); - if (dListOffset < declAddress + decl->size) - { - uint32_t index = (dListOffset - declAddress) / 8; - return StringHelper::Sprintf("&%s[%u]", decl->varName.c_str(), index); - } - } - } - - // Create the DList - std::string dListStr = - StringHelper::Sprintf("%s%sLimbDL_%06X", prefix.c_str(), limbPrefix.c_str(), dListOffset); + std::string dlistName; + bool declFound = Globals::Instance->GetSegmentedArrayIndexedName(dListSegmentedPtr, 8, parent, + "Gfx", dlistName); + if (declFound) + return; int32_t dlistLength = ZDisplayList::GetDListLength( - parent->GetRawData(), dListOffset, + parent->GetRawData(), dlistOffset, Globals::Instance->game == ZGame::OOT_SW97 ? DListType::F3DEX : DListType::F3DZEX); - auto dList = new ZDisplayList(dListOffset, dlistLength, parent); - dList->SetName(dListStr); - dList->GetSourceOutputCode(prefix); - return dListStr; -} - -std::string ZLimb::GetSourceOutputCodeSkin_Type_4(const std::string& prefix) -{ - assert(type == ZLimbType::Skin); - assert(skinSegmentType == ZLimbSkinType::SkinType_4); - - if (skinSegment == 0) - return "NULL"; - - uint32_t skinSegmentOffset = Seg2Filespace(skinSegment, parent->baseAddress); - - std::string struct_800A5E28_Str; - Declaration* decl = parent->GetDeclaration(skinSegmentOffset); - if (decl == nullptr) - { - struct_800A5E28_Str = - StringHelper::Sprintf("%sSkinLimb_%s_%06X", prefix.c_str(), - Struct_800A5E28::GetSourceTypeName().c_str(), skinSegmentOffset); - - segmentStruct.PreGenSourceFiles(prefix); - std::string entryStr = segmentStruct.GetSourceOutputCode(prefix); - - parent->AddDeclaration(skinSegmentOffset, DeclarationAlignment::None, - Struct_800A5E28::GetRawDataSize(), - Struct_800A5E28::GetSourceTypeName(), struct_800A5E28_Str, entryStr); - } - else - { - struct_800A5E28_Str = decl->varName; - } - - return struct_800A5E28_Str; -} - -std::string ZLimb::GetSourceOutputCodeSkin(const std::string& prefix) -{ - assert(type == ZLimbType::Skin); - - std::string skinSegmentStr = "NULL"; - - if (skinSegment != 0) - { - switch (skinSegmentType) - { - case ZLimbSkinType::SkinType_4: - skinSegmentStr = "&" + GetSourceOutputCodeSkin_Type_4(prefix); - break; - case ZLimbSkinType::SkinType_DList: - skinSegmentStr = GetLimbDListSourceOutputCode(prefix, "Skin", skinSegment); - break; - default: - fprintf(stderr, - "ZLimb::GetSourceOutputCodeSkinType: Error in '%s'.\n\t Unknown segment type " - "for SkinLimb: '%i'. \n\tPlease report this.\n", - name.c_str(), static_cast(skinSegmentType)); - break; - case ZLimbSkinType::SkinType_0: - case ZLimbSkinType::SkinType_5: - fprintf(stderr, - "ZLimb::GetSourceOutputCodeSkinType: Error in '%s'.\n\t Segment type for " - "SkinLimb not implemented: '%i'.\n", - name.c_str(), static_cast(skinSegmentType)); - skinSegmentStr = StringHelper::Sprintf("0x%08X", skinSegment); - break; - } - } - - std::string entryStr = - StringHelper::Sprintf(" 0x%02X, %s\n", skinSegmentType, skinSegmentStr.c_str()); - - return entryStr; + ZDisplayList* dlist = new ZDisplayList(parent); + dlist->ExtractFromBinary(dlistOffset, dlistLength); + + std::string dListStr = + StringHelper::Sprintf("%s%sDL_%06X", prefix.c_str(), limbSuffix.c_str(), dlistOffset); + dlist->SetName(dListStr); + dlist->DeclareVar(prefix, ""); + parent->AddResource(dlist); } diff --git a/tools/ZAPD/ZAPD/ZLimb.h b/tools/ZAPD/ZAPD/ZLimb.h index ac9f17d838..53a4143292 100644 --- a/tools/ZAPD/ZAPD/ZLimb.h +++ b/tools/ZAPD/ZAPD/ZLimb.h @@ -3,6 +3,8 @@ #include #include #include + +#include "OtherStructs/SkinLimbStructs.h" #include "ZDisplayList.h" #include "ZFile.h" @@ -16,117 +18,14 @@ enum class ZLimbType Legacy, }; -// TODO: check if more types exists -enum class ZLimbSkinType -{ - SkinType_0, // Segment = 0 - SkinType_4 = 4, // Segment = segmented address // Struct_800A5E28 - SkinType_5 = 5, // Segment = 0 - SkinType_DList = 11, // Segment = DList address -}; - -class Struct_800A57C0 -{ -protected: - uint16_t unk_0; - int16_t unk_2; - int16_t unk_4; - int8_t unk_6; - int8_t unk_7; - int8_t unk_8; - uint8_t unk_9; - -public: - Struct_800A57C0(const std::vector& rawData, uint32_t fileOffset); - Struct_800A57C0(const std::vector& rawData, uint32_t fileOffset, size_t index); - - [[nodiscard]] std::string GetSourceOutputCode() const; - - static size_t GetRawDataSize(); - static std::string GetSourceTypeName(); -}; - -class Struct_800A598C_2 -{ -protected: - uint8_t unk_0; - int16_t x; - int16_t y; - int16_t z; - uint8_t unk_8; - -public: - Struct_800A598C_2(const std::vector& rawData, uint32_t fileOffset); - Struct_800A598C_2(const std::vector& rawData, uint32_t fileOffset, size_t index); - - [[nodiscard]] std::string GetSourceOutputCode() const; - - static size_t GetRawDataSize(); - static std::string GetSourceTypeName(); -}; - -class Struct_800A598C -{ -protected: - ZFile* parent; - - uint16_t unk_0; // Length of unk_8 - uint16_t unk_2; // Length of unk_C - uint16_t unk_4; // 0 or 1 // Used as an index for unk_C - segptr_t unk_8; // Struct_800A57C0* - segptr_t unk_C; // Struct_800A598C_2* - - std::vector unk_8_arr; - std::vector unk_C_arr; - -public: - Struct_800A598C(ZFile* parent, const std::vector& rawData, uint32_t fileOffset); - Struct_800A598C(ZFile* parent, const std::vector& rawData, uint32_t fileOffset, - size_t index); - - void PreGenSourceFiles(const std::string& prefix); - [[nodiscard]] std::string GetSourceOutputCode(const std::string& prefix) const; - - static size_t GetRawDataSize(); - static std::string GetSourceTypeName(); -}; - -class Struct_800A5E28 -{ -protected: - ZFile* parent; - - uint16_t unk_0; // Vtx count - uint16_t unk_2; // Length of unk_4 - segptr_t unk_4; // Struct_800A598C* - segptr_t unk_8; // Gfx* - - std::vector unk_4_arr; - ZDisplayList* unk_8_dlist = nullptr; - -public: - Struct_800A5E28() = default; - Struct_800A5E28(ZFile* parent, const std::vector& rawData, uint32_t fileOffset); - Struct_800A5E28(ZFile* parent, const std::vector& rawData, uint32_t fileOffset, - size_t index); - ~Struct_800A5E28(); - - void PreGenSourceFiles(const std::string& prefix); - [[nodiscard]] std::string GetSourceOutputCode(const std::string& prefix) const; - - static size_t GetRawDataSize(); - static std::string GetSourceTypeName(); -}; - class ZLimb : public ZResource { -protected: +public: ZLimbType type = ZLimbType::Standard; ZLimbSkinType skinSegmentType = ZLimbSkinType::SkinType_0; // Skin only segptr_t skinSegment = 0; // Skin only Struct_800A5E28 segmentStruct; // Skin only - segptr_t dList2Ptr; // LOD and Curve Only // Legacy only float legTransX, legTransY, legTransZ; // Vec3f @@ -134,29 +33,24 @@ protected: segptr_t childPtr; // LegacyLimb* segptr_t siblingPtr; // LegacyLimb* - std::string GetLimbDListSourceOutputCode(const std::string& prefix, - const std::string& limbPrefix, segptr_t dListPtr); - - std::string GetSourceOutputCodeSkin(const std::string& prefix); - std::string GetSourceOutputCodeSkin_Type_4(const std::string& prefix); - -public: segptr_t dListPtr = 0; - segptr_t farDListPtr = 0; // LOD only + segptr_t dList2Ptr = 0; // LOD and Curve Only + int16_t transX, transY, transZ; uint8_t childIndex, siblingIndex; ZLimb(ZFile* nParent); - ZLimb(ZLimbType limbType, const std::string& prefix, uint32_t nRawDataIndex, ZFile* nParent); - void ExtractFromXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex) override; + void ExtractFromBinary(uint32_t nRawDataIndex, ZLimbType nType); void ParseXML(tinyxml2::XMLElement* reader) override; void ParseRawData() override; void DeclareReferences(const std::string& prefix) override; + std::string GetBodySourceCode() const override; + std::string GetDefaultName(const std::string& prefix) const override; + size_t GetRawDataSize() const override; - std::string GetSourceOutputCode(const std::string& prefix) override; std::string GetSourceTypeName() const override; ZResourceType GetResourceType() const override; @@ -165,6 +59,7 @@ public: static const char* GetSourceTypeName(ZLimbType limbType); static ZLimbType GetTypeByAttributeName(const std::string& attrName); - uint32_t GetFileAddress(); - void SetFileAddress(uint32_t nAddress); +protected: + void DeclareDList(segptr_t dListSegmentedPtr, const std::string& prefix, + const std::string& limbSuffix); }; diff --git a/tools/ZAPD/ZAPD/ZMtx.cpp b/tools/ZAPD/ZAPD/ZMtx.cpp index f92506cede..b9ca3f22d2 100644 --- a/tools/ZAPD/ZAPD/ZMtx.cpp +++ b/tools/ZAPD/ZAPD/ZMtx.cpp @@ -1,6 +1,7 @@ #include "ZMtx.h" -#include "BitConverter.h" -#include "StringHelper.h" + +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" #include "ZFile.h" REGISTER_ZFILENODE(Mtx, ZMtx); @@ -9,13 +10,6 @@ ZMtx::ZMtx(ZFile* nParent) : ZResource(nParent) { } -ZMtx::ZMtx(const std::string& prefix, uint32_t nRawDataIndex, ZFile* nParent) : ZResource(nParent) -{ - name = GetDefaultName(prefix.c_str(), rawDataIndex); - ExtractFromFile(nRawDataIndex); - DeclareVar("", ""); -} - void ZMtx::ParseRawData() { ZResource::ParseRawData(); @@ -26,29 +20,12 @@ void ZMtx::ParseRawData() mtx[i][j] = BitConverter::ToInt32BE(rawData, rawDataIndex + (i * 4 + j) * 4); } -void ZMtx::ExtractFromXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex) -{ - ZResource::ExtractFromXML(reader, nRawDataIndex); - DeclareVar("", ""); -} - size_t ZMtx::GetRawDataSize() const { return 64; } -void ZMtx::DeclareVar(const std::string& prefix, const std::string& bodyStr) const -{ - std::string auxName = name; - - if (name == "") - auxName = GetDefaultName(prefix, rawDataIndex); - - parent->AddDeclaration(rawDataIndex, DeclarationAlignment::Align8, GetRawDataSize(), - GetSourceTypeName(), auxName, bodyStr); -} - -std::string ZMtx::GetBodySourceCode() +std::string ZMtx::GetBodySourceCode() const { std::string bodyStr = "\n"; @@ -65,25 +42,6 @@ std::string ZMtx::GetBodySourceCode() return bodyStr; } -std::string ZMtx::GetSourceOutputCode(const std::string& prefix) -{ - std::string bodyStr = GetBodySourceCode(); - - Declaration* decl = parent->GetDeclaration(rawDataIndex); - - if (decl == nullptr) - DeclareVar(prefix, bodyStr); - else - decl->text = bodyStr; - - return ""; -} - -std::string ZMtx::GetDefaultName(const std::string& prefix, uint32_t address) -{ - return StringHelper::Sprintf("%sMtx_%06X", prefix.c_str(), address); -} - std::string ZMtx::GetSourceTypeName() const { return "Mtx"; @@ -93,3 +51,8 @@ ZResourceType ZMtx::GetResourceType() const { return ZResourceType::Mtx; } + +DeclarationAlignment ZMtx::GetDeclarationAlignment() const +{ + return DeclarationAlignment::Align8; +} diff --git a/tools/ZAPD/ZAPD/ZMtx.h b/tools/ZAPD/ZAPD/ZMtx.h index 7a98650efb..eed502374b 100644 --- a/tools/ZAPD/ZAPD/ZMtx.h +++ b/tools/ZAPD/ZAPD/ZMtx.h @@ -8,22 +8,17 @@ class ZMtx : public ZResource { public: ZMtx(ZFile* nParent); - ZMtx(const std::string& prefix, uint32_t nRawDataIndex, ZFile* nParent); void ParseRawData() override; - void ExtractFromXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex) override; - size_t GetRawDataSize() const override; - - void DeclareVar(const std::string& prefix, const std::string& bodyStr) const; - - std::string GetBodySourceCode(); - std::string GetSourceOutputCode(const std::string& prefix) override; - static std::string GetDefaultName(const std::string& prefix, uint32_t address); + std::string GetBodySourceCode() const override; std::string GetSourceTypeName() const override; ZResourceType GetResourceType() const override; + size_t GetRawDataSize() const override; + DeclarationAlignment GetDeclarationAlignment() const override; + protected: std::array, 4> mtx; }; diff --git a/tools/ZAPD/ZAPD/ZPath.cpp b/tools/ZAPD/ZAPD/ZPath.cpp index 890fa5e58d..4a95c5b91e 100644 --- a/tools/ZAPD/ZAPD/ZPath.cpp +++ b/tools/ZAPD/ZAPD/ZPath.cpp @@ -1,8 +1,8 @@ #include "ZPath.h" -#include "BitConverter.h" #include "Globals.h" -#include "StringHelper.h" +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" #include "ZFile.h" REGISTER_ZFILENODE(Path, ZPath); @@ -13,14 +13,6 @@ ZPath::ZPath(ZFile* nParent) : ZResource(nParent) RegisterOptionalAttribute("NumPaths", "1"); } -void ZPath::ExtractFromXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex) -{ - ZResource::ExtractFromXML(reader, nRawDataIndex); - - parent->AddDeclarationArray(rawDataIndex, DeclarationAlignment::Align4, pathways.size() * 8, - GetSourceTypeName(), name, pathways.size(), ""); -} - void ZPath::ParseXML(tinyxml2::XMLElement* reader) { ZResource::ParseXML(reader); @@ -43,8 +35,7 @@ void ZPath::ParseRawData() for (size_t pathIndex = 0; pathIndex < numPaths; pathIndex++) { PathwayEntry path(parent); - path.SetRawDataIndex(currentPtr); - path.ParseRawData(); + path.ExtractFromFile(currentPtr); if (path.GetListAddress() == 0) break; @@ -62,9 +53,23 @@ void ZPath::DeclareReferences(const std::string& prefix) entry.DeclareReferences(prefix); } +Declaration* ZPath::DeclareVar(const std::string& prefix, const std::string& bodyStr) +{ + std::string auxName = name; + + if (name == "") + auxName = GetDefaultName(prefix); + + Declaration* decl = + parent->AddDeclarationArray(rawDataIndex, GetDeclarationAlignment(), GetRawDataSize(), + GetSourceTypeName(), name, pathways.size(), bodyStr); + decl->staticConf = staticConf; + return decl; +} + std::string ZPath::GetBodySourceCode() const { - std::string declaration = ""; + std::string declaration; size_t index = 0; for (const auto& entry : pathways) @@ -80,20 +85,6 @@ std::string ZPath::GetBodySourceCode() const return declaration; } -std::string ZPath::GetSourceOutputCode(const std::string& prefix) -{ - std::string declaration = GetBodySourceCode(); - - Declaration* decl = parent->GetDeclaration(rawDataIndex); - if (decl == nullptr || decl->isPlaceholder) - parent->AddDeclarationArray(rawDataIndex, DeclarationAlignment::Align4, pathways.size() * 8, - GetSourceTypeName(), name, pathways.size(), declaration); - else - decl->text = declaration; - - return ""; -} - std::string ZPath::GetSourceTypeName() const { return "Path"; @@ -134,10 +125,7 @@ void PathwayEntry::ParseRawData() for (int32_t i = 0; i < numPoints; i++) { ZVector vec(parent); - vec.SetRawDataIndex(currentPtr); - vec.SetScalarType(ZScalarType::ZSCALAR_S16); - vec.SetDimensions(3); - vec.ParseRawData(); + vec.ExtractFromBinary(currentPtr, ZScalarType::ZSCALAR_S16, 3); currentPtr += vec.GetRawDataSize(); points.push_back(vec); @@ -150,12 +138,18 @@ void PathwayEntry::DeclareReferences(const std::string& prefix) if (points.empty()) return; - std::string declaration = ""; + std::string pointsName; + bool addressFound = + Globals::Instance->GetSegmentedPtrName(listSegmentAddress, parent, "Vec3s", pointsName); + if (addressFound) + return; + + std::string declaration; size_t index = 0; for (const auto& point : points) { - declaration += StringHelper::Sprintf("\t%s,", point.GetBodySourceCode().c_str()); + declaration += StringHelper::Sprintf("\t{ %s },", point.GetBodySourceCode().c_str()); if (index < points.size() - 1) declaration += "\n"; @@ -163,14 +157,13 @@ void PathwayEntry::DeclareReferences(const std::string& prefix) index++; } - Declaration* decl = parent->GetDeclaration(GETSEGOFFSET(listSegmentAddress)); + uint32_t pointsOffset = Seg2Filespace(listSegmentAddress, parent->baseAddress); + Declaration* decl = parent->GetDeclaration(pointsOffset); if (decl == nullptr) { - parent->AddDeclarationArray(GETSEGOFFSET(listSegmentAddress), DeclarationAlignment::Align4, - DeclarationPadding::Pad4, points.size() * 6, - points.at(0).GetSourceTypeName(), - StringHelper::Sprintf("%sPathwayList0x%06X", prefix.c_str(), - GETSEGOFFSET(listSegmentAddress)), + pointsName = StringHelper::Sprintf("%sPathwayList_%06X", prefix.c_str(), pointsOffset); + parent->AddDeclarationArray(pointsOffset, points.at(0).GetDeclarationAlignment(), + points.size() * 6, points.at(0).GetSourceTypeName(), pointsName, points.size(), declaration); } else @@ -179,8 +172,9 @@ void PathwayEntry::DeclareReferences(const std::string& prefix) std::string PathwayEntry::GetBodySourceCode() const { - std::string declaration = ""; - std::string listName = parent->GetDeclarationPtrName(listSegmentAddress); + std::string declaration; + std::string listName; + Globals::Instance->GetSegmentedPtrName(listSegmentAddress, parent, "Vec3s", listName); if (Globals::Instance->game == ZGame::MM_RETAIL) declaration += diff --git a/tools/ZAPD/ZAPD/ZPath.h b/tools/ZAPD/ZAPD/ZPath.h index 23e2933e61..e519decff4 100644 --- a/tools/ZAPD/ZAPD/ZPath.h +++ b/tools/ZAPD/ZAPD/ZPath.h @@ -11,12 +11,12 @@ public: void ParseRawData() override; void DeclareReferences(const std::string& prefix) override; - std::string GetBodySourceCode() const; + std::string GetBodySourceCode() const override; std::string GetSourceTypeName() const override; ZResourceType GetResourceType() const override; - size_t GetRawDataSize() const; + size_t GetRawDataSize() const override; segptr_t GetListAddress() const; protected: @@ -32,14 +32,12 @@ class ZPath : public ZResource public: ZPath(ZFile* nParent); - void ExtractFromXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex); - void ParseXML(tinyxml2::XMLElement* reader) override; void ParseRawData() override; void DeclareReferences(const std::string& prefix) override; - std::string GetBodySourceCode() const; - std::string GetSourceOutputCode(const std::string& prefix) override; + Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override; + std::string GetBodySourceCode() const override; std::string GetSourceTypeName() const override; ZResourceType GetResourceType() const override; diff --git a/tools/ZAPD/ZAPD/ZPlayerAnimationData.cpp b/tools/ZAPD/ZAPD/ZPlayerAnimationData.cpp new file mode 100644 index 0000000000..a96604fda0 --- /dev/null +++ b/tools/ZAPD/ZAPD/ZPlayerAnimationData.cpp @@ -0,0 +1,97 @@ +#include "ZPlayerAnimationData.h" + +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" +#include "ZFile.h" + +REGISTER_ZFILENODE(PlayerAnimationData, ZPlayerAnimationData); + +ZPlayerAnimationData::ZPlayerAnimationData(ZFile* nParent) : ZResource(nParent) +{ + RegisterRequiredAttribute("FrameCount"); +} + +void ZPlayerAnimationData::ParseXML(tinyxml2::XMLElement* reader) +{ + ZResource::ParseXML(reader); + + std::string& frameCountXml = registeredAttributes.at("FrameCount").value; + + frameCount = StringHelper::StrToL(frameCountXml); +} + +void ZPlayerAnimationData::ParseRawData() +{ + ZResource::ParseRawData(); + + const auto& rawData = parent->GetRawData(); + + size_t totalSize = GetRawDataSize(); + // Divided by 2 because each value is an s16 + limbRotData.reserve(totalSize * frameCount / 2); + + for (size_t i = 0; i < totalSize; i += 2) + { + limbRotData.push_back(BitConverter::ToUInt16BE(rawData, rawDataIndex + i)); + } +} + +Declaration* ZPlayerAnimationData::DeclareVar(const std::string& prefix, const std::string& bodyStr) +{ + std::string auxName = name; + + if (auxName == "") + auxName = GetDefaultName(prefix); + + Declaration* decl = + parent->AddDeclarationArray(rawDataIndex, GetDeclarationAlignment(), GetRawDataSize(), + GetSourceTypeName(), name, limbRotData.size(), bodyStr); + decl->staticConf = staticConf; + return decl; +} + +std::string ZPlayerAnimationData::GetBodySourceCode() const +{ + std::string declaration = ""; + + size_t index = 0; + for (const auto& entry : limbRotData) + { + if (index % 8 == 0) + { + declaration += "\t"; + } + + declaration += StringHelper::Sprintf("0x%04X, ", entry); + + if ((index + 1) % 8 == 0) + { + declaration += "\n"; + } + + index++; + } + + return declaration; +} + +std::string ZPlayerAnimationData::GetDefaultName(const std::string& prefix) const +{ + return StringHelper::Sprintf("%sPlayerAnimationData_%06X", prefix.c_str(), rawDataIndex); +} + +std::string ZPlayerAnimationData::GetSourceTypeName() const +{ + return "s16"; +} + +ZResourceType ZPlayerAnimationData::GetResourceType() const +{ + return ZResourceType::PlayerAnimationData; +} + +size_t ZPlayerAnimationData::GetRawDataSize() const +{ + // (sizeof(Vec3s) * limbCount + 2) * frameCount + return (6 * 22 + 2) * frameCount; +} diff --git a/tools/ZAPD/ZAPD/ZPlayerAnimationData.h b/tools/ZAPD/ZAPD/ZPlayerAnimationData.h new file mode 100644 index 0000000000..20835f2369 --- /dev/null +++ b/tools/ZAPD/ZAPD/ZPlayerAnimationData.h @@ -0,0 +1,28 @@ +#pragma once + +#include +#include + +#include "ZResource.h" + +class ZPlayerAnimationData : public ZResource +{ +public: + int16_t frameCount = 0; + std::vector limbRotData; + + ZPlayerAnimationData(ZFile* nParent); + + void ParseXML(tinyxml2::XMLElement* reader) override; + void ParseRawData() override; + + Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override; + + std::string GetBodySourceCode() const override; + std::string GetDefaultName(const std::string& prefix) const override; + + std::string GetSourceTypeName() const override; + ZResourceType GetResourceType() const override; + + size_t GetRawDataSize() const override; +}; diff --git a/tools/ZAPD/ZAPD/ZResource.cpp b/tools/ZAPD/ZAPD/ZResource.cpp index f64ce4aa05..cb811f4c3b 100644 --- a/tools/ZAPD/ZAPD/ZResource.cpp +++ b/tools/ZAPD/ZAPD/ZResource.cpp @@ -2,7 +2,8 @@ #include #include -#include "StringHelper.h" + +#include "Utils/StringHelper.h" #include "ZFile.h" ZResource::ZResource(ZFile* nParent) @@ -19,23 +20,43 @@ ZResource::ZResource(ZFile* nParent) RegisterOptionalAttribute("OutName"); RegisterOptionalAttribute("Offset"); RegisterOptionalAttribute("Custom"); + RegisterOptionalAttribute("Static", "Global"); } -void ZResource::ExtractFromXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex) +void ZResource::ExtractFromXML(tinyxml2::XMLElement* reader, offset_t nRawDataIndex) { rawDataIndex = nRawDataIndex; + declaredInXml = true; if (reader != nullptr) ParseXML(reader); - ParseRawData(); - CalcHash(); + // Don't parse raw data of external files + if (parent->GetMode() != ZFileMode::ExternalFile) + { + ParseRawData(); + CalcHash(); + } + + if (!isInner) + { + Declaration* decl = DeclareVar(parent->GetName(), ""); + if (decl != nullptr) + { + decl->declaredInXml = true; + decl->staticConf = staticConf; + } + } } -void ZResource::ExtractFromFile(uint32_t nRawDataIndex) +void ZResource::ExtractFromFile(offset_t nRawDataIndex) { rawDataIndex = nRawDataIndex; + // Don't parse raw data of external files + if (parent->GetMode() == ZFileMode::ExternalFile) + return; + ParseRawData(); CalcHash(); } @@ -110,15 +131,59 @@ void ZResource::ParseXML(tinyxml2::XMLElement* reader) isCustomAsset = registeredAttributes["Custom"].wasSet; + std::string& staticXml = registeredAttributes["Static"].value; + if (staticXml == "Global") + { + staticConf = StaticConfig::Global; + } + else if (staticXml == "On") + { + staticConf = StaticConfig::On; + } + else if (staticXml == "Off") + { + staticConf = StaticConfig::Off; + } + else + { + throw std::runtime_error("Invalid value for 'Static' attribute."); + } + declaredInXml = true; } } -void ZResource::Save(const fs::path& outFolder) +void ZResource::ParseRawData() { } -void ZResource::PreGenSourceFiles() +void ZResource::DeclareReferences([[maybe_unused]] const std::string& prefix) +{ +} + +void ZResource::ParseRawDataLate() +{ +} + +void ZResource::DeclareReferencesLate([[maybe_unused]] const std::string& prefix) +{ +} + +Declaration* ZResource::DeclareVar(const std::string& prefix, const std::string& bodyStr) +{ + std::string auxName = name; + + if (name == "") + auxName = GetDefaultName(prefix); + + Declaration* decl = + parent->AddDeclaration(rawDataIndex, GetDeclarationAlignment(), GetRawDataSize(), + GetSourceTypeName(), auxName, bodyStr); + decl->staticConf = staticConf; + return decl; +} + +void ZResource::Save([[maybe_unused]] const fs::path& outFolder) { } @@ -157,19 +222,24 @@ std::string ZResource::GetExternalExtension() const return ""; } +DeclarationAlignment ZResource::GetDeclarationAlignment() const +{ + return DeclarationAlignment::Align4; +} + bool ZResource::WasDeclaredInXml() const { return declaredInXml; } -uint32_t ZResource::GetRawDataIndex() const +StaticConfig ZResource::GetStaticConf() const { - return rawDataIndex; + return staticConf; } -void ZResource::SetRawDataIndex(uint32_t value) +offset_t ZResource::GetRawDataIndex() const { - rawDataIndex = value; + return rawDataIndex; } std::string ZResource::GetBodySourceCode() const @@ -177,33 +247,31 @@ std::string ZResource::GetBodySourceCode() const return "ERROR"; } -std::string ZResource::GetSourceOutputCode(const std::string& prefix) +std::string ZResource::GetDefaultName(const std::string& prefix) const { + return StringHelper::Sprintf("%s%s_%06X", prefix.c_str(), GetSourceTypeName().c_str(), + rawDataIndex); +} + +std::string ZResource::GetSourceOutputCode([[maybe_unused]] const std::string& prefix) +{ + std::string bodyStr = GetBodySourceCode(); + + Declaration* decl = parent->GetDeclaration(rawDataIndex); + if (decl == nullptr || decl->isPlaceholder) + decl = DeclareVar(prefix, bodyStr); + else + decl->text = bodyStr; + decl->staticConf = staticConf; + return ""; } -std::string ZResource::GetSourceOutputHeader(const std::string& prefix) +std::string ZResource::GetSourceOutputHeader([[maybe_unused]] const std::string& prefix) { return ""; } -void ZResource::ParseRawData() -{ -} - -void ZResource::DeclareReferences(const std::string& prefix) -{ -} - -void ZResource::GenerateHLIntermediette(HLFileIntermediette& hlFile) -{ -} - -std::string ZResource::GetSourceTypeName() const -{ - return "u8"; -} - ZResourceType ZResource::GetResourceType() const { return ZResourceType::Error; @@ -235,12 +303,24 @@ void ZResource::RegisterOptionalAttribute(const std::string& attr, const std::st registeredAttributes[attr] = resAtrr; } -uint32_t Seg2Filespace(segptr_t segmentedAddress, uint32_t parentBaseAddress) +offset_t Seg2Filespace(segptr_t segmentedAddress, uint32_t parentBaseAddress) { - uint32_t currentPtr = GETSEGOFFSET(segmentedAddress); + offset_t currentPtr = GETSEGOFFSET(segmentedAddress); if (GETSEGNUM(segmentedAddress) == 0x80) // Is defined in code? - currentPtr -= GETSEGOFFSET(parentBaseAddress); + { + uint32_t parentBaseOffset = GETSEGOFFSET(parentBaseAddress); + if (parentBaseOffset > currentPtr) + { + throw std::runtime_error( + StringHelper::Sprintf("\nSeg2Filespace: Segmented address is smaller than " + "'BaseAddress'. Maybe your 'BaseAddress' is wrong?\n" + "\t SegmentedAddress: 0x%08X\n" + "\t BaseAddress: 0x%08X\n", + segmentedAddress, parentBaseAddress)); + } + currentPtr -= parentBaseOffset; + } return currentPtr; } diff --git a/tools/ZAPD/ZAPD/ZResource.h b/tools/ZAPD/ZAPD/ZResource.h index 6ebfcf8fce..727eca2ccb 100644 --- a/tools/ZAPD/ZAPD/ZResource.h +++ b/tools/ZAPD/ZAPD/ZResource.h @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -8,7 +9,7 @@ #include "Declaration.h" #include "tinyxml2.h" -#include "Directory.h" +#include #define SEGMENT_SCENE 2 #define SEGMENT_ROOM 3 @@ -20,16 +21,14 @@ #define GETSEGOFFSET(x) (x & 0x00FFFFFF) #define GETSEGNUM(x) ((x >> 24) & 0xFF) -typedef uint32_t segptr_t; - class ZFile; -class HLFileIntermediette; enum class ZResourceType { Error, Animation, Array, + AltHeader, Background, Blob, CollisionHeader, @@ -39,13 +38,17 @@ enum class ZResourceType LimbTable, Mtx, Path, + PlayerAnimationData, Room, RoomCommand, Scalar, + Scene, Skeleton, String, Symbol, Texture, + TextureAnimation, + TextureAnimationParams, Vector, Vertex, }; @@ -53,8 +56,8 @@ enum class ZResourceType class ResourceAttribute { public: - std::string key = ""; - std::string value = ""; + std::string key; + std::string value; bool isRequired = false; bool wasSet = false; }; @@ -66,54 +69,127 @@ public: bool outputDeclaration = true; uint32_t hash = 0; + /** + * Constructor. + * Child classes should not declare any other constructor besides this one + */ ZResource(ZFile* nParent); virtual ~ZResource() = default; // Parsing from File - virtual void ExtractFromXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex); - virtual void ExtractFromFile(uint32_t nRawDataIndex); + virtual void ExtractFromXML(tinyxml2::XMLElement* reader, offset_t nRawDataIndex); + virtual void ExtractFromFile(offset_t nRawDataIndex); // Misc + /** + * Parses additional attributes of the XML node. + * Extra attritbutes have to be registered using `RegisterRequiredAttribute` or + * `RegisterOptionalAttribute` in the constructor of the ZResource + */ virtual void ParseXML(tinyxml2::XMLElement* reader); + /** + * Extracts data from the binary file + */ virtual void ParseRawData(); + /** + * Declares any data pointed by this resource that has not been declared already. + * For example, a Vtx referenced by a Dlist should be declared here if it wasn't + * declared previously by something else + */ virtual void DeclareReferences(const std::string& prefix); - virtual std::string GetBodySourceCode() const; + virtual void ParseRawDataLate(); + virtual void DeclareReferencesLate(const std::string& prefix); + + /** + * Adds this resource as a Declaration of its parent ZFile + */ + virtual Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr); + /** + * Returns the body of the variable of the extracted resource, without any side-effect + */ + [[nodiscard]] virtual std::string GetBodySourceCode() const; + /** + * Creates an automatically generated variable name for the current resource + */ + [[nodiscard]] virtual std::string GetDefaultName(const std::string& prefix) const; virtual std::string GetSourceOutputCode(const std::string& prefix); virtual std::string GetSourceOutputHeader(const std::string& prefix); - virtual void PreGenSourceFiles(); - virtual void GenerateHLIntermediette(HLFileIntermediette& hlFile); virtual void CalcHash(); + /** + * Exports the resource to binary format + */ virtual void Save(const fs::path& outFolder); // Properties + /** + * Returns true if the resource will be externalized, and included back to the C file using + * `#include`s + */ virtual bool IsExternalResource() const; - virtual bool DoesSupportArray() const; // Can this type be wrapped in an node? - virtual std::string GetSourceTypeName() const; - virtual ZResourceType GetResourceType() const = 0; - virtual std::string GetExternalExtension() const; + /** + * Can this type be wrapped in an node? + */ + virtual bool DoesSupportArray() const; + /** + * The type of the resource as a C struct + */ + [[nodiscard]] virtual std::string GetSourceTypeName() const = 0; + /** + * The type in the ZResource enum + */ + [[nodiscard]] virtual ZResourceType GetResourceType() const = 0; + /** + * The filename extension for assets extracted as standalone files + */ + [[nodiscard]] virtual std::string GetExternalExtension() const; // Getters/Setters - const std::string& GetName() const; + [[nodiscard]] const std::string& GetName() const; void SetName(const std::string& nName); - const std::string& GetOutName() const; + [[nodiscard]] const std::string& GetOutName() const; void SetOutName(const std::string& nName); - virtual uint32_t GetRawDataIndex() const; - virtual void SetRawDataIndex(uint32_t value); - virtual size_t GetRawDataSize() const = 0; + [[nodiscard]] offset_t GetRawDataIndex() const; + /** + * The size of the current struct being extracted, not counting data referenced by it + */ + [[nodiscard]] virtual size_t GetRawDataSize() const = 0; + /** + * The alignment of the extracted struct + */ + [[nodiscard]] virtual DeclarationAlignment GetDeclarationAlignment() const; void SetInnerNode(bool inner); - bool WasDeclaredInXml() const; + /** + * Returns `true` if this ZResource was declared using an XML node, + * `false` otherwise (for example, a Vtx extracted indirectly by a DList) + */ + [[nodiscard]] bool WasDeclaredInXml() const; + [[nodiscard]] StaticConfig GetStaticConf() const; protected: std::string name; std::string outName; - uint32_t rawDataIndex; + offset_t rawDataIndex; std::string sourceOutput; - bool isInner = false; // Is this resource an inner node of another resource? inside of - bool canHaveInner = false; // Can this type have an inner node? - bool isCustomAsset; // If set to true, create a reference for the asset in the file, but don't - // actually try to extract it from the file + + // Inner is used mostly for nodes + /** + * Is this resource an inner node of another resource? + * (namely inside an ) + */ + bool isInner = false; + /** + * Can this type have an inner node? + */ + bool canHaveInner = false; + + /** + * If set to true, create a reference for the asset in the file, but don't + * actually try to extract it from the file + */ + bool isCustomAsset; bool declaredInXml = false; + StaticConfig staticConf = StaticConfig::Global; // Reading from this XMLs attributes should be performed in the overrided `ParseXML` method. std::map registeredAttributes; @@ -129,7 +205,15 @@ protected: void RegisterOptionalAttribute(const std::string& attr, const std::string& defaultValue = ""); }; -uint32_t Seg2Filespace(segptr_t segmentedAddress, uint32_t parentBaseAddress); +class ZResourceExporter +{ +public: + ZResourceExporter() = default; + + virtual void Save(ZResource* res, fs::path outPath, BinaryWriter* writer) = 0; +}; + +offset_t Seg2Filespace(segptr_t segmentedAddress, uint32_t parentBaseAddress); typedef ZResource*(ZResourceFactoryFunc)(ZFile* nParent); @@ -148,3 +232,11 @@ typedef ZResource*(ZResourceFactoryFunc)(ZFile* nParent); } \ }; \ static ZRes_##nodeName inst_ZRes_##nodeName + +#define REGISTER_EXPORTER(expFunc) \ + class ZResExp_##expFunc \ + { \ + public: \ + ZResExp_##expFunc() { expFunc(); } \ + }; \ + static ZResExp_##expFunc inst_ZResExp_##expFunc; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetActorCutsceneList.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetActorCutsceneList.cpp index 18cfd1ef61..60391a9d1d 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetActorCutsceneList.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetActorCutsceneList.cpp @@ -1,8 +1,8 @@ #include "SetActorCutsceneList.h" -#include "BitConverter.h" #include "Globals.h" -#include "StringHelper.h" +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" #include "ZFile.h" #include "ZRoom/ZRoom.h" @@ -29,7 +29,7 @@ void SetActorCutsceneList::DeclareReferences(const std::string& prefix) { if (cutscenes.size() > 0) { - std::string declaration = ""; + std::string declaration; for (size_t i = 0; i < cutscenes.size(); i++) { @@ -45,24 +45,20 @@ void SetActorCutsceneList::DeclareReferences(const std::string& prefix) std::string typeName = cutscenes.at(0).GetSourceTypeName(); parent->AddDeclarationArray( - segmentOffset, DeclarationAlignment::Align4, cutscenes.size() * 16, typeName, + segmentOffset, GetDeclarationAlignment(), cutscenes.size() * 16, typeName, StringHelper::Sprintf("%s%sList_%06X", prefix.c_str(), typeName.c_str(), segmentOffset), - 0, declaration); + cutscenes.size(), declaration); } } std::string SetActorCutsceneList::GetBodySourceCode() const { - std::string listName = parent->GetDeclarationPtrName(cmdArg2); + std::string listName; + Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "ActorCutscene", listName); return StringHelper::Sprintf("SCENE_CMD_ACTOR_CUTSCENE_LIST(%i, %s)", cutscenes.size(), listName.c_str()); } -size_t SetActorCutsceneList::GetRawDataSize() const -{ - return ZRoomCommand::GetRawDataSize() + (cutscenes.size() * 16); -} - std::string SetActorCutsceneList::GetCommandCName() const { return "SCmdCutsceneActorList"; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetActorCutsceneList.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetActorCutsceneList.h index d36dd4c2ff..8fd48e425c 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetActorCutsceneList.h +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetActorCutsceneList.h @@ -26,6 +26,8 @@ public: class SetActorCutsceneList : public ZRoomCommand { public: + std::vector cutscenes; + SetActorCutsceneList(ZFile* nParent); void ParseRawData() override; @@ -35,8 +37,6 @@ public: std::string GetCommandCName() const override; RoomCommand GetRoomCommand() const override; - size_t GetRawDataSize() const override; private: - std::vector cutscenes; }; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetActorList.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetActorList.cpp index b93623b986..919d86f573 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetActorList.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetActorList.cpp @@ -1,8 +1,8 @@ #include "SetActorList.h" -#include "BitConverter.h" #include "Globals.h" -#include "StringHelper.h" +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" #include "ZFile.h" #include "ZRoom/ZNames.h" #include "ZRoom/ZRoom.h" @@ -15,10 +15,26 @@ void SetActorList::ParseRawData() { ZRoomCommand::ParseRawData(); numActors = cmdArg1; +} + +void SetActorList::DeclareReferences(const std::string& prefix) +{ + if (numActors != 0 && cmdArg2 != 0) + { + std::string varName = + StringHelper::Sprintf("%sActorList_%06X", prefix.c_str(), segmentOffset); + parent->AddDeclarationPlaceholder(segmentOffset, varName); + } +} + +void SetActorList::ParseRawDataLate() +{ + ZRoomCommand::ParseRawDataLate(); + size_t actorsAmount = zRoom->GetDeclarationSizeFromNeighbor(segmentOffset) / 0x10; uint32_t currentPtr = segmentOffset; - for (size_t i = 0; i < numActors; i++) + for (size_t i = 0; i < actorsAmount; i++) { ActorSpawnEntry entry(parent->GetRawData(), currentPtr); @@ -27,50 +43,53 @@ void SetActorList::ParseRawData() } } -void SetActorList::DeclareReferences(const std::string& prefix) +void SetActorList::DeclareReferencesLate(const std::string& prefix) { - if (!actors.empty()) + if (actors.empty()) + return; + + std::string declaration; + + size_t largestlength = 0; + for (const auto& entry : actors) { - std::string declaration = ""; - - size_t index = 0; - for (const auto& entry : actors) - { - declaration += - StringHelper::Sprintf("\t{ %s }, // 0x%06X", entry.GetBodySourceCode().c_str(), - segmentOffset + (index * 16)); - - if (index < actors.size() - 1) - declaration += "\n"; - - index++; - } - - const auto& entry = actors.front(); - - DeclarationPadding padding = DeclarationPadding::Pad16; - if (Globals::Instance->game == ZGame::MM_RETAIL) - padding = DeclarationPadding::None; - - parent->AddDeclarationArray( - segmentOffset, DeclarationAlignment::Align4, padding, - actors.size() * entry.GetRawDataSize(), entry.GetSourceTypeName(), - StringHelper::Sprintf("%sActorList_%06X", prefix.c_str(), segmentOffset), - GetActorListArraySize(), declaration); + size_t actorNameLength = ZNames::GetActorName(entry.GetActorId()).size(); + if (actorNameLength > largestlength) + largestlength = actorNameLength; } + + size_t index = 0; + for (auto& entry : actors) + { + entry.SetLargestActorName(largestlength); + declaration += StringHelper::Sprintf("\t{ %s },", entry.GetBodySourceCode().c_str()); + + if (index < actors.size() - 1) + declaration += "\n"; + + index++; + } + + const auto& entry = actors.front(); + + std::string varName = StringHelper::Sprintf("%sActorList_%06X", prefix.c_str(), segmentOffset); + parent->AddDeclarationArray(segmentOffset, DeclarationAlignment::Align4, + actors.size() * entry.GetRawDataSize(), entry.GetSourceTypeName(), + varName, GetActorListArraySize(), declaration); } std::string SetActorList::GetBodySourceCode() const { - std::string listName = parent->GetDeclarationPtrName(cmdArg2); + std::string listName; + Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "ActorEntry", listName); + if (numActors != actors.size()) + { + printf("%s: numActors(%i) ~ actors(%li)\n", parent->GetName().c_str(), numActors, + actors.size()); + } return StringHelper::Sprintf("SCENE_CMD_ACTOR_LIST(%i, %s)", numActors, listName.c_str()); } -size_t SetActorList::GetRawDataSize() const -{ - return ZRoomCommand::GetRawDataSize() + ((int32_t)actors.size() * 16); -} - size_t SetActorList::GetActorListArraySize() const { size_t actorCount = 0; @@ -110,27 +129,31 @@ ActorSpawnEntry::ActorSpawnEntry(const std::vector& rawData, uint32_t r posX = BitConverter::ToInt16BE(rawData, rawDataIndex + 2); posY = BitConverter::ToInt16BE(rawData, rawDataIndex + 4); posZ = BitConverter::ToInt16BE(rawData, rawDataIndex + 6); - rotX = BitConverter::ToInt16BE(rawData, rawDataIndex + 8); - rotY = BitConverter::ToInt16BE(rawData, rawDataIndex + 10); - rotZ = BitConverter::ToInt16BE(rawData, rawDataIndex + 12); + rotX = BitConverter::ToUInt16BE(rawData, rawDataIndex + 8); + rotY = BitConverter::ToUInt16BE(rawData, rawDataIndex + 10); + rotZ = BitConverter::ToUInt16BE(rawData, rawDataIndex + 12); initVar = BitConverter::ToInt16BE(rawData, rawDataIndex + 14); } std::string ActorSpawnEntry::GetBodySourceCode() const { - std::string body = "\n"; + std::string body; - body += "\t\t" + ZNames::GetActorName(actorNum) + ",\n"; - body += StringHelper::Sprintf("\t\t{ %6i, %6i, %6i },\n", posX, posY, posZ); + std::string actorNameFmt = StringHelper::Sprintf("%%-%zus ", largestActorName + 1); + body = + StringHelper::Sprintf(actorNameFmt.c_str(), (ZNames::GetActorName(actorNum) + ",").c_str()); + + body += StringHelper::Sprintf("{ %6i, %6i, %6i }, ", posX, posY, posZ); if (Globals::Instance->game == ZGame::MM_RETAIL) - body += StringHelper::Sprintf("\t\t{ SPAWN_ROT_FLAGS(%i, 0x%04X), SPAWN_ROT_FLAGS(%i, " - "0x%04X), SPAWN_ROT_FLAGS(%i, 0x%04X)},\n", + body += StringHelper::Sprintf("{ SPAWN_ROT_FLAGS(%#5hX, 0x%04X)" + ", SPAWN_ROT_FLAGS(%#5hX, 0x%04X)" + ", SPAWN_ROT_FLAGS(%#5hX, 0x%04X) }, ", (rotX >> 7) & 0b111111111, rotX & 0b1111111, (rotY >> 7) & 0b111111111, rotY & 0b1111111, (rotZ >> 7) & 0b111111111, rotZ & 0b1111111); else - body += StringHelper::Sprintf("\t\t{ %6i, %6i, %6i },\n", rotX, rotY, rotZ); - body += StringHelper::Sprintf("\t\t0x%04X\n ", initVar); + body += StringHelper::Sprintf("{ %#6hX, %#6hX, %#6hX }, ", rotX, rotY, rotZ); + body += StringHelper::Sprintf("0x%04X", initVar); return body; } @@ -149,3 +172,8 @@ uint16_t ActorSpawnEntry::GetActorId() const { return actorNum; } + +void ActorSpawnEntry::SetLargestActorName(size_t nameSize) +{ + largestActorName = nameSize; +} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetActorList.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetActorList.h index bb4091fe3e..7b341256cd 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetActorList.h +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetActorList.h @@ -5,6 +5,16 @@ class ActorSpawnEntry { public: + uint16_t actorNum; + int16_t posX; + int16_t posY; + int16_t posZ; + uint16_t rotX; + uint16_t rotY; + uint16_t rotZ; + uint16_t initVar; + size_t largestActorName = 16; + ActorSpawnEntry(const std::vector& rawData, uint32_t rawDataIndex); std::string GetBodySourceCode() const; @@ -13,35 +23,28 @@ public: int32_t GetRawDataSize() const; uint16_t GetActorId() const; - -protected: - uint16_t actorNum; - int16_t posX; - int16_t posY; - int16_t posZ; - int16_t rotX; - int16_t rotY; - int16_t rotZ; - uint16_t initVar; + void SetLargestActorName(size_t nameSize); }; class SetActorList : public ZRoomCommand { public: + uint8_t numActors; + std::vector actors; + SetActorList(ZFile* nParent); void ParseRawData() override; void DeclareReferences(const std::string& prefix) override; + void ParseRawDataLate() override; + void DeclareReferencesLate(const std::string& prefix) override; + std::string GetBodySourceCode() const override; RoomCommand GetRoomCommand() const override; - size_t GetRawDataSize() const override; std::string GetCommandCName() const override; protected: size_t GetActorListArraySize() const; - - uint8_t numActors; - std::vector actors; }; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetAlternateHeaders.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetAlternateHeaders.cpp index c5f9387bd6..629d4a0b05 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetAlternateHeaders.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetAlternateHeaders.cpp @@ -1,17 +1,22 @@ #include "SetAlternateHeaders.h" -#include "BitConverter.h" -#include "StringHelper.h" +#include "Globals.h" +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" #include "ZFile.h" SetAlternateHeaders::SetAlternateHeaders(ZFile* nParent) : ZRoomCommand(nParent) { } -void SetAlternateHeaders::DeclareReferences(const std::string& prefix) +void SetAlternateHeaders::DeclareReferences([[maybe_unused]] const std::string& prefix) { - if (segmentOffset != 0) - parent->AddDeclarationPlaceholder(segmentOffset); + if (cmdArg2 != 0) + { + std::string varName = + StringHelper::Sprintf("%sAlternateHeaders0x%06X", prefix.c_str(), segmentOffset); + parent->AddDeclarationPlaceholder(segmentOffset, varName); + } } void SetAlternateHeaders::ParseRawDataLate() @@ -23,8 +28,14 @@ void SetAlternateHeaders::ParseRawDataLate() int32_t address = BitConverter::ToInt32BE(parent->GetRawData(), segmentOffset + (i * 4)); headers.push_back(address); - if (address != 0) - zRoom->commandSets.push_back(CommandSet(address)); + if (address != 0 && parent->GetDeclaration(GETSEGOFFSET(address)) == nullptr) + { + ZRoom* altheader = new ZRoom(parent); + altheader->ExtractFromBinary(GETSEGOFFSET(address), zRoom->GetResourceType()); + altheader->DeclareReferences(parent->GetName()); + + parent->resources.push_back(altheader); + } } } @@ -32,30 +43,30 @@ void SetAlternateHeaders::DeclareReferencesLate(const std::string& prefix) { if (!headers.empty()) { - std::string declaration = ""; + std::string declaration; for (size_t i = 0; i < headers.size(); i++) { - if (headers.at(i) == 0) - declaration += StringHelper::Sprintf("\tNULL,"); - else - declaration += - StringHelper::Sprintf("\t%sSet%04X,", prefix.c_str(), GETSEGOFFSET(headers[i])); + std::string altHeaderName; + Globals::Instance->GetSegmentedPtrName(headers.at(i), parent, "", altHeaderName); + + declaration += StringHelper::Sprintf("\t%s,", altHeaderName.c_str()); if (i + 1 < headers.size()) declaration += "\n"; } - parent->AddDeclarationArray( - segmentOffset, DeclarationAlignment::None, headers.size() * 4, "SCmdBase*", - StringHelper::Sprintf("%sAlternateHeaders0x%06X", prefix.c_str(), segmentOffset), 0, - declaration); + std::string varName = + StringHelper::Sprintf("%sAlternateHeaders0x%06X", prefix.c_str(), segmentOffset); + parent->AddDeclarationArray(segmentOffset, GetDeclarationAlignment(), headers.size() * 4, + "SceneCmd*", varName, headers.size(), declaration); } } std::string SetAlternateHeaders::GetBodySourceCode() const { - std::string listName = parent->GetDeclarationPtrName(cmdArg2); + std::string listName; + Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "SceneCmd*", listName); return StringHelper::Sprintf("SCENE_CMD_ALTERNATE_HEADER_LIST(%s)", listName.c_str()); } diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetAlternateHeaders.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetAlternateHeaders.h index e6e7baf45c..e66df936d5 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetAlternateHeaders.h +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetAlternateHeaders.h @@ -6,6 +6,8 @@ class SetAlternateHeaders : public ZRoomCommand { public: + std::vector headers; + SetAlternateHeaders(ZFile* nParent); void DeclareReferences(const std::string& prefix) override; @@ -18,5 +20,4 @@ public: std::string GetCommandCName() const override; private: - std::vector headers; }; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetAnimatedMaterialList.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetAnimatedMaterialList.cpp index aeef2e8ca4..0b9a67e0ec 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetAnimatedMaterialList.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetAnimatedMaterialList.cpp @@ -1,137 +1,42 @@ +/** + * File: SetAnimatedMaterialList.cpp + * Description: Defines a class SetAnimatedMaterialList to enable ZRoom to declare + * ZTextureAnimations, using that ZResource to do the work. + */ #include "SetAnimatedMaterialList.h" -#include "BitConverter.h" #include "Globals.h" -#include "StringHelper.h" +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" #include "ZFile.h" #include "ZRoom/ZRoom.h" +#include "ZTextureAnimation.h" -SetAnimatedMaterialList::SetAnimatedMaterialList(ZFile* nParent) : ZRoomCommand(nParent) +SetAnimatedMaterialList::SetAnimatedMaterialList(ZFile* nParent) + : ZRoomCommand(nParent), textureAnimation(nParent) { } void SetAnimatedMaterialList::ParseRawData() { ZRoomCommand::ParseRawData(); - int32_t currentPtr = segmentOffset; - bool keepGoing = true; - - do - { - AnimatedMaterial lastTexture(parent->GetRawData(), currentPtr); - keepGoing = (lastTexture.segment != 0) && (lastTexture.segment > -1); - currentPtr += 8; - textures.push_back(lastTexture); - } while (keepGoing); + textureAnimation.ExtractFromFile(segmentOffset); } void SetAnimatedMaterialList::DeclareReferences(const std::string& prefix) { - std::string nameStr = - StringHelper::Sprintf("%sAnimatedMaterialList0x%06X", prefix.c_str(), segmentOffset); - - for (auto& texture : textures) - { - size_t declSize = 0; - std::string declTypeName = ""; - std::string declName = StringHelper::Sprintf("%sAnimatedMaterialParams0x%06X", - prefix.c_str(), texture.segmentOffset); - std::string declaration = ""; - size_t index = 0; - - switch (texture.type) - { - case 0: - case 1: - for (const auto& param : texture.params) - { - declaration += param->GenerateSourceCode(zRoom, texture.segmentOffset); - - if (index < texture.params.size() - 1) - declaration += "\n"; - - index++; - } - - declSize = texture.params.size() * 4; - declTypeName = "AnimatedMatTexScrollParams"; - - parent->AddDeclarationArray(texture.segmentOffset, DeclarationAlignment::Align4, - declSize, declTypeName, declName, texture.params.size(), - declaration); - break; - case 2: - case 3: - case 4: - declSize = texture.params.at(0)->GetParamsSize(); - declTypeName = "AnimatedMatColorParams"; - declaration = texture.params.at(0)->GenerateSourceCode(zRoom, texture.segmentOffset); - - parent->AddDeclaration(texture.segmentOffset, DeclarationAlignment::Align4, declSize, - declTypeName, declName, - StringHelper::Sprintf("\n\t%s\n", declaration.c_str())); - break; - case 5: - declSize = texture.params.at(0)->GetParamsSize(); - declTypeName = "AnimatedMatTexCycleParams"; - declaration = texture.params.at(0)->GenerateSourceCode(zRoom, texture.segmentOffset); - - parent->AddDeclaration(texture.segmentOffset, DeclarationAlignment::Align4, declSize, - declTypeName, declName, - StringHelper::Sprintf("\n\t%s\n", declaration.c_str())); - break; - case 6: - continue; - - default: - throw std::runtime_error( - StringHelper::Sprintf("Error in SetAnimatedMaterialList::DeclareReferences (%s)\n" - "\t Unknown texture.type: %i\n", - nameStr.c_str(), texture.type)); - } - } - - if (!textures.empty()) - { - std::string declaration = ""; - - for (size_t i = 0; i < textures.size(); i++) - { - std::string textureName = parent->GetDeclarationPtrName(textures.at(i).segmentAddress); - - declaration += StringHelper::Sprintf("\t{ %2i, %2i, %s },", textures.at(i).segment, - textures.at(i).type, textureName.c_str()); - - if (i + 1 < textures.size()) - declaration += "\n"; - } - - parent->AddDeclarationArray(segmentOffset, DeclarationAlignment::Align4, - DeclarationPadding::Pad16, textures.size() * 8, - "AnimatedMaterial", nameStr, textures.size(), declaration); - } + textureAnimation.SetName(textureAnimation.GetDefaultName(prefix.c_str())); + textureAnimation.DeclareReferences(prefix); + textureAnimation.GetSourceOutputCode(prefix); } std::string SetAnimatedMaterialList::GetBodySourceCode() const { - std::string listName = parent->GetDeclarationPtrName(cmdArg2); + std::string listName; + Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "AnimatedMaterial", listName); return StringHelper::Sprintf("SCENE_CMD_ANIMATED_MATERIAL_LIST(%s)", listName.c_str()); } -size_t SetAnimatedMaterialList::GetRawDataSize() const -{ - size_t paramsSize = 0; - for (const auto& texture : textures) - { - for (const auto& param : texture.params) - { - paramsSize += param->GetParamsSize(); - } - } - - return ZRoomCommand::GetRawDataSize() + paramsSize; -} - std::string SetAnimatedMaterialList::GetCommandCName() const { return "SCmdTextureAnimations"; @@ -141,273 +46,3 @@ RoomCommand SetAnimatedMaterialList::GetRoomCommand() const { return RoomCommand::SetAnimatedMaterialList; } - -AnimatedMaterial::AnimatedMaterial(const std::vector& rawData, uint32_t rawDataIndex) - : segment(rawData.at(rawDataIndex)), type(BitConverter::ToInt16BE(rawData, rawDataIndex + 2)) -{ - segmentAddress = BitConverter::ToInt32BE(rawData, rawDataIndex + 4); - segmentOffset = GETSEGOFFSET(segmentAddress); - - switch (type) - { - case 0: - params.push_back(std::make_shared(rawData, segmentOffset)); - break; - case 1: - params.push_back(std::make_shared(rawData, segmentOffset)); - params.push_back(std::make_shared(rawData, segmentOffset + 4)); - break; - case 2: - case 3: - case 4: - params.push_back(std::make_shared(rawData, segmentOffset, type)); - break; - case 5: - params.push_back(std::make_shared(rawData, segmentOffset)); - break; - case 6: // Some terminator when there are no animated textures? - break; - } -} - -ScrollingTexture::ScrollingTexture(const std::vector& rawData, uint32_t rawDataIndex) - : xStep(rawData.at(rawDataIndex + 0)), yStep(rawData.at(rawDataIndex + 1)), - width(rawData.at(rawDataIndex + 2)), height(rawData.at(rawDataIndex + 3)) -{ -} - -std::string ScrollingTexture::GenerateSourceCode(ZRoom* zRoom, uint32_t baseAddress) -{ - return StringHelper::Sprintf(" { %i, %i, 0x%02X, 0x%02X },", xStep, yStep, width, height); -} - -size_t ScrollingTexture::GetParamsSize() -{ - return 4; -} - -F3DPrimColor::F3DPrimColor(const std::vector& rawData, uint32_t rawDataIndex) - : r(rawData.at(rawDataIndex + 0)), g(rawData.at(rawDataIndex + 1)), - b(rawData.at(rawDataIndex + 2)), a(rawData.at(rawDataIndex + 3)), - lodFrac(rawData.at(rawDataIndex + 4)) -{ -} - -FlashingTextureEnvColor::FlashingTextureEnvColor(const std::vector& rawData, - uint32_t rawDataIndex) - : r(rawData.at(rawDataIndex + 0)), g(rawData.at(rawDataIndex + 1)), - b(rawData.at(rawDataIndex + 2)), a(rawData.at(rawDataIndex + 3)) -{ -} - -FlashingTexture::FlashingTexture(const std::vector& rawData, uint32_t rawDataIndex, - int32_t type) - : cycleLength(BitConverter::ToUInt16BE(rawData, rawDataIndex + 0)), - numKeyFrames(BitConverter::ToUInt16BE(rawData, rawDataIndex + 2)) -{ - uint16_t length = (type == 2) ? cycleLength : numKeyFrames; - - primColorSegmentAddr = BitConverter::ToInt32BE(rawData, rawDataIndex + 4); - envColorSegmentAddr = BitConverter::ToInt32BE(rawData, rawDataIndex + 8); - keyFrameSegmentAddr = BitConverter::ToInt32BE(rawData, rawDataIndex + 12); - - primColorSegmentOffset = GETSEGOFFSET(primColorSegmentAddr); - envColorSegmentOffset = GETSEGOFFSET(envColorSegmentAddr); - keyFrameSegmentOffset = GETSEGOFFSET(keyFrameSegmentAddr); - - int32_t currentPtr = primColorSegmentOffset; - for (uint16_t i = 0; i < length; i++) - { - primColors.push_back(F3DPrimColor(rawData, currentPtr)); - currentPtr += 5; - } - - currentPtr = envColorSegmentOffset; - for (uint16_t i = 0; i < length; i++) - { - envColors.push_back(FlashingTextureEnvColor(rawData, currentPtr)); - currentPtr += 4; - } - - currentPtr = keyFrameSegmentOffset; - for (uint16_t i = 0; i < length; i++) - { - keyFrames.push_back(BitConverter::ToUInt16BE(rawData, currentPtr)); - currentPtr += 2; - } -} - -std::string FlashingTexture::GenerateSourceCode(ZRoom* zRoom, uint32_t baseAddress) -{ - if (primColorSegmentOffset != 0) - { - std::string declaration = ""; - size_t index = 0; - - for (F3DPrimColor& color : primColors) - { - declaration += StringHelper::Sprintf(" { 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X },", - color.r, color.g, color.b, color.a, color.lodFrac); - - if (index < primColors.size() - 1) - declaration += "\n"; - - index++; - } - - zRoom->parent->AddDeclarationArray(primColorSegmentOffset, DeclarationAlignment::Align4, - primColors.size() * 5, "F3DPrimColor", - StringHelper::Sprintf("%sAnimatedMaterialPrimColor_%06X", - zRoom->GetName().c_str(), - primColorSegmentOffset), - primColors.size(), declaration); - } - - if (envColorSegmentOffset != 0) - { - std::string declaration = ""; - size_t index = 0; - - for (FlashingTextureEnvColor& color : envColors) - { - declaration += StringHelper::Sprintf(" { 0x%02X, 0x%02X, 0x%02X, 0x%02X },", color.r, - color.g, color.b, color.a); - - if (index < envColors.size() - 1) - declaration += "\n"; - - index++; - } - - zRoom->parent->AddDeclarationArray( - envColorSegmentOffset, DeclarationAlignment::Align4, envColors.size() * 4, - "F3DEnvColor", - StringHelper::Sprintf("%sAnimatedMaterialEnvColors0x%06X", zRoom->GetName().c_str(), - envColorSegmentOffset), - envColors.size(), declaration); - } - - if (keyFrameSegmentOffset != 0) - { - std::string declaration = ""; - size_t index = 0; - - for (uint16_t keyFrame : keyFrames) - { - declaration += StringHelper::Sprintf(" 0x%02X,", keyFrame); - - if (index < keyFrames.size() - 1) - declaration += "\n"; - - index++; - } - - zRoom->parent->AddDeclarationArray( - keyFrameSegmentOffset, DeclarationAlignment::Align4, keyFrames.size() * 2, "u16", - StringHelper::Sprintf("%sAnimatedMaterialKeyFrames0x%06X", zRoom->GetName().c_str(), - keyFrameSegmentOffset), - keyFrames.size(), declaration); - } - - std::string primName = zRoom->parent->GetDeclarationPtrName(primColorSegmentAddr); - std::string envName = zRoom->parent->GetDeclarationPtrName(envColorSegmentAddr); - std::string keyName = zRoom->parent->GetDeclarationPtrName(keyFrameSegmentAddr); - - return StringHelper::Sprintf("%i, %i, %s, %s, %s", cycleLength, numKeyFrames, primName.c_str(), - envName.c_str(), keyName.c_str()); -} - -size_t FlashingTexture::GetParamsSize() -{ - return 16; -} - -AnimatedMatTexCycleParams::AnimatedMatTexCycleParams(const std::vector& rawData, - uint32_t rawDataIndex) - : cycleLength(BitConverter::ToUInt16BE(rawData, rawDataIndex + 0)) -{ - textureSegmentOffsetsSegmentAddress = BitConverter::ToInt32BE(rawData, rawDataIndex + 4); - textureIndicesSegmentAddress = BitConverter::ToInt32BE(rawData, rawDataIndex + 8); - - textureSegmentOffsetsSegmentOffset = GETSEGOFFSET(textureSegmentOffsetsSegmentAddress); - textureIndicesSegmentOffset = GETSEGOFFSET(textureIndicesSegmentAddress); - - int32_t currentPtr = textureIndicesSegmentOffset; - int32_t maxIndex = 0; - - for (uint16_t i = 0; i < cycleLength; i++) - { - uint8_t newIndex = rawData.at(currentPtr); - textureIndices.push_back(newIndex); - currentPtr++; - if (newIndex > maxIndex) - maxIndex = newIndex; - } - - currentPtr = textureSegmentOffsetsSegmentOffset; - for (int32_t i = 0; i < maxIndex + 1; i++) - { - textureSegmentOffsets.push_back(GETSEGOFFSET(BitConverter::ToInt32BE(rawData, currentPtr))); - currentPtr += 4; - } -} - -std::string AnimatedMatTexCycleParams::GenerateSourceCode(ZRoom* zRoom, uint32_t baseAddress) -{ - if (textureSegmentOffsetsSegmentOffset != 0) - { - std::string declaration = ""; - size_t index = 0; - - for (uint32_t offset : textureSegmentOffsets) - { - declaration += - StringHelper::Sprintf(" %sTex_%06X,", zRoom->GetName().c_str(), offset); - - if (index < textureSegmentOffsets.size() - 1) - declaration += "\n"; - - index++; - } - - zRoom->parent->AddDeclarationArray( - textureSegmentOffsetsSegmentOffset, DeclarationAlignment::Align4, - textureSegmentOffsets.size() * 4, "u64*", - StringHelper::Sprintf("%sAnimatedMaterialTexSegOffsets0x%06X", zRoom->GetName().c_str(), - textureSegmentOffsetsSegmentOffset), - textureSegmentOffsets.size(), declaration); - } - - if (textureIndicesSegmentOffset != 0) - { - std::string declaration = ""; - size_t index = 0; - - for (uint8_t textureIndex : textureIndices) - { - declaration += StringHelper::Sprintf(" 0x%02X,", textureIndex); - - if (index < textureIndices.size() - 1) - declaration += "\n"; - - index++; - } - - zRoom->parent->AddDeclarationArray( - textureIndicesSegmentOffset, DeclarationAlignment::Align4, textureIndices.size(), "u8", - StringHelper::Sprintf("%sAnimatedMaterialTexIndices0x%06X", zRoom->GetName().c_str(), - textureIndicesSegmentOffset), - textureIndices.size(), declaration); - } - - std::string segmName = - zRoom->parent->GetDeclarationPtrName(textureSegmentOffsetsSegmentAddress); - std::string indexesName = zRoom->parent->GetDeclarationPtrName(textureIndicesSegmentAddress); - - return StringHelper::Sprintf("%i, %s, %s", cycleLength, segmName.c_str(), indexesName.c_str()); -} - -size_t AnimatedMatTexCycleParams::GetParamsSize() -{ - return 12; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetAnimatedMaterialList.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetAnimatedMaterialList.h index 3284d819ff..3dbbf9684a 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetAnimatedMaterialList.h +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetAnimatedMaterialList.h @@ -1,104 +1,7 @@ #pragma once -#include #include "ZRoom/ZRoomCommand.h" - -// TODO move into header and add all types -class AnitmatedTextureParams -{ -public: - virtual std::string GenerateSourceCode(ZRoom* zRoom, uint32_t baseAddress) = 0; - virtual size_t GetParamsSize() = 0; -}; - -class ScrollingTexture : public AnitmatedTextureParams -{ -public: - ScrollingTexture(const std::vector& rawData, uint32_t rawDataIndex); - std::string GenerateSourceCode(ZRoom* zRoom, uint32_t baseAddress) override; - size_t GetParamsSize() override; - - int8_t xStep; - int8_t yStep; - uint8_t width; - uint8_t height; -}; - -class F3DPrimColor -{ -public: - F3DPrimColor(const std::vector& rawData, uint32_t rawDataIndex); - - uint8_t r; - uint8_t g; - uint8_t b; - uint8_t a; - uint8_t lodFrac; -}; - -class FlashingTextureEnvColor -{ -public: - FlashingTextureEnvColor(const std::vector& rawData, uint32_t rawDataIndex); - - uint8_t r; - uint8_t g; - uint8_t b; - uint8_t a; -}; - -class FlashingTexture : public AnitmatedTextureParams -{ -public: - FlashingTexture(const std::vector& rawData, uint32_t rawDataIndex, int32_t type); - std::string GenerateSourceCode(ZRoom* zRoom, uint32_t baseAddress) override; - size_t GetParamsSize() override; - - uint16_t cycleLength; - uint16_t numKeyFrames; - - segptr_t primColorSegmentAddr; - segptr_t envColorSegmentAddr; - segptr_t keyFrameSegmentAddr; - - uint32_t primColorSegmentOffset; - uint32_t envColorSegmentOffset; - uint32_t keyFrameSegmentOffset; - - std::vector primColors; - std::vector envColors; - std::vector keyFrames; -}; - -class AnimatedMatTexCycleParams : public AnitmatedTextureParams -{ -public: - AnimatedMatTexCycleParams(const std::vector& rawData, uint32_t rawDataIndex); - std::string GenerateSourceCode(ZRoom* zRoom, uint32_t baseAddress) override; - size_t GetParamsSize() override; - - uint16_t cycleLength; - - segptr_t textureSegmentOffsetsSegmentAddress; - segptr_t textureIndicesSegmentAddress; - uint32_t textureSegmentOffsetsSegmentOffset; - uint32_t textureIndicesSegmentOffset; - - std::vector textureSegmentOffsets; - std::vector textureIndices; -}; - -class AnimatedMaterial -{ -public: - AnimatedMaterial(const std::vector& rawData, uint32_t rawDataIndex); - - int8_t segment; - int16_t type; - segptr_t segmentAddress; - uint32_t segmentOffset; - std::vector> params; -}; +#include "ZTextureAnimation.h" class SetAnimatedMaterialList : public ZRoomCommand { @@ -111,9 +14,8 @@ public: std::string GetBodySourceCode() const override; RoomCommand GetRoomCommand() const override; - size_t GetRawDataSize() const override; std::string GetCommandCName() const override; private: - std::vector textures; + ZTextureAnimation textureAnimation; }; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCameraSettings.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetCameraSettings.cpp index fb41b88626..ae2d31c81e 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCameraSettings.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetCameraSettings.cpp @@ -1,7 +1,7 @@ #include "SetCameraSettings.h" -#include "BitConverter.h" -#include "StringHelper.h" +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" SetCameraSettings::SetCameraSettings(ZFile* nParent) : ZRoomCommand(nParent) { diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCameraSettings.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetCameraSettings.h index 1a0eb11b8c..a8fed44ec2 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCameraSettings.h +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetCameraSettings.h @@ -5,6 +5,9 @@ class SetCameraSettings : public ZRoomCommand { public: + uint8_t cameraMovement; + uint32_t mapHighlight; + SetCameraSettings(ZFile* nParent); void ParseRawData() override; @@ -15,6 +18,4 @@ public: RoomCommand GetRoomCommand() const override; private: - uint8_t cameraMovement; - uint32_t mapHighlight; }; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCollisionHeader.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetCollisionHeader.cpp index 569a7c0785..03aaa4bbbc 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCollisionHeader.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetCollisionHeader.cpp @@ -1,7 +1,8 @@ #include "SetCollisionHeader.h" -#include "BitConverter.h" -#include "StringHelper.h" +#include "Globals.h" +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" #include "ZFile.h" #include "ZRoom/ZRoom.h" @@ -12,21 +13,23 @@ SetCollisionHeader::SetCollisionHeader(ZFile* nParent) : ZRoomCommand(nParent) void SetCollisionHeader::ParseRawData() { ZRoomCommand::ParseRawData(); + collisionHeader = new ZCollisionHeader(parent); - collisionHeader->SetRawDataIndex(segmentOffset); collisionHeader->SetName( StringHelper::Sprintf("%sCollisionHeader_%06X", parent->GetName().c_str(), segmentOffset)); - collisionHeader->ParseRawData(); + collisionHeader->ExtractFromFile(segmentOffset); + parent->AddResource(collisionHeader); } -SetCollisionHeader::~SetCollisionHeader() +void SetCollisionHeader::DeclareReferences(const std::string& prefix) { - delete collisionHeader; + collisionHeader->DeclareVar(prefix, ""); } std::string SetCollisionHeader::GetBodySourceCode() const { - std::string listName = parent->GetDeclarationPtrName(cmdArg2); + std::string listName; + Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "CollisionHeader", listName); return StringHelper::Sprintf("SCENE_CMD_COL_HEADER(%s)", listName.c_str()); } diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCollisionHeader.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetCollisionHeader.h index 7ea15eff8a..f7d5ecf358 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCollisionHeader.h +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetCollisionHeader.h @@ -6,16 +6,15 @@ class SetCollisionHeader : public ZRoomCommand { public: + ZCollisionHeader* collisionHeader; + SetCollisionHeader(ZFile* nParent); - ~SetCollisionHeader(); void ParseRawData() override; + void DeclareReferences(const std::string& prefix) override; std::string GetBodySourceCode() const override; std::string GetCommandCName() const override; RoomCommand GetRoomCommand() const override; - -private: - ZCollisionHeader* collisionHeader; }; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCsCamera.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetCsCamera.cpp index 0402d939e7..5cf0a3d034 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCsCamera.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetCsCamera.cpp @@ -1,7 +1,8 @@ #include "SetCsCamera.h" -#include "BitConverter.h" -#include "StringHelper.h" +#include "Globals.h" +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" #include "ZFile.h" #include "ZRoom/ZRoom.h" @@ -33,31 +34,23 @@ void SetCsCamera::ParseRawData() for (int32_t i = 0; i < numPoints; i++) { ZVector vec(parent); - vec.SetRawDataIndex(currentPtr); - vec.SetScalarType(ZScalarType::ZSCALAR_S16); - vec.SetDimensions(3); - vec.ParseRawData(); + vec.ExtractFromBinary(currentPtr, ZScalarType::ZSCALAR_S16, 3); currentPtr += vec.GetRawDataSize(); points.push_back(vec); } } - - if (segmentOffset != 0) - parent->AddDeclarationPlaceholder(segmentOffset); } void SetCsCamera::DeclareReferences(const std::string& prefix) { if (points.size() > 0) { - std::string declaration = ""; + std::string declaration; size_t index = 0; for (auto& point : points) { - declaration += - StringHelper::Sprintf("\t%s, //0x%06X", point.GetBodySourceCode().c_str(), - cameras.at(0).segmentOffset + (index * 6)); + declaration += StringHelper::Sprintf("\t{ %s },", point.GetBodySourceCode().c_str()); if (index < points.size() - 1) declaration += "\n"; @@ -76,8 +69,10 @@ void SetCsCamera::DeclareReferences(const std::string& prefix) if (!cameras.empty()) { - std::string camPointsName = parent->GetDeclarationName(cameras.at(0).GetSegmentOffset()); - std::string declaration = ""; + std::string camPointsName; + Globals::Instance->GetSegmentedPtrName(cameras.at(0).GetCamAddress(), parent, "Vec3s", + camPointsName); + std::string declaration; size_t index = 0; size_t pointsIndex = 0; @@ -98,8 +93,8 @@ void SetCsCamera::DeclareReferences(const std::string& prefix) std::string camTypename = entry.GetSourceTypeName(); parent->AddDeclarationArray( - segmentOffset, DeclarationAlignment::Align4, DeclarationPadding::Pad16, - cameras.size() * entry.GetRawDataSize(), camTypename, + segmentOffset, DeclarationAlignment::Align4, cameras.size() * entry.GetRawDataSize(), + camTypename, StringHelper::Sprintf("%s%s_%06X", prefix.c_str(), camTypename.c_str(), segmentOffset), cameras.size(), declaration); } @@ -107,16 +102,12 @@ void SetCsCamera::DeclareReferences(const std::string& prefix) std::string SetCsCamera::GetBodySourceCode() const { - std::string listName = parent->GetDeclarationPtrName(cmdArg2); + std::string listName; + Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "CsCameraEntry", listName); return StringHelper::Sprintf("SCENE_CMD_ACTOR_CUTSCENE_CAM_LIST(%i, %s)", cameras.size(), listName.c_str()); } -size_t SetCsCamera::GetRawDataSize() const -{ - return ZRoomCommand::GetRawDataSize() + (cameras.size() * 8) + (points.size() * 6); -} - std::string SetCsCamera::GetCommandCName() const { return "SCmdCsCameraList"; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCsCamera.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetCsCamera.h index e62b073902..5e0e3c8257 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCsCamera.h +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetCsCamera.h @@ -25,6 +25,9 @@ public: class SetCsCamera : public ZRoomCommand { public: + std::vector cameras; + std::vector points; + SetCsCamera(ZFile* nParent); void ParseRawData() override; @@ -33,10 +36,5 @@ public: std::string GetBodySourceCode() const override; RoomCommand GetRoomCommand() const override; - size_t GetRawDataSize() const override; std::string GetCommandCName() const override; - -private: - std::vector cameras; - std::vector points; }; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCutscenes.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetCutscenes.cpp index d9ecb7962b..e51e550b09 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCutscenes.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetCutscenes.cpp @@ -1,8 +1,8 @@ #include "SetCutscenes.h" -#include "BitConverter.h" #include "Globals.h" -#include "StringHelper.h" +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" #include "ZFile.h" #include "ZRoom/ZRoom.h" @@ -10,10 +10,16 @@ SetCutscenes::SetCutscenes(ZFile* nParent) : ZRoomCommand(nParent) { } +SetCutscenes::~SetCutscenes() +{ + for (ZCutsceneBase* cutscene : cutscenes) + delete cutscene; +} + void SetCutscenes::ParseRawData() { ZRoomCommand::ParseRawData(); - std::string output = ""; + std::string output; numCutscenes = cmdArg1; if (Globals::Instance->game == ZGame::OOT_RETAIL || Globals::Instance->game == ZGame::OOT_SW97) @@ -32,7 +38,7 @@ void SetCutscenes::ParseRawData() else { int32_t currentPtr = segmentOffset; - std::string declaration = ""; + std::string declaration; for (uint8_t i = 0; i < numCutscenes; i++) { @@ -40,8 +46,9 @@ void SetCutscenes::ParseRawData() cutsceneEntries.push_back(entry); currentPtr += 8; + // TODO: don't hardcode %sCutsceneData_%06X, look up for the declared name instead declaration += StringHelper::Sprintf( - " { %sCutsceneData0x%06X, 0x%04X, 0x%02X, 0x%02X },", zRoom->GetName().c_str(), + " { %sCutsceneData_%06X, 0x%04X, 0x%02X, 0x%02X },", zRoom->GetName().c_str(), entry.segmentOffset, entry.exit, entry.entrance, entry.flag); if (i < numCutscenes - 1) @@ -61,9 +68,9 @@ void SetCutscenes::ParseRawData() for (ZCutsceneBase* cutscene : cutscenes) { - if (cutscene->getSegmentOffset() != 0) + if (cutscene->GetRawDataIndex() != 0) { - Declaration* decl = parent->GetDeclaration(cutscene->getSegmentOffset()); + Declaration* decl = parent->GetDeclaration(cutscene->GetRawDataIndex()); if (decl == nullptr) { cutscene->GetSourceOutputCode(zRoom->GetName()); @@ -76,15 +83,10 @@ void SetCutscenes::ParseRawData() } } -SetCutscenes::~SetCutscenes() -{ - for (ZCutsceneBase* cutscene : cutscenes) - delete cutscene; -} - std::string SetCutscenes::GetBodySourceCode() const { - std::string listName = parent->GetDeclarationPtrName(cmdArg2); + std::string listName; + Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "CutsceneData", listName); if (Globals::Instance->game == ZGame::MM_RETAIL) return StringHelper::Sprintf("SCENE_CMD_CUTSCENE_LIST(%i, %s)", numCutscenes, @@ -92,11 +94,6 @@ std::string SetCutscenes::GetBodySourceCode() const return StringHelper::Sprintf("SCENE_CMD_CUTSCENE_DATA(%s)", listName.c_str()); } -size_t SetCutscenes::GetRawDataSize() const -{ - return ZRoomCommand::GetRawDataSize(); -} - std::string SetCutscenes::GetCommandCName() const { return "SCmdCutsceneData"; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCutscenes.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetCutscenes.h index 0d1def29a1..ad032bbe6a 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCutscenes.h +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetCutscenes.h @@ -18,6 +18,10 @@ public: class SetCutscenes : public ZRoomCommand { public: + std::vector cutscenes; + std::vector cutsceneEntries; // (MM Only) + uint8_t numCutscenes; // (MM Only) + SetCutscenes(ZFile* nParent); ~SetCutscenes(); @@ -26,11 +30,5 @@ public: std::string GetBodySourceCode() const override; RoomCommand GetRoomCommand() const override; - size_t GetRawDataSize() const override; std::string GetCommandCName() const override; - -private: - std::vector cutscenes; - std::vector cutsceneEntries; // (MM Only) - uint8_t numCutscenes; // (MM Only) }; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetEchoSettings.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetEchoSettings.cpp index 275dc632db..79a278bc69 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetEchoSettings.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetEchoSettings.cpp @@ -1,5 +1,5 @@ #include "SetEchoSettings.h" -#include "StringHelper.h" +#include "Utils/StringHelper.h" SetEchoSettings::SetEchoSettings(ZFile* nParent) : ZRoomCommand(nParent) { diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetEchoSettings.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetEchoSettings.h index 59632631b4..82b8c27dbc 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetEchoSettings.h +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetEchoSettings.h @@ -5,6 +5,8 @@ class SetEchoSettings : public ZRoomCommand { public: + uint8_t echo; + SetEchoSettings(ZFile* nParent); void ParseRawData() override; @@ -13,7 +15,4 @@ public: std::string GetCommandCName() const override; RoomCommand GetRoomCommand() const override; - -private: - uint8_t echo; }; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetEntranceList.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetEntranceList.cpp index 4ba73a2e80..8099bacf12 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetEntranceList.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetEntranceList.cpp @@ -1,7 +1,9 @@ #include "SetEntranceList.h" -#include "BitConverter.h" + +#include "Globals.h" #include "SetStartPositionList.h" -#include "StringHelper.h" +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" #include "ZFile.h" #include "ZRoom/ZRoom.h" @@ -9,10 +11,14 @@ SetEntranceList::SetEntranceList(ZFile* nParent) : ZRoomCommand(nParent) { } -void SetEntranceList::DeclareReferences(const std::string& prefix) +void SetEntranceList::DeclareReferences([[maybe_unused]] const std::string& prefix) { if (segmentOffset != 0) - parent->AddDeclarationPlaceholder(segmentOffset); + { + std::string varName = + StringHelper::Sprintf("%sEntranceList0x%06X", prefix.c_str(), segmentOffset); + parent->AddDeclarationPlaceholder(segmentOffset, varName); + } } void SetEntranceList::ParseRawDataLate() @@ -30,34 +36,34 @@ void SetEntranceList::ParseRawDataLate() } } -void SetEntranceList::DeclareReferencesLate(const std::string& prefix) +void SetEntranceList::DeclareReferencesLate([[maybe_unused]] const std::string& prefix) { if (!entrances.empty()) { - std::string declaration = ""; + std::string declaration; size_t index = 0; for (const auto& entry : entrances) { - declaration += - StringHelper::Sprintf(" { %s }, //0x%06X", entry.GetBodySourceCode().c_str(), - segmentOffset + (index * 2)); + declaration += StringHelper::Sprintf(" { %s },", entry.GetBodySourceCode().c_str()); if (index + 1 < entrances.size()) declaration += "\n"; index++; } - parent->AddDeclarationArray( - segmentOffset, DeclarationAlignment::None, entrances.size() * 2, "EntranceEntry", - StringHelper::Sprintf("%sEntranceList0x%06X", zRoom->GetName().c_str(), segmentOffset), - entrances.size(), declaration); + std::string varName = + StringHelper::Sprintf("%sEntranceList0x%06X", prefix.c_str(), segmentOffset); + parent->AddDeclarationArray(segmentOffset, DeclarationAlignment::Align4, + entrances.size() * 2, "EntranceEntry", varName, + entrances.size(), declaration); } } std::string SetEntranceList::GetBodySourceCode() const { - std::string listName = parent->GetDeclarationPtrName(cmdArg2); + std::string listName; + Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "EntranceEntry", listName); return StringHelper::Sprintf("SCENE_CMD_ENTRANCE_LIST(%s)", listName.c_str()); } diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetEntranceList.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetEntranceList.h index 5e76f9f6c9..e13e9a8ce6 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetEntranceList.h +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetEntranceList.h @@ -5,18 +5,19 @@ class EntranceEntry { public: + uint8_t startPositionIndex; + uint8_t roomToLoad; + EntranceEntry(const std::vector& rawData, uint32_t rawDataIndex); std::string GetBodySourceCode() const; - -protected: - uint8_t startPositionIndex; - uint8_t roomToLoad; }; class SetEntranceList : public ZRoomCommand { public: + std::vector entrances; + SetEntranceList(ZFile* nParent); void DeclareReferences(const std::string& prefix) override; @@ -27,7 +28,4 @@ public: RoomCommand GetRoomCommand() const override; std::string GetCommandCName() const override; - -private: - std::vector entrances; }; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetExitList.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetExitList.cpp index 5bfd19a578..ddc4c5d43e 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetExitList.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetExitList.cpp @@ -1,7 +1,8 @@ #include "SetExitList.h" -#include "BitConverter.h" -#include "StringHelper.h" +#include "Globals.h" +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" #include "ZFile.h" #include "ZRoom/ZRoom.h" @@ -9,10 +10,14 @@ SetExitList::SetExitList(ZFile* nParent) : ZRoomCommand(nParent) { } -void SetExitList::DeclareReferences(const std::string& prefix) +void SetExitList::DeclareReferences([[maybe_unused]] const std::string& prefix) { if (segmentOffset != 0) - parent->AddDeclarationPlaceholder(segmentOffset); + { + std::string varName = + StringHelper::Sprintf("%sExitList_%06X", prefix.c_str(), segmentOffset); + parent->AddDeclarationPlaceholder(segmentOffset, varName); + } } void SetExitList::ParseRawDataLate() @@ -30,11 +35,11 @@ void SetExitList::ParseRawDataLate() } } -void SetExitList::DeclareReferencesLate(const std::string& prefix) +void SetExitList::DeclareReferencesLate([[maybe_unused]] const std::string& prefix) { if (!exits.empty()) { - std::string declaration = ""; + std::string declaration; for (size_t i = 0; i < exits.size(); i++) { @@ -43,16 +48,17 @@ void SetExitList::DeclareReferencesLate(const std::string& prefix) declaration += "\n"; } - parent->AddDeclarationArray( - segmentOffset, DeclarationAlignment::Align4, exits.size() * 2, "u16", - StringHelper::Sprintf("%sExitList_%06X", zRoom->GetName().c_str(), segmentOffset), - exits.size(), declaration); + std::string varName = + StringHelper::Sprintf("%sExitList_%06X", prefix.c_str(), segmentOffset); + parent->AddDeclarationArray(segmentOffset, DeclarationAlignment::Align4, exits.size() * 2, + "u16", varName, exits.size(), declaration); } } std::string SetExitList::GetBodySourceCode() const { - std::string listName = parent->GetDeclarationPtrName(cmdArg2); + std::string listName; + Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "u16", listName); return StringHelper::Sprintf("SCENE_CMD_EXIT_LIST(%s)", listName.c_str()); } diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetExitList.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetExitList.h index 8d220b1cd1..9d2791a83d 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetExitList.h +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetExitList.h @@ -5,6 +5,8 @@ class SetExitList : public ZRoomCommand { public: + std::vector exits; + SetExitList(ZFile* nParent); void DeclareReferences(const std::string& prefix) override; @@ -15,7 +17,4 @@ public: RoomCommand GetRoomCommand() const override; std::string GetCommandCName() const override; - -private: - std::vector exits; }; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetLightList.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetLightList.cpp index a12832c0a3..2e023ff206 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetLightList.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetLightList.cpp @@ -1,6 +1,8 @@ #include "SetLightList.h" -#include "BitConverter.h" -#include "StringHelper.h" + +#include "Globals.h" +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" SetLightList::SetLightList(ZFile* nParent) : ZRoomCommand(nParent) { @@ -9,7 +11,7 @@ SetLightList::SetLightList(ZFile* nParent) : ZRoomCommand(nParent) void SetLightList::ParseRawData() { ZRoomCommand::ParseRawData(); - std::string declarations = ""; + std::string declarations; numLights = cmdArg1; int32_t currentPtr = segmentOffset; @@ -26,7 +28,7 @@ void SetLightList::DeclareReferences(const std::string& prefix) { if (!lights.empty()) { - std::string declarations = ""; + std::string declarations; for (size_t i = 0; i < lights.size(); i++) { @@ -40,7 +42,7 @@ void SetLightList::DeclareReferences(const std::string& prefix) const auto& light = lights.front(); parent->AddDeclarationArray( - segmentOffset, DeclarationAlignment::None, lights.size() * light.GetRawDataSize(), + segmentOffset, DeclarationAlignment::Align4, lights.size() * light.GetRawDataSize(), light.GetSourceTypeName(), StringHelper::Sprintf("%sLightInfo0x%06X", prefix.c_str(), segmentOffset), lights.size(), declarations); @@ -49,7 +51,8 @@ void SetLightList::DeclareReferences(const std::string& prefix) std::string SetLightList::GetBodySourceCode() const { - std::string listName = parent->GetDeclarationPtrName(cmdArg2); + std::string listName; + Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "LightInfo", listName); return StringHelper::Sprintf("SCENE_CMD_LIGHT_LIST(%i, %s)", numLights, listName.c_str()); } diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetLightList.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetLightList.h index 389ffef0f9..c089d82a54 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetLightList.h +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetLightList.h @@ -27,6 +27,9 @@ protected: class SetLightList : public ZRoomCommand { public: + uint8_t numLights; + std::vector lights; + SetLightList(ZFile* nParent); void ParseRawData() override; @@ -36,8 +39,4 @@ public: RoomCommand GetRoomCommand() const override; std::string GetCommandCName() const override; - -private: - uint8_t numLights; - std::vector lights; }; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetLightingSettings.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetLightingSettings.cpp index e677738f5c..08cd83d141 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetLightingSettings.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetLightingSettings.cpp @@ -1,6 +1,8 @@ #include "SetLightingSettings.h" -#include "BitConverter.h" -#include "StringHelper.h" + +#include "Globals.h" +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" #include "ZFile.h" #include "ZRoom/ZRoom.h" @@ -21,13 +23,12 @@ void SetLightingSettings::DeclareReferences(const std::string& prefix) { if (settings.size() > 0) { - std::string declaration = ""; + std::string declaration; for (size_t i = 0; i < settings.size(); i++) { - declaration += StringHelper::Sprintf("\t{ %s }, // 0x%06X", - settings.at(i).GetBodySourceCode().c_str(), - segmentOffset + (i * 22)); + declaration += + StringHelper::Sprintf("\t{ %s },", settings.at(i).GetBodySourceCode().c_str()); if (i + 1 < settings.size()) declaration += "\n"; } @@ -42,7 +43,8 @@ void SetLightingSettings::DeclareReferences(const std::string& prefix) std::string SetLightingSettings::GetBodySourceCode() const { - std::string listName = parent->GetDeclarationPtrName(cmdArg2); + std::string listName; + Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "LightSettings", listName); return StringHelper::Sprintf("SCENE_CMD_ENV_LIGHT_SETTINGS(%i, %s)", settings.size(), listName.c_str()); } diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetLightingSettings.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetLightingSettings.h index 7717957fa3..29caf4aa6a 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetLightingSettings.h +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetLightingSettings.h @@ -5,13 +5,6 @@ class LightingSettings { public: - LightingSettings(const std::vector& rawData, uint32_t rawDataIndex); - - std::string GetBodySourceCode() const; - - size_t GetRawDataSize() const; - -protected: uint8_t ambientClrR, ambientClrG, ambientClrB; uint8_t diffuseClrA_R, diffuseClrA_G, diffuseClrA_B; uint8_t diffuseDirA_X, diffuseDirA_Y, diffuseDirA_Z; @@ -20,11 +13,19 @@ protected: uint8_t fogClrR, fogClrG, fogClrB; uint16_t unk; uint16_t drawDistance; + + LightingSettings(const std::vector& rawData, uint32_t rawDataIndex); + + std::string GetBodySourceCode() const; + + size_t GetRawDataSize() const; }; class SetLightingSettings : public ZRoomCommand { public: + std::vector settings; + SetLightingSettings(ZFile* nParent); void ParseRawData() override; @@ -34,7 +35,4 @@ public: RoomCommand GetRoomCommand() const override; std::string GetCommandCName() const override; - -private: - std::vector settings; }; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetMesh.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetMesh.cpp index f2a9676901..4fa1f05cb2 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetMesh.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetMesh.cpp @@ -1,8 +1,8 @@ #include "SetMesh.h" #include -#include -#include "BitConverter.h" -#include "StringHelper.h" +#include +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" #include "ZBackground.h" #include "ZFile.h" #include "ZRoom/ZRoom.h" @@ -22,15 +22,15 @@ void SetMesh::ParseRawData() switch (meshHeaderType) { case 0: - polyType = std::make_shared(parent, parentRawData, segmentOffset, zRoom); + polyType = std::make_shared(parent, segmentOffset, zRoom); break; case 1: - polyType = std::make_shared(parent, parentRawData, segmentOffset, zRoom); + polyType = std::make_shared(parent, segmentOffset, zRoom); break; case 2: - polyType = std::make_shared(parent, parentRawData, segmentOffset, zRoom); + polyType = std::make_shared(parent, segmentOffset, zRoom); break; default: @@ -49,37 +49,23 @@ void SetMesh::DeclareReferences(const std::string& prefix) polyType->DeclareAndGenerateOutputCode(prefix); } +// TODO: is this really needed? void GenDListDeclarations(ZRoom* zRoom, ZFile* parent, ZDisplayList* dList) { if (dList == nullptr) { return; } - std::string srcVarName = - StringHelper::Sprintf("%s%s", zRoom->GetName().c_str(), dList->GetName().c_str()); - dList->SetName(srcVarName); - dList->scene = zRoom->scene; std::string sourceOutput = dList->GetSourceOutputCode(zRoom->GetName()); for (ZDisplayList* otherDList : dList->otherDLists) GenDListDeclarations(zRoom, parent, otherDList); - - for (const auto& vtxEntry : dList->vtxDeclarations) - { - DeclarationAlignment alignment = DeclarationAlignment::Align4; - if (Globals::Instance->game == ZGame::MM_RETAIL) - alignment = DeclarationAlignment::None; - parent->AddDeclarationArray( - vtxEntry.first, alignment, dList->vertices[vtxEntry.first].size() * 16, "static Vtx", - StringHelper::Sprintf("%sVtx_%06X", zRoom->GetName().c_str(), vtxEntry.first), - dList->vertices[vtxEntry.first].size(), vtxEntry.second); - } } std::string SetMesh::GenDListExterns(ZDisplayList* dList) { - std::string sourceOutput = ""; + std::string sourceOutput; sourceOutput += StringHelper::Sprintf("extern Gfx %sDL_%06X[];\n", zRoom->GetName().c_str(), dList->GetRawDataIndex()); @@ -87,22 +73,16 @@ std::string SetMesh::GenDListExterns(ZDisplayList* dList) for (ZDisplayList* otherDList : dList->otherDLists) sourceOutput += GenDListExterns(otherDList); - sourceOutput += dList->defines; - return sourceOutput; } std::string SetMesh::GetBodySourceCode() const { - std::string list = parent->GetDeclarationPtrName(cmdArg2); + std::string list; + Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "", list); return StringHelper::Sprintf("SCENE_CMD_MESH(%s)", list.c_str()); } -size_t SetMesh::GetRawDataSize() const -{ - return ZRoomCommand::GetRawDataSize(); -} - std::string SetMesh::GetCommandCName() const { return "SCmdMesh"; @@ -113,14 +93,8 @@ RoomCommand SetMesh::GetRoomCommand() const return RoomCommand::SetMesh; } -PolygonDlist::PolygonDlist(const std::string& prefix, const std::vector& nRawData, - uint32_t nRawDataIndex, ZFile* nParent, ZRoom* nRoom) +PolygonDlist::PolygonDlist(ZFile* nParent) : ZResource(nParent) { - rawDataIndex = nRawDataIndex; - parent = nParent; - zRoom = nRoom; - - name = GetDefaultName(prefix.c_str(), rawDataIndex); } void PolygonDlist::ParseRawData() @@ -151,22 +125,57 @@ void PolygonDlist::DeclareReferences(const std::string& prefix) xluDList = MakeDlist(xlu, prefix); } -ZDisplayList* PolygonDlist::MakeDlist(segptr_t ptr, const std::string& prefix) +std::string PolygonDlist::GetBodySourceCode() const { - if (ptr == 0) + std::string bodyStr; + std::string opaStr; + std::string xluStr; + Globals::Instance->GetSegmentedPtrName(opa, parent, "Gfx", opaStr); + Globals::Instance->GetSegmentedPtrName(xlu, parent, "Gfx", xluStr); + + if (polyType == 2) { - return nullptr; + bodyStr += StringHelper::Sprintf("{ %6i, %6i, %6i }, %6i, ", x, y, z, unk_06); } - uint32_t dlistAddress = Seg2Filespace(ptr, parent->baseAddress); + bodyStr += StringHelper::Sprintf("%s, %s", opaStr.c_str(), xluStr.c_str()); - int32_t dlistLength = ZDisplayList::GetDListLength( - parent->GetRawData(), dlistAddress, - Globals::Instance->game == ZGame::OOT_SW97 ? DListType::F3DEX : DListType::F3DZEX); - ZDisplayList* dlist = new ZDisplayList(dlistAddress, dlistLength, parent); - GenDListDeclarations(zRoom, parent, dlist); + return bodyStr; +} - return dlist; +std::string PolygonDlist::GetSourceOutputCode(const std::string& prefix) +{ + std::string bodyStr = StringHelper::Sprintf("\n\t%s\n", GetBodySourceCode().c_str()); + + Declaration* decl = parent->GetDeclaration(rawDataIndex); + if (decl == nullptr) + { + DeclareVar(prefix, bodyStr); + } + else + { + decl->text = bodyStr; + } + + return ""; +} + +std::string PolygonDlist::GetSourceTypeName() const +{ + switch (polyType) + { + case 2: + return "PolygonDlist2"; + + default: + return "PolygonDlist"; + } +} + +ZResourceType PolygonDlist::GetResourceType() const +{ + // TODO + return ZResourceType::Error; } size_t PolygonDlist::GetRawDataSize() const @@ -186,96 +195,41 @@ void PolygonDlist::SetPolyType(uint8_t nPolyType) polyType = nPolyType; } -void PolygonDlist::DeclareVar(const std::string& prefix, const std::string& bodyStr) +ZDisplayList* PolygonDlist::MakeDlist(segptr_t ptr, [[maybe_unused]] const std::string& prefix) { - std::string auxName = name; - if (name == "") + if (ptr == 0) { - auxName = GetDefaultName(prefix, rawDataIndex); + return nullptr; } - parent->AddDeclaration(rawDataIndex, DeclarationAlignment::Align4, GetRawDataSize(), - GetSourceTypeName(), auxName, bodyStr); + + uint32_t dlistAddress = Seg2Filespace(ptr, parent->baseAddress); + + int32_t dlistLength = ZDisplayList::GetDListLength( + parent->GetRawData(), dlistAddress, + Globals::Instance->game == ZGame::OOT_SW97 ? DListType::F3DEX : DListType::F3DZEX); + ZDisplayList* dlist = new ZDisplayList(parent); + dlist->ExtractFromBinary(dlistAddress, dlistLength); + dlist->SetName(dlist->GetDefaultName(prefix)); + GenDListDeclarations(zRoom, parent, dlist); + + return dlist; } -std::string PolygonDlist::GetBodySourceCode(bool arrayElement) +/* BgImage */ + +BgImage::BgImage(ZFile* nParent) : ZResource(nParent) { - std::string bodyStr = ""; - std::string opaStr = parent->GetDeclarationPtrName(opa); - std::string xluStr = parent->GetDeclarationPtrName(xlu); - if (arrayElement) - { - bodyStr += " { "; - } - else - { - bodyStr += "\n "; - } - - if (polyType == 2) - { - bodyStr += StringHelper::Sprintf("{ %6i, %6i, %6i }, %6i, ", x, y, z, unk_06); - } - - bodyStr += StringHelper::Sprintf("%s, ", opaStr.c_str()); - bodyStr += StringHelper::Sprintf("%s", xluStr.c_str()); - - if (arrayElement) - { - bodyStr += " },"; - } - else - { - bodyStr += "\n"; - } - - return bodyStr; } -void PolygonDlist::DeclareAndGenerateOutputCode() -{ - std::string bodyStr = GetBodySourceCode(false); - - Declaration* decl = parent->GetDeclaration(rawDataIndex); - if (decl == nullptr) - { - DeclareVar("", bodyStr); - } - else - { - decl->text = bodyStr; - } -} - -std::string PolygonDlist::GetDefaultName(const std::string& prefix, uint32_t address) -{ - return StringHelper::Sprintf("%sPolyDlist_%06X", prefix.c_str(), address); -} - -std::string PolygonDlist::GetSourceTypeName() -{ - switch (polyType) - { - case 2: - return "PolygonDlist2"; - - default: - return "PolygonDlist"; - } -} - -std::string PolygonDlist::GetName() -{ - return name; -} - -BgImage::BgImage(bool nIsSubStruct, const std::string& prefix, const std::vector& nRawData, - uint32_t nRawDataIndex, ZFile* nParent) +BgImage::BgImage(bool nIsSubStruct, const std::string& prefix, uint32_t nRawDataIndex, + ZFile* nParent) + : BgImage(nParent) { rawDataIndex = nRawDataIndex; parent = nParent; isSubStruct = nIsSubStruct; - name = GetDefaultName(prefix.c_str(), rawDataIndex); + name = GetDefaultName(prefix); ParseRawData(); sourceBackground = MakeBackground(source, prefix); @@ -306,28 +260,32 @@ void BgImage::ParseRawData() ZBackground* BgImage::MakeBackground(segptr_t ptr, const std::string& prefix) { if (ptr == 0) - { return nullptr; - } uint32_t backAddress = Seg2Filespace(ptr, parent->baseAddress); - ZBackground* background = new ZBackground(prefix, backAddress, parent); + ZBackground* background = new ZBackground(parent); + background->ExtractFromFile(backAddress); + + std::string defaultName = background->GetDefaultName(prefix); + background->SetName(defaultName); + background->SetOutName(defaultName); + background->DeclareVar(prefix, ""); parent->resources.push_back(background); return background; } -size_t BgImage::GetRawDataSize() +size_t BgImage::GetRawDataSize() const { return 0x1C; } -std::string BgImage::GetBodySourceCode(bool arrayElement) const +std::string BgImage::GetBodySourceCode() const { std::string bodyStr = " "; - if (arrayElement) + if (!isSubStruct) { bodyStr += "{ \n "; } @@ -337,16 +295,14 @@ std::string BgImage::GetBodySourceCode(bool arrayElement) const bodyStr += StringHelper::Sprintf("0x%04X, ", unk_00); bodyStr += StringHelper::Sprintf("%i, ", id); bodyStr += "\n "; - if (arrayElement) - { - bodyStr += " "; - } + bodyStr += " "; } - std::string backgroundName = parent->GetDeclarationPtrName(source); + std::string backgroundName; + Globals::Instance->GetSegmentedPtrName(source, parent, "", backgroundName); bodyStr += StringHelper::Sprintf("%s, ", backgroundName.c_str()); bodyStr += "\n "; - if (arrayElement) + if (!isSubStruct) { bodyStr += " "; } @@ -354,7 +310,7 @@ std::string BgImage::GetBodySourceCode(bool arrayElement) const bodyStr += StringHelper::Sprintf("0x%08X, ", unk_0C); bodyStr += StringHelper::Sprintf("0x%08X, ", tlut); bodyStr += "\n "; - if (arrayElement) + if (!isSubStruct) { bodyStr += " "; } @@ -362,7 +318,7 @@ std::string BgImage::GetBodySourceCode(bool arrayElement) const bodyStr += StringHelper::Sprintf("%i, ", width); bodyStr += StringHelper::Sprintf("%i, ", height); bodyStr += "\n "; - if (arrayElement) + if (!isSubStruct) { bodyStr += " "; } @@ -370,14 +326,14 @@ std::string BgImage::GetBodySourceCode(bool arrayElement) const bodyStr += StringHelper::Sprintf("%i, ", fmt); bodyStr += StringHelper::Sprintf("%i, ", siz); bodyStr += "\n "; - if (arrayElement) + if (!isSubStruct) { bodyStr += " "; } bodyStr += StringHelper::Sprintf("0x%04X, ", mode0); bodyStr += StringHelper::Sprintf("0x%04X, ", tlutCount); - if (arrayElement) + if (!isSubStruct) { bodyStr += " \n }, "; } @@ -389,40 +345,26 @@ std::string BgImage::GetBodySourceCode(bool arrayElement) const return bodyStr; } -std::string BgImage::GetDefaultName(const std::string& prefix, uint32_t address) -{ - return StringHelper::Sprintf("%sBgImage_%06X", prefix.c_str(), address); -} - -std::string BgImage::GetSourceTypeName() +std::string BgImage::GetSourceTypeName() const { return "BgImage"; } -std::string BgImage::GetName() +ZResourceType BgImage::GetResourceType() const { - return name; + // TODO + return ZResourceType::Error; } /* PolygonType section */ -PolygonTypeBase::PolygonTypeBase(ZFile* nParent, const std::vector& nRawData, - uint32_t nRawDataIndex, ZRoom* nRoom) - : rawDataIndex{nRawDataIndex}, parent{nParent}, zRoom{nRoom} +PolygonTypeBase::PolygonTypeBase(ZFile* nParent, uint32_t nRawDataIndex, ZRoom* nRoom) + : ZResource(nParent), zRoom{nRoom} { + rawDataIndex = nRawDataIndex; type = BitConverter::ToUInt8BE(parent->GetRawData(), rawDataIndex); } -void PolygonTypeBase::DeclareVar(const std::string& prefix, const std::string& bodyStr) -{ - std::string auxName = name; - if (name == "") - auxName = GetDefaultName(prefix); - - parent->AddDeclaration(rawDataIndex, DeclarationAlignment::Align4, GetRawDataSize(), - GetSourceTypeName(), auxName, bodyStr); -} - void PolygonTypeBase::DeclareAndGenerateOutputCode(const std::string& prefix) { std::string bodyStr = GetBodySourceCode(); @@ -453,25 +395,14 @@ std::string PolygonTypeBase::GetSourceTypeName() const } } -std::string PolygonTypeBase::GetName() const +ZResourceType PolygonTypeBase::GetResourceType() const { - return name; + // TODO + return ZResourceType::Error; } -void PolygonTypeBase::SetName(const std::string& newName) -{ - name = newName; -} - -std::string PolygonTypeBase::GetDefaultName(const std::string& prefix) const -{ - return StringHelper::Sprintf("%s%s_%06X", prefix.c_str(), GetSourceTypeName().c_str(), - rawDataIndex); -} - -PolygonType1::PolygonType1(ZFile* nParent, const std::vector& nRawData, - uint32_t nRawDataIndex, ZRoom* nRoom) - : PolygonTypeBase(nParent, nRawData, nRawDataIndex, nRoom) +PolygonType1::PolygonType1(ZFile* nParent, uint32_t nRawDataIndex, ZRoom* nRoom) + : PolygonTypeBase(nParent, nRawDataIndex, nRoom), single(nParent) { } @@ -490,10 +421,10 @@ void PolygonType1::ParseRawData() if (dlist != 0) { - PolygonDlist polyGfxList(zRoom->GetName(), rawData, - Seg2Filespace(dlist, parent->baseAddress), parent, zRoom); + PolygonDlist polyGfxList(parent); + polyGfxList.zRoom = zRoom; polyGfxList.SetPolyType(type); - polyGfxList.ParseRawData(); + polyGfxList.ExtractFromFile(Seg2Filespace(dlist, parent->baseAddress)); polyGfxList.DeclareReferences(zRoom->GetName()); polyDLists.push_back(polyGfxList); } @@ -501,26 +432,27 @@ void PolygonType1::ParseRawData() void PolygonType1::DeclareReferences(const std::string& prefix) { - polyDLists.at(0).DeclareAndGenerateOutputCode(); + polyDLists.at(0).GetSourceOutputCode(prefix); uint32_t listAddress; - std::string bgImageArrayBody = ""; + std::string bgImageArrayBody; switch (format) { case 1: - single = BgImage(true, prefix, parent->GetRawData(), rawDataIndex + 0x08, parent); + single = BgImage(true, prefix, rawDataIndex + 0x08, parent); break; case 2: if (list != 0) { listAddress = Seg2Filespace(list, parent->baseAddress); + uint32_t auxPtr = listAddress; for (size_t i = 0; i < count; ++i) { - BgImage bg(false, prefix, parent->GetRawData(), - listAddress + i * BgImage::GetRawDataSize(), parent); + BgImage bg(false, prefix, auxPtr, parent); multiList.push_back(bg); - bgImageArrayBody += bg.GetBodySourceCode(true); + auxPtr += bg.GetRawDataSize(); + bgImageArrayBody += bg.GetBodySourceCode(); if (i + 1 < count) { bgImageArrayBody += "\n"; @@ -531,9 +463,9 @@ void PolygonType1::DeclareReferences(const std::string& prefix) if (decl == nullptr) { parent->AddDeclarationArray( - listAddress, DeclarationAlignment::Align4, count * BgImage::GetRawDataSize(), - BgImage::GetSourceTypeName(), multiList.at(0).GetName().c_str(), count, - bgImageArrayBody); + listAddress, DeclarationAlignment::Align4, + count * multiList.at(0).GetRawDataSize(), multiList.at(0).GetSourceTypeName(), + multiList.at(0).GetName().c_str(), count, bgImageArrayBody); } } break; @@ -565,26 +497,26 @@ std::string PolygonType1::GetBodySourceCode() const bodyStr += "{ "; bodyStr += StringHelper::Sprintf("%i, %i, ", type, format); - std::string dlistStr = parent->GetDeclarationPtrName(dlist); + std::string dlistStr; + Globals::Instance->GetSegmentedPtrName(dlist, parent, "", dlistStr); + bodyStr += StringHelper::Sprintf("%s, ", dlistStr.c_str()); bodyStr += "}, \n"; std::string listStr = "NULL"; - // bodyStr += " { \n"; switch (format) { case 1: - bodyStr += single.GetBodySourceCode(false); + bodyStr += single.GetBodySourceCode(); break; case 2: - listStr = parent->GetDeclarationPtrName(list); + Globals::Instance->GetSegmentedPtrName(list, parent, "BgImage", listStr); bodyStr += StringHelper::Sprintf(" %i, %s, \n", count, listStr.c_str()); break; default: break; } - // bodyStr += " } \n"; return bodyStr; } @@ -603,9 +535,8 @@ std::string PolygonType1::GetSourceTypeName() const // return "PolygonType1"; } -PolygonType2::PolygonType2(ZFile* nParent, const std::vector& nRawData, - uint32_t nRawDataIndex, ZRoom* nRoom) - : PolygonTypeBase(nParent, nRawData, nRawDataIndex, nRoom) +PolygonType2::PolygonType2(ZFile* nParent, uint32_t nRawDataIndex, ZRoom* nRoom) + : PolygonTypeBase(nParent, nRawDataIndex, nRoom) { } @@ -621,9 +552,10 @@ void PolygonType2::ParseRawData() uint32_t currentPtr = GETSEGOFFSET(start); for (size_t i = 0; i < num; i++) { - PolygonDlist entry(zRoom->GetName(), rawData, currentPtr, parent, zRoom); + PolygonDlist entry(parent); + entry.zRoom = zRoom; entry.SetPolyType(type); - entry.ParseRawData(); + entry.ExtractFromFile(currentPtr); entry.DeclareReferences(zRoom->GetName()); polyDLists.push_back(entry); currentPtr += entry.GetRawDataSize(); @@ -634,17 +566,18 @@ void PolygonType2::DeclareReferences(const std::string& prefix) { if (num > 0) { - std::string declaration = ""; + std::string declaration; for (size_t i = 0; i < polyDLists.size(); i++) { - declaration += polyDLists.at(i).GetBodySourceCode(true); + declaration += + StringHelper::Sprintf("\t{ %s },", polyDLists.at(i).GetBodySourceCode().c_str()); if (i + 1 < polyDLists.size()) declaration += "\n"; } std::string polyDlistType = polyDLists.at(0).GetSourceTypeName(); - std::string polyDListName = ""; + std::string polyDListName; polyDListName = StringHelper::Sprintf("%s%s_%06X", prefix.c_str(), polyDlistType.c_str(), GETSEGOFFSET(start)); @@ -653,14 +586,16 @@ void PolygonType2::DeclareReferences(const std::string& prefix) polyDlistType, polyDListName, polyDLists.size(), declaration); } - parent->AddDeclaration(GETSEGOFFSET(end), DeclarationAlignment::Align4, - DeclarationPadding::Pad16, 4, "static s32", "terminatorMaybe", + parent->AddDeclaration(GETSEGOFFSET(end), DeclarationAlignment::Align4, 4, "s32", + StringHelper::Sprintf("%s_terminatorMaybe_%06X", + parent->GetName().c_str(), GETSEGOFFSET(end)), "0x01000000"); } std::string PolygonType2::GetBodySourceCode() const { - std::string listName = parent->GetDeclarationPtrName(start); + std::string listName; + Globals::Instance->GetSegmentedPtrName(start, parent, "", listName); std::string body = StringHelper::Sprintf("\n %i, %i,\n", type, polyDLists.size()); body += StringHelper::Sprintf(" %s,\n", listName.c_str()); @@ -673,3 +608,8 @@ size_t PolygonType2::GetRawDataSize() const { return 0x0C; } + +DeclarationAlignment PolygonType2::GetDeclarationAlignment() const +{ + return DeclarationAlignment::Align4; +} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetMesh.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetMesh.h index 20ec9c3ae2..566711a9a7 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetMesh.h +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetMesh.h @@ -5,51 +5,45 @@ #include "ZDisplayList.h" #include "ZRoom/ZRoomCommand.h" -class PolygonDlist +class PolygonDlist : public ZResource { public: - PolygonDlist() = default; - PolygonDlist(const std::string& prefix, const std::vector& nRawData, - uint32_t nRawDataIndex, ZFile* nParent, ZRoom* nRoom); + ZRoom* zRoom; - void ParseRawData(); - void DeclareReferences(const std::string& prefix); + uint8_t polyType; - size_t GetRawDataSize() const; - void SetPolyType(uint8_t nPolyType); - - void DeclareVar(const std::string& prefix, const std::string& bodyStr); - - std::string GetBodySourceCode(bool arrayElement); - void DeclareAndGenerateOutputCode(); - - static std::string GetDefaultName(const std::string& prefix, uint32_t address); - std::string GetSourceTypeName(); - std::string GetName(); - -protected: int16_t x, y, z; // polyType == 2 int16_t unk_06; // polyType == 2 segptr_t opa = 0; // Gfx* segptr_t xlu = 0; // Gfx* - uint8_t polyType; - ZDisplayList* opaDList = nullptr; // Gfx* ZDisplayList* xluDList = nullptr; // Gfx* - uint32_t rawDataIndex; - ZFile* parent; - ZRoom* zRoom; - std::string name; + PolygonDlist(ZFile* nParent); + void ParseRawData() override; + void DeclareReferences(const std::string& prefix) override; + + std::string GetBodySourceCode() const override; + + std::string GetSourceOutputCode(const std::string& prefix) override; + + std::string GetSourceTypeName() const override; + ZResourceType GetResourceType() const override; + + size_t GetRawDataSize() const override; + + void SetPolyType(uint8_t nPolyType); + +protected: ZDisplayList* MakeDlist(segptr_t ptr, const std::string& prefix); }; -class BgImage +class BgImage : public ZResource { -protected: +public: uint16_t unk_00; uint8_t id; segptr_t source; @@ -64,63 +58,44 @@ protected: ZBackground* sourceBackground; - uint32_t rawDataIndex; - ZFile* parent; - std::string name; bool isSubStruct; - void ParseRawData(); - ZBackground* MakeBackground(segptr_t ptr, const std::string& prefix); + BgImage(ZFile* nParent); + BgImage(bool nIsSubStruct, const std::string& prefix, uint32_t nRawDataIndex, ZFile* nParent); -public: - BgImage() = default; - BgImage(bool nIsSubStruct, const std::string& prefix, const std::vector& nRawData, - uint32_t nRawDataIndex, ZFile* nParent); + void ParseRawData() override; - static size_t GetRawDataSize(); + std::string GetBodySourceCode() const override; - std::string GetBodySourceCode(bool arrayElement) const; + std::string GetSourceTypeName() const override; + ZResourceType GetResourceType() const override; - static std::string GetDefaultName(const std::string& prefix, uint32_t address); - static std::string GetSourceTypeName(); - std::string GetName(); -}; - -class PolygonTypeBase -{ -public: - PolygonTypeBase(ZFile* nParent, const std::vector& nRawData, uint32_t nRawDataIndex, - ZRoom* nRoom); - - virtual void ParseRawData() = 0; - virtual void DeclareReferences(const std::string& prefix) = 0; - - virtual std::string GetBodySourceCode() const = 0; - void DeclareVar(const std::string& prefix, const std::string& bodyStr); - void DeclareAndGenerateOutputCode(const std::string& prefix); - - virtual std::string GetSourceTypeName() const; - - std::string GetName() const; - void SetName(const std::string& newName); - virtual size_t GetRawDataSize() const = 0; - - std::string GetDefaultName(const std::string& prefix) const; + size_t GetRawDataSize() const override; protected: - uint8_t type; + ZBackground* MakeBackground(segptr_t ptr, const std::string& prefix); +}; +class PolygonTypeBase : public ZResource +{ +public: + uint8_t type; std::vector polyDLists; - uint32_t rawDataIndex; - ZFile* parent; + PolygonTypeBase(ZFile* nParent, uint32_t nRawDataIndex, ZRoom* nRoom); + + void DeclareAndGenerateOutputCode(const std::string& prefix); + + std::string GetSourceTypeName() const override; + ZResourceType GetResourceType() const override; + +protected: ZRoom* zRoom; - std::string name; }; class PolygonType1 : public PolygonTypeBase { -protected: +public: uint8_t format; segptr_t dlist; @@ -132,9 +107,7 @@ protected: segptr_t list; // BgImage* std::vector multiList; -public: - PolygonType1(ZFile* nParent, const std::vector& nRawData, uint32_t nRawDataIndex, - ZRoom* nRoom); + PolygonType1(ZFile* nParent, uint32_t nRawDataIndex, ZRoom* nRoom); void ParseRawData() override; void DeclareReferences(const std::string& prefix) override; @@ -149,8 +122,11 @@ public: class PolygonType2 : public PolygonTypeBase { public: - PolygonType2(ZFile* nParent, const std::vector& nRawData, uint32_t nRawDataIndex, - ZRoom* nRoom); + uint8_t num; + segptr_t start; + segptr_t end; + + PolygonType2(ZFile* nParent, uint32_t nRawDataIndex, ZRoom* nRoom); void ParseRawData() override; void DeclareReferences(const std::string& prefix) override; @@ -158,16 +134,16 @@ public: std::string GetBodySourceCode() const override; size_t GetRawDataSize() const override; - -protected: - uint8_t num; - segptr_t start; - segptr_t end; + DeclarationAlignment GetDeclarationAlignment() const override; }; class SetMesh : public ZRoomCommand { public: + uint8_t data; + uint8_t meshHeaderType; + std::shared_ptr polyType; + SetMesh(ZFile* nParent); void ParseRawData() override; @@ -176,12 +152,8 @@ public: std::string GetBodySourceCode() const override; RoomCommand GetRoomCommand() const override; - size_t GetRawDataSize() const override; std::string GetCommandCName() const override; private: - uint8_t meshHeaderType; - std::shared_ptr polyType; - std::string GenDListExterns(ZDisplayList* dList); }; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetMinimapChests.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetMinimapChests.cpp index bd9c8a004a..ec432b7d99 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetMinimapChests.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetMinimapChests.cpp @@ -1,8 +1,8 @@ #include "SetMinimapChests.h" -#include "BitConverter.h" #include "Globals.h" -#include "StringHelper.h" +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" #include "ZFile.h" #include "ZRoom/ZRoom.h" @@ -28,7 +28,7 @@ void SetMinimapChests::ParseRawData() void SetMinimapChests::DeclareReferences(const std::string& prefix) { - std::string declaration = ""; + std::string declaration; size_t index = 0; for (const auto& chest : chests) @@ -42,14 +42,15 @@ void SetMinimapChests::DeclareReferences(const std::string& prefix) } parent->AddDeclarationArray( - segmentOffset, DeclarationAlignment::None, chests.size() * 10, "MinimapChest", + segmentOffset, DeclarationAlignment::Align4, chests.size() * 10, "MinimapChest", StringHelper::Sprintf("%sMinimapChests0x%06X", prefix.c_str(), segmentOffset), chests.size(), declaration); } std::string SetMinimapChests::GetBodySourceCode() const { - std::string listName = parent->GetDeclarationPtrName(cmdArg2); + std::string listName; + Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "MinimapChest", listName); return StringHelper::Sprintf("SCENE_CMD_MINIMAP_COMPASS_ICON_INFO(0x%02X, %s)", chests.size(), listName.c_str()); } @@ -64,11 +65,6 @@ RoomCommand SetMinimapChests::GetRoomCommand() const return RoomCommand::SetMinimapChests; } -size_t SetMinimapChests::GetRawDataSize() const -{ - return ZRoomCommand::GetRawDataSize() + (chests.size() * 10); -} - MinimapChest::MinimapChest(const std::vector& rawData, uint32_t rawDataIndex) : unk0(BitConverter::ToUInt16BE(rawData, rawDataIndex + 0)), unk2(BitConverter::ToUInt16BE(rawData, rawDataIndex + 2)), diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetMinimapChests.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetMinimapChests.h index b18534d5ef..0db09a8a25 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetMinimapChests.h +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetMinimapChests.h @@ -20,6 +20,8 @@ protected: class SetMinimapChests : public ZRoomCommand { public: + std::vector chests; + SetMinimapChests(ZFile* nParent); void ParseRawData() override; @@ -28,9 +30,5 @@ public: std::string GetBodySourceCode() const override; RoomCommand GetRoomCommand() const override; - size_t GetRawDataSize() const override; std::string GetCommandCName() const override; - -private: - std::vector chests; }; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetMinimapList.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetMinimapList.cpp index c94ef30d73..be5d8f15d1 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetMinimapList.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetMinimapList.cpp @@ -1,8 +1,8 @@ #include "SetMinimapList.h" -#include "BitConverter.h" #include "Globals.h" -#include "StringHelper.h" +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" #include "ZFile.h" #include "ZRoom/ZRoom.h" @@ -31,7 +31,7 @@ void SetMinimapList::ParseRawData() void SetMinimapList::DeclareReferences(const std::string& prefix) { { - std::string declaration = ""; + std::string declaration; size_t index = 0; for (const auto& entry : minimaps) @@ -51,7 +51,8 @@ void SetMinimapList::DeclareReferences(const std::string& prefix) } { - std::string listName = parent->GetDeclarationPtrName(listSegmentAddr); + std::string listName; + Globals::Instance->GetSegmentedPtrName(listSegmentAddr, parent, "MinimapEntry", listName); std::string declaration = StringHelper::Sprintf("\n\t%s, 0x%08X\n", listName.c_str(), unk4); parent->AddDeclaration( @@ -63,7 +64,8 @@ void SetMinimapList::DeclareReferences(const std::string& prefix) std::string SetMinimapList::GetBodySourceCode() const { - std::string listName = parent->GetDeclarationPtrName(cmdArg2); + std::string listName; + Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "MinimapList", listName); return StringHelper::Sprintf("SCENE_CMD_MINIMAP_INFO(%s)", listName.c_str()); } @@ -77,11 +79,6 @@ RoomCommand SetMinimapList::GetRoomCommand() const return RoomCommand::SetMinimapList; } -size_t SetMinimapList::GetRawDataSize() const -{ - return ZRoomCommand::GetRawDataSize() + (minimaps.size() * 10); -} - MinimapEntry::MinimapEntry(const std::vector& rawData, uint32_t rawDataIndex) : unk0(BitConverter::ToUInt16BE(rawData, rawDataIndex + 0)), unk2(BitConverter::ToUInt16BE(rawData, rawDataIndex + 2)), diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetMinimapList.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetMinimapList.h index 079e7b3a3c..5b18b3dd78 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetMinimapList.h +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetMinimapList.h @@ -20,6 +20,8 @@ protected: class SetMinimapList : public ZRoomCommand { public: + std::vector minimaps; + SetMinimapList(ZFile* nParent); void ParseRawData() override; @@ -28,12 +30,9 @@ public: std::string GetBodySourceCode() const override; RoomCommand GetRoomCommand() const override; - size_t GetRawDataSize() const override; std::string GetCommandCName() const override; private: - std::vector minimaps; - segptr_t listSegmentAddr; uint32_t listSegmentOffset; uint32_t unk4; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetObjectList.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetObjectList.cpp index d3184b4e62..fdd41e6cb4 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetObjectList.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetObjectList.cpp @@ -1,8 +1,8 @@ #include "SetObjectList.h" -#include "BitConverter.h" #include "Globals.h" -#include "StringHelper.h" +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" #include "ZFile.h" #include "ZRoom/ZNames.h" #include "ZRoom/ZRoom.h" @@ -23,16 +23,13 @@ void SetObjectList::ParseRawData() objects.push_back(objectIndex); currentPtr += 2; } - - if (segmentOffset != 0) - parent->AddDeclarationPlaceholder(segmentOffset); } void SetObjectList::DeclareReferences(const std::string& prefix) { if (!objects.empty()) { - std::string declaration = ""; + std::string declaration; for (size_t i = 0; i < objects.size(); i++) { @@ -45,7 +42,7 @@ void SetObjectList::DeclareReferences(const std::string& prefix) } parent->AddDeclarationArray( - segmentOffset, DeclarationAlignment::None, objects.size() * 2, "s16", + segmentOffset, DeclarationAlignment::Align4, objects.size() * 2, "s16", StringHelper::Sprintf("%sObjectList_%06X", prefix.c_str(), segmentOffset), objects.size(), declaration); } @@ -53,15 +50,11 @@ void SetObjectList::DeclareReferences(const std::string& prefix) std::string SetObjectList::GetBodySourceCode() const { - std::string listName = parent->GetDeclarationPtrName(cmdArg2); + std::string listName; + Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "s16", listName); return StringHelper::Sprintf("SCENE_CMD_OBJECT_LIST(%i, %s)", objects.size(), listName.c_str()); } -size_t SetObjectList::GetRawDataSize() const -{ - return ZRoomCommand::GetRawDataSize() + (objects.size() * 2); -} - std::string SetObjectList::GetCommandCName() const { return "SCmdObjectList"; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetObjectList.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetObjectList.h index c952333fb7..03c159483c 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetObjectList.h +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetObjectList.h @@ -5,17 +5,15 @@ class SetObjectList : public ZRoomCommand { public: + std::vector objects; + SetObjectList(ZFile* nParent); void ParseRawData() override; - void DeclareReferences(const std::string& prefix); + void DeclareReferences(const std::string& prefix) override; std::string GetBodySourceCode() const override; std::string GetCommandCName() const override; RoomCommand GetRoomCommand() const override; - size_t GetRawDataSize() const override; - -private: - std::vector objects; }; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetPathways.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetPathways.cpp index 13ee7a7cab..52d400a848 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetPathways.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetPathways.cpp @@ -1,7 +1,8 @@ #include "SetPathways.h" -#include "BitConverter.h" + #include "Globals.h" -#include "StringHelper.h" +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" #include "ZFile.h" #include "ZRoom/ZRoom.h" @@ -9,10 +10,14 @@ SetPathways::SetPathways(ZFile* nParent) : ZRoomCommand(nParent), pathwayList(nP { } -void SetPathways::DeclareReferences(const std::string& prefix) +void SetPathways::DeclareReferences([[maybe_unused]] const std::string& prefix) { if (segmentOffset != 0) - parent->AddDeclarationPlaceholder(segmentOffset); + { + std::string varName = + StringHelper::Sprintf("%sPathway_%06X", prefix.c_str(), segmentOffset); + parent->AddDeclarationPlaceholder(segmentOffset, varName); + } } void SetPathways::ParseRawDataLate() @@ -23,30 +28,24 @@ void SetPathways::ParseRawDataLate() pathwayList.SetNumPaths(numPaths); } - pathwayList.SetRawDataIndex(segmentOffset); - pathwayList.ParseRawData(); + pathwayList.ExtractFromFile(segmentOffset); } void SetPathways::DeclareReferencesLate(const std::string& prefix) { - pathwayList.SetName(StringHelper::Sprintf("%sPathway_%06X", prefix.c_str(), segmentOffset)); + std::string varName = StringHelper::Sprintf("%sPathway_%06X", prefix.c_str(), segmentOffset); + pathwayList.SetName(varName); pathwayList.DeclareReferences(prefix); pathwayList.GetSourceOutputCode(prefix); } std::string SetPathways::GetBodySourceCode() const { - std::string listName = parent->GetDeclarationPtrName(cmdArg2); + std::string listName; + Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "Path", listName); return StringHelper::Sprintf("SCENE_CMD_PATH_LIST(%s)", listName.c_str()); } -size_t SetPathways::GetRawDataSize() const -{ - int32_t size = pathwayList.GetRawDataSize(); - - return ZRoomCommand::GetRawDataSize() + size; -} - std::string SetPathways::GetCommandCName() const { return "SCmdPathList"; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetPathways.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetPathways.h index 30b765b564..9abc93d32e 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetPathways.h +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetPathways.h @@ -8,6 +8,8 @@ class SetPathways : public ZRoomCommand { public: + ZPath pathwayList; + SetPathways(ZFile* nParent); void DeclareReferences(const std::string& prefix) override; @@ -15,14 +17,8 @@ public: void ParseRawDataLate() override; void DeclareReferencesLate(const std::string& prefix) override; - void DeclareVar(const std::string& prefix, const std::string& bodyStr); - std::string GetBodySourceCode() const override; RoomCommand GetRoomCommand() const override; - size_t GetRawDataSize() const override; std::string GetCommandCName() const override; - -private: - ZPath pathwayList; }; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetRoomBehavior.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetRoomBehavior.cpp index d667328b78..8c6f4bf514 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetRoomBehavior.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetRoomBehavior.cpp @@ -1,7 +1,8 @@ #include "SetRoomBehavior.h" -#include "BitConverter.h" + #include "Globals.h" -#include "StringHelper.h" +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" SetRoomBehavior::SetRoomBehavior(ZFile* nParent) : ZRoomCommand(nParent) { diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetRoomBehavior.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetRoomBehavior.h index 7989ea37ab..47b772d77f 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetRoomBehavior.h +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetRoomBehavior.h @@ -5,16 +5,6 @@ class SetRoomBehavior : public ZRoomCommand { public: - SetRoomBehavior(ZFile* nParent); - - void ParseRawData() override; - - std::string GetBodySourceCode() const override; - - RoomCommand GetRoomCommand() const override; - std::string GetCommandCName() const override; - -protected: uint8_t gameplayFlags; uint32_t gameplayFlags2; @@ -27,4 +17,13 @@ protected: uint8_t enablePosLights; uint8_t kankyoContextUnkE2; + + SetRoomBehavior(ZFile* nParent); + + void ParseRawData() override; + + std::string GetBodySourceCode() const override; + + RoomCommand GetRoomCommand() const override; + std::string GetCommandCName() const override; }; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetRoomList.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetRoomList.cpp index 8cac82e87f..43c3968221 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetRoomList.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetRoomList.cpp @@ -1,8 +1,8 @@ #include "SetRoomList.h" -#include "BitConverter.h" #include "Globals.h" -#include "StringHelper.h" +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" #include "ZFile.h" #include "ZRoom/ZRoom.h" @@ -15,30 +15,28 @@ void SetRoomList::ParseRawData() ZRoomCommand::ParseRawData(); int numRooms = cmdArg1; - int32_t currentPtr = segmentOffset; + romfile = new RomFile(parent); + romfile->numRooms = numRooms; + romfile->ExtractFromFile(segmentOffset); - for (int32_t i = 0; i < numRooms; i++) - { - RoomEntry entry(parent->GetRawData(), currentPtr); - rooms.push_back(entry); - - currentPtr += 8; - } + parent->resources.push_back(romfile); zRoom->roomCount = numRooms; } void SetRoomList::DeclareReferences(const std::string& prefix) { - parent->AddDeclarationArray( - segmentOffset, DeclarationAlignment::None, rooms.size() * 8, "RomFile", - StringHelper::Sprintf("%sRoomList0x%06X", prefix.c_str(), segmentOffset), 0, ""); + ZRoomCommand::DeclareReferences(prefix); + + romfile->DeclareVar(prefix, ""); } std::string SetRoomList::GetBodySourceCode() const { - std::string listName = parent->GetDeclarationPtrName(cmdArg2); - return StringHelper::Sprintf("SCENE_CMD_ROOM_LIST(%i, %s)", rooms.size(), listName.c_str()); + std::string listName; + Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "RomFile", listName); + return StringHelper::Sprintf("SCENE_CMD_ROOM_LIST(%i, %s)", romfile->rooms.size(), + listName.c_str()); } std::string SetRoomList::GetCommandCName() const @@ -51,28 +49,93 @@ RoomCommand SetRoomList::GetRoomCommand() const return RoomCommand::SetRoomList; } -void SetRoomList::PreGenSourceFiles() +RomFile::RomFile(ZFile* nParent) : ZResource(nParent) { - std::string declaration = ""; +} + +void RomFile::ParseXML(tinyxml2::XMLElement* reader) +{ + ZResource::ParseXML(reader); + + if (reader->Attribute("NumRooms") != nullptr) + { + numRooms = StringHelper::StrToL(std::string(reader->Attribute("NumRooms"))); + } +} + +void RomFile::ParseRawData() +{ + ZResource::ParseRawData(); + + uint32_t currentPtr = rawDataIndex; + + for (int32_t i = 0; i < numRooms; i++) + { + RoomEntry entry(parent->GetRawData(), currentPtr); + rooms.push_back(entry); + + currentPtr += 8; + } +} + +Declaration* RomFile::DeclareVar(const std::string& prefix, const std::string& body) +{ + std::string auxName = name; + if (name == "") + auxName = StringHelper::Sprintf("%sRoomList0x%06X", prefix.c_str(), rawDataIndex); + + return parent->AddDeclarationArray(rawDataIndex, DeclarationAlignment::Align4, + rooms.size() * rooms.at(0).GetRawDataSize(), + GetSourceTypeName(), auxName, rooms.size(), body); +} + +std::string RomFile::GetBodySourceCode() const +{ + std::string declaration; + bool isFirst = true; for (ZFile* file : Globals::Instance->files) { for (ZResource* res : file->resources) { - if (res->GetResourceType() == ZResourceType::Room && res != zRoom) + if (res->GetResourceType() == ZResourceType::Room) { std::string roomName = res->GetName(); + if (!isFirst) + declaration += "\n"; + declaration += - StringHelper::Sprintf("\t{ (u32)_%sSegmentRomStart, (u32)_%sSegmentRomEnd },\n", + StringHelper::Sprintf("\t{ (u32)_%sSegmentRomStart, (u32)_%sSegmentRomEnd },", roomName.c_str(), roomName.c_str()); + isFirst = false; } } } - parent->AddDeclarationArray( - segmentOffset, DeclarationAlignment::None, rooms.size() * 8, "RomFile", - StringHelper::Sprintf("%sRoomList0x%06X", zRoom->GetName().c_str(), segmentOffset), 0, - declaration); + return declaration; +} + +std::string RomFile::GetSourceOutputCode(const std::string& prefix) +{ + DeclareVar(prefix, GetBodySourceCode()); + + return ""; +} + +std::string RomFile::GetSourceTypeName() const +{ + return "RomFile"; +} + +ZResourceType RomFile::GetResourceType() const +{ + // TODO + return ZResourceType::Error; +} + +size_t RomFile::GetRawDataSize() const +{ + return 8 * rooms.size(); } RoomEntry::RoomEntry(uint32_t nVAS, uint32_t nVAE) @@ -86,3 +149,8 @@ RoomEntry::RoomEntry(const std::vector& rawData, uint32_t rawDataIndex) BitConverter::ToInt32BE(rawData, rawDataIndex + 4)) { } + +size_t RoomEntry::GetRawDataSize() const +{ + return 0x08; +} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetRoomList.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetRoomList.h index eaa2013f4d..4fb2ced176 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetRoomList.h +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetRoomList.h @@ -5,28 +5,49 @@ class RoomEntry { public: + int32_t virtualAddressStart; + int32_t virtualAddressEnd; + RoomEntry(uint32_t nVAS, uint32_t nVAE); RoomEntry(const std::vector& rawData, uint32_t rawDataIndex); -protected: - int32_t virtualAddressStart; - int32_t virtualAddressEnd; + size_t GetRawDataSize() const; +}; + +class RomFile : public ZResource +{ +public: + RomFile(ZFile* nParent); + + void ParseXML(tinyxml2::XMLElement* reader) override; + void ParseRawData() override; + + Declaration* DeclareVar(const std::string& prefix, const std::string& body) override; + std::string GetBodySourceCode() const override; + std::string GetSourceOutputCode(const std::string& prefix) override; + + std::string GetSourceTypeName() const override; + virtual ZResourceType GetResourceType() const override; + + virtual size_t GetRawDataSize() const override; + + uint8_t numRooms = 0; + std::vector rooms; }; class SetRoomList : public ZRoomCommand { public: + // Borrowed reference. Don't delete. + RomFile* romfile = nullptr; + SetRoomList(ZFile* nParent); void ParseRawData() override; - virtual void DeclareReferences(const std::string& prefix); + void DeclareReferences(const std::string& prefix) override; std::string GetBodySourceCode() const override; - void PreGenSourceFiles() override; RoomCommand GetRoomCommand() const override; std::string GetCommandCName() const override; - -private: - std::vector rooms; }; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSkyboxModifier.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetSkyboxModifier.cpp index d8af2d11f1..b16f1355b2 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSkyboxModifier.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetSkyboxModifier.cpp @@ -1,6 +1,6 @@ #include "SetSkyboxModifier.h" -#include "StringHelper.h" +#include "Utils/StringHelper.h" SetSkyboxModifier::SetSkyboxModifier(ZFile* nParent) : ZRoomCommand(nParent) { diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSkyboxModifier.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetSkyboxModifier.h index 1b0e02231d..65935bf928 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSkyboxModifier.h +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetSkyboxModifier.h @@ -5,6 +5,9 @@ class SetSkyboxModifier : public ZRoomCommand { public: + uint8_t disableSky; + uint8_t disableSunMoon; + SetSkyboxModifier(ZFile* nParent); void ParseRawData() override; @@ -13,8 +16,4 @@ public: std::string GetCommandCName() const override; RoomCommand GetRoomCommand() const override; - -private: - uint8_t disableSky; - uint8_t disableSunMoon; }; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSkyboxSettings.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetSkyboxSettings.cpp index 43c5c1e9cd..d5ae7ef761 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSkyboxSettings.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetSkyboxSettings.cpp @@ -1,6 +1,6 @@ #include "SetSkyboxSettings.h" #include "Globals.h" -#include "StringHelper.h" +#include "Utils/StringHelper.h" SetSkyboxSettings::SetSkyboxSettings(ZFile* nParent) : ZRoomCommand(nParent) { diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSkyboxSettings.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetSkyboxSettings.h index 380addcf0f..1c7e01ad40 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSkyboxSettings.h +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetSkyboxSettings.h @@ -5,6 +5,11 @@ class SetSkyboxSettings : public ZRoomCommand { public: + uint8_t unk1; // (MM Only) + uint8_t skyboxNumber; + uint8_t cloudsType; + uint8_t isIndoors; + SetSkyboxSettings(ZFile* nParent); void ParseRawData() override; @@ -13,10 +18,4 @@ public: std::string GetCommandCName() const override; RoomCommand GetRoomCommand() const override; - -private: - uint8_t unk1; // (MM Only) - uint8_t skyboxNumber; - uint8_t cloudsType; - uint8_t isIndoors; }; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSoundSettings.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetSoundSettings.cpp index 9472468cec..54b91328fb 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSoundSettings.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetSoundSettings.cpp @@ -1,5 +1,5 @@ #include "SetSoundSettings.h" -#include "StringHelper.h" +#include "Utils/StringHelper.h" SetSoundSettings::SetSoundSettings(ZFile* nParent) : ZRoomCommand(nParent) { diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSoundSettings.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetSoundSettings.h index 0e35af7d12..f378e5e4ed 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSoundSettings.h +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetSoundSettings.h @@ -5,6 +5,10 @@ class SetSoundSettings : public ZRoomCommand { public: + uint8_t reverb; + uint8_t nightTimeSFX; + uint8_t musicSequence; + SetSoundSettings(ZFile* nParent); void ParseRawData() override; @@ -13,9 +17,4 @@ public: RoomCommand GetRoomCommand() const override; std::string GetCommandCName() const override; - -private: - uint8_t reverb; - uint8_t nightTimeSFX; - uint8_t musicSequence; }; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSpecialObjects.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetSpecialObjects.cpp index b202c4d9d3..0c24a2f328 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSpecialObjects.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetSpecialObjects.cpp @@ -1,6 +1,6 @@ #include "SetSpecialObjects.h" -#include "BitConverter.h" -#include "StringHelper.h" +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" SetSpecialObjects::SetSpecialObjects(ZFile* nParent) : ZRoomCommand(nParent) { diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSpecialObjects.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetSpecialObjects.h index 959133d9e2..3327d44c38 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSpecialObjects.h +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetSpecialObjects.h @@ -5,6 +5,9 @@ class SetSpecialObjects : public ZRoomCommand { public: + uint8_t elfMessage; + uint16_t globalObject; + SetSpecialObjects(ZFile* nParent); void ParseRawData() override; @@ -13,8 +16,4 @@ public: RoomCommand GetRoomCommand() const override; std::string GetCommandCName() const override; - -private: - uint8_t elfMessage; - uint16_t globalObject; }; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetStartPositionList.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetStartPositionList.cpp index 01bd1bf6e0..f75b5e0d5e 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetStartPositionList.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetStartPositionList.cpp @@ -1,8 +1,8 @@ #include "SetStartPositionList.h" -#include "BitConverter.h" #include "Globals.h" -#include "StringHelper.h" +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" #include "ZFile.h" #include "ZRoom/ZNames.h" #include "ZRoom/ZRoom.h" @@ -29,7 +29,7 @@ void SetStartPositionList::DeclareReferences(const std::string& prefix) { if (!actors.empty()) { - std::string declaration = ""; + std::string declaration; size_t index = 0; for (const auto& entry : actors) @@ -43,14 +43,15 @@ void SetStartPositionList::DeclareReferences(const std::string& prefix) parent->AddDeclarationArray( segmentOffset, DeclarationAlignment::Align4, actors.size() * 16, "ActorEntry", - StringHelper::Sprintf("%sStartPositionList0x%06X", prefix.c_str(), segmentOffset), 0, - declaration); + StringHelper::Sprintf("%sStartPositionList0x%06X", prefix.c_str(), segmentOffset), + actors.size(), declaration); } } std::string SetStartPositionList::GetBodySourceCode() const { - std::string listName = parent->GetDeclarationPtrName(cmdArg2); + std::string listName; + Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "ActorEntry", listName); return StringHelper::Sprintf("SCENE_CMD_SPAWN_LIST(%i, %s)", actors.size(), listName.c_str()); } diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetStartPositionList.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetStartPositionList.h index 02cf7c65ad..10075adf3c 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetStartPositionList.h +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetStartPositionList.h @@ -6,6 +6,8 @@ class SetStartPositionList : public ZRoomCommand { public: + std::vector actors; + SetStartPositionList(ZFile* nParent); void ParseRawData() override; @@ -15,7 +17,4 @@ public: RoomCommand GetRoomCommand() const override; std::string GetCommandCName() const override; - -private: - std::vector actors; }; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetTimeSettings.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetTimeSettings.cpp index 708c421228..9d4d356df7 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetTimeSettings.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetTimeSettings.cpp @@ -1,6 +1,6 @@ #include "SetTimeSettings.h" -#include "BitConverter.h" -#include "StringHelper.h" +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" SetTimeSettings::SetTimeSettings(ZFile* nParent) : ZRoomCommand(nParent) { diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetTimeSettings.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetTimeSettings.h index cafafc16e4..7ff2711d4e 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetTimeSettings.h +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetTimeSettings.h @@ -5,6 +5,10 @@ class SetTimeSettings : public ZRoomCommand { public: + uint8_t hour; + uint8_t min; + uint8_t unk; + SetTimeSettings(ZFile* nParent); void ParseRawData() override; @@ -13,9 +17,4 @@ public: std::string GetCommandCName() const override; RoomCommand GetRoomCommand() const override; - -private: - uint8_t hour; - uint8_t min; - uint8_t unk; }; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetTransitionActorList.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetTransitionActorList.cpp index 9d70e6d7b2..a33d1c6e1c 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetTransitionActorList.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetTransitionActorList.cpp @@ -1,8 +1,8 @@ #include "SetTransitionActorList.h" -#include "BitConverter.h" #include "Globals.h" -#include "StringHelper.h" +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" #include "ZFile.h" #include "ZRoom/ZNames.h" #include "ZRoom/ZRoom.h" @@ -28,7 +28,7 @@ void SetTransitionActorList::ParseRawData() void SetTransitionActorList::DeclareReferences(const std::string& prefix) { - std::string declaration = ""; + std::string declaration; size_t index = 0; for (const auto& entry : transitionActors) @@ -43,24 +43,20 @@ void SetTransitionActorList::DeclareReferences(const std::string& prefix) } parent->AddDeclarationArray( - segmentOffset, DeclarationAlignment::None, transitionActors.size() * 16, + segmentOffset, DeclarationAlignment::Align4, transitionActors.size() * 16, "TransitionActorEntry", - StringHelper::Sprintf("%sTransitionActorList_%06X", prefix.c_str(), segmentOffset), 0, - declaration); + StringHelper::Sprintf("%sTransitionActorList_%06X", prefix.c_str(), segmentOffset), + transitionActors.size(), declaration); } std::string SetTransitionActorList::GetBodySourceCode() const { - std::string listName = parent->GetDeclarationPtrName(cmdArg2); + std::string listName; + Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "TransitionActorEntry", listName); return StringHelper::Sprintf("SCENE_CMD_TRANSITION_ACTOR_LIST(%i, %s)", transitionActors.size(), listName.c_str()); } -size_t SetTransitionActorList::GetRawDataSize() const -{ - return ZRoomCommand::GetRawDataSize() + (transitionActors.size() * 16); -} - std::string SetTransitionActorList::GetCommandCName() const { return "SCmdTransiActorList"; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetTransitionActorList.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetTransitionActorList.h index dba7a80e8c..a5ce2e66fd 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetTransitionActorList.h +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetTransitionActorList.h @@ -5,11 +5,6 @@ class TransitionActorEntry { public: - TransitionActorEntry(const std::vector& rawData, int rawDataIndex); - - std::string GetBodySourceCode() const; - -protected: uint8_t frontObjectRoom; uint8_t frontTransitionReaction; uint8_t backObjectRoom; @@ -18,11 +13,17 @@ protected: int16_t posX, posY, posZ; int16_t rotY; uint16_t initVar; + + TransitionActorEntry(const std::vector& rawData, int rawDataIndex); + + std::string GetBodySourceCode() const; }; class SetTransitionActorList : public ZRoomCommand { public: + std::vector transitionActors; + SetTransitionActorList(ZFile* nParent); void ParseRawData() override; @@ -31,9 +32,5 @@ public: std::string GetBodySourceCode() const override; RoomCommand GetRoomCommand() const override; - size_t GetRawDataSize() const override; std::string GetCommandCName() const override; - -private: - std::vector transitionActors; }; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetWind.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetWind.cpp index 3b50c811f1..1893b56018 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetWind.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetWind.cpp @@ -1,5 +1,5 @@ #include "SetWind.h" -#include "StringHelper.h" +#include "Utils/StringHelper.h" SetWind::SetWind(ZFile* nParent) : ZRoomCommand(nParent) { diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetWind.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetWind.h index 8e00b4fd8d..05eaafeda8 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetWind.h +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetWind.h @@ -5,6 +5,11 @@ class SetWind : public ZRoomCommand { public: + uint8_t windWest; + uint8_t windVertical; + uint8_t windSouth; + uint8_t clothFlappingStrength; + SetWind(ZFile* nParent); void ParseRawData() override; @@ -13,10 +18,4 @@ public: std::string GetCommandCName() const override; RoomCommand GetRoomCommand() const override; - -private: - uint8_t windWest; - uint8_t windVertical; - uint8_t windSouth; - uint8_t clothFlappingStrength; }; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetWorldMapVisited.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetWorldMapVisited.cpp index 4420c9d4fe..d20e4a3e29 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetWorldMapVisited.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/SetWorldMapVisited.cpp @@ -1,6 +1,6 @@ #include "SetWorldMapVisited.h" -#include "StringHelper.h" +#include "Utils/StringHelper.h" SetWorldMapVisited::SetWorldMapVisited(ZFile* nParent) : ZRoomCommand(nParent) { diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/Unused09.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/Unused09.cpp index 69db353a49..9dfcaa5c23 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/Unused09.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/Unused09.cpp @@ -1,5 +1,5 @@ #include "Unused09.h" -#include "StringHelper.h" +#include "Utils/StringHelper.h" Unused09::Unused09(ZFile* nParent) : ZRoomCommand(nParent) { @@ -7,12 +7,12 @@ Unused09::Unused09(ZFile* nParent) : ZRoomCommand(nParent) std::string Unused09::GetBodySourceCode() const { - return StringHelper::Sprintf("{ %s, 0x00, 0x00 }", GetCommandHex().c_str()); + return "SCENE_CMD_UNK_09()"; } std::string Unused09::GetCommandCName() const { - return "SCmdBase"; + return "SceneCmd"; } RoomCommand Unused09::GetRoomCommand() const diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/Unused1D.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/Unused1D.cpp index 14ac6e410a..b8ea13652f 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/Unused1D.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/Unused1D.cpp @@ -1,5 +1,5 @@ #include "Unused1D.h" -#include "StringHelper.h" +#include "Utils/StringHelper.h" Unused1D::Unused1D(ZFile* nParent) : ZRoomCommand(nParent) { @@ -12,7 +12,7 @@ std::string Unused1D::GetBodySourceCode() const std::string Unused1D::GetCommandCName() const { - return "SCmdBase"; + return "SceneCmd"; } RoomCommand Unused1D::GetRoomCommand() const diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/ZRoomCommandUnk.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/ZRoomCommandUnk.cpp index 3f35c13182..a892086c2a 100644 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/ZRoomCommandUnk.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/Commands/ZRoomCommandUnk.cpp @@ -1,6 +1,6 @@ #include "ZRoomCommandUnk.h" -#include "BitConverter.h" -#include "StringHelper.h" +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" #include "ZRoom/ZRoom.h" ZRoomCommandUnk::ZRoomCommandUnk(ZFile* nParent) : ZRoomCommand(nParent) diff --git a/tools/ZAPD/ZAPD/ZRoom/ZNames.h b/tools/ZAPD/ZAPD/ZRoom/ZNames.h index bee03869e0..94e08de0d2 100644 --- a/tools/ZAPD/ZAPD/ZRoom/ZNames.h +++ b/tools/ZAPD/ZAPD/ZRoom/ZNames.h @@ -3,7 +3,7 @@ #include #include "Globals.h" -#include "StringHelper.h" +#include "Utils/StringHelper.h" class ZNames { @@ -29,7 +29,7 @@ public: { int32_t flags = id & 0xF000; id &= 0xFFF; - std::string name = ""; + std::string name; if (id < ZNames::GetNumActors()) name = Globals::Instance->cfg.actorList.at(id); else diff --git a/tools/ZAPD/ZAPD/ZRoom/ZRoom.cpp b/tools/ZAPD/ZAPD/ZRoom/ZRoom.cpp index 32dad6106f..edc0cad029 100644 --- a/tools/ZAPD/ZAPD/ZRoom/ZRoom.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/ZRoom.cpp @@ -1,11 +1,8 @@ #include "ZRoom.h" -#include #include +#include #include -#include "../File.h" -#include "../Globals.h" -#include "../StringHelper.h" -#include "../ZBlob.h" +#include #include "Commands/EndMarker.h" #include "Commands/SetActorCutsceneList.h" #include "Commands/SetActorList.h" @@ -39,13 +36,17 @@ #include "Commands/Unused09.h" #include "Commands/Unused1D.h" #include "Commands/ZRoomCommandUnk.h" +#include "Globals.h" +#include "Utils/File.h" +#include "Utils/Path.h" +#include "Utils/StringHelper.h" +#include "ZBlob.h" #include "ZCutscene.h" #include "ZFile.h" -using namespace tinyxml2; - REGISTER_ZFILENODE(Room, ZRoom); REGISTER_ZFILENODE(Scene, ZRoom); +REGISTER_ZFILENODE(AltHeader, ZRoom); ZRoom::ZRoom(ZFile* nParent) : ZResource(nParent) { @@ -64,122 +65,84 @@ void ZRoom::ExtractFromXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex) { ZResource::ExtractFromXML(reader, nRawDataIndex); - scene = Globals::Instance->lastScene; - - if (std::string(reader->Name()) == "Scene") - { - scene = this; - Globals::Instance->lastScene = this; - } - - uint32_t cmdCount = UINT32_MAX; - - if (name == "syotes_room_0") + if (hackMode == "syotes_room") { SyotesRoomHack(); - cmdCount = 0; } - - for (XMLElement* child = reader->FirstChildElement(); child != nullptr; - child = child->NextSiblingElement()) + else { - std::string childName = - child->Attribute("Name") == NULL ? "" : std::string(child->Attribute("Name")); - std::string childComment = child->Attribute("Comment") == NULL ? - "" : - "// " + std::string(child->Attribute("Comment")) + "\n"; - - // TODO: Bunch of repeated code between all of these that needs to be combined. - if (std::string(child->Name()) == "DListHint") - { - std::string addressStr = child->Attribute("Offset"); - int32_t address = strtol(StringHelper::Split(addressStr, "0x")[1].c_str(), NULL, 16); - - ZDisplayList* dList = new ZDisplayList( - address, - ZDisplayList::GetDListLength(parent->GetRawData(), address, - Globals::Instance->game == ZGame::OOT_SW97 ? - DListType::F3DEX : - DListType::F3DZEX), - parent); - dList->SetInnerNode(true); - - dList->GetSourceOutputCode(name); - delete dList; - } - else if (std::string(child->Name()) == "CutsceneHint") - { - std::string addressStr = child->Attribute("Offset"); - int32_t address = strtol(StringHelper::Split(addressStr, "0x")[1].c_str(), NULL, 16); - - ZCutscene* cutscene = new ZCutscene(parent); - cutscene->SetInnerNode(true); - cutscene->ExtractFromXML(child, address); - - cutscene->GetSourceOutputCode(name); - - delete cutscene; - } - else if (std::string(child->Name()) == "AltHeaderHint") - { - std::string addressStr = child->Attribute("Offset"); - int32_t address = strtol(StringHelper::Split(addressStr, "0x")[1].c_str(), NULL, 16); - - uint32_t commandsCount = UINT32_MAX; - - if (child->FindAttribute("Count") != NULL) - { - std::string commandCountStr = child->Attribute("Count"); - commandsCount = strtol(commandCountStr.c_str(), NULL, 10); - } - - commandSets.push_back(CommandSet(address, commandsCount)); - } - else if (std::string(child->Name()) == "PathHint") - { - std::string addressStr = child->Attribute("Offset"); - int32_t address = strtol(StringHelper::Split(addressStr, "0x")[1].c_str(), NULL, 16); - - // TODO: add this to command set - ZPath* pathway = new ZPath(parent); - pathway->SetInnerNode(true); - pathway->SetRawDataIndex(address); - pathway->ParseRawData(); - pathway->DeclareReferences(name); - pathway->GetSourceOutputCode(name); - - delete pathway; - } - -#ifdef DEPRECATION_ON - fprintf(stderr, - "ZRoom::ExtractFromXML: Deprecation warning in '%s'.\n" - "\t The resource '%s' is currently deprecated, and will be removed in a future " - "version.\n" - "\t Use the non-hint version instead.\n", - name.c_str(), child->Name()); -#endif + DeclareVar(name, ""); } - - commandSets.push_back(CommandSet(rawDataIndex, cmdCount)); - ProcessCommandSets(); } -void ZRoom::ParseCommands(std::vector& commandList, CommandSet commandSet) +void ZRoom::ExtractFromBinary(uint32_t nRawDataIndex, ZResourceType parentType) { + rawDataIndex = nRawDataIndex; + name = GetDefaultName(parent->GetName()); + + zroomType = ZResourceType::AltHeader; + switch (parentType) + { + case ZResourceType::Scene: + case ZResourceType::Room: + case ZResourceType::AltHeader: + parentZroomType = parentType; + break; + + default: + // TODO: error message or something + assert(false); + break; + } + + ParseRawData(); + DeclareVar(name, ""); +} + +void ZRoom::ParseXML(tinyxml2::XMLElement* reader) +{ + ZResource::ParseXML(reader); + + // TODO: HACK: remove this specific check when the repo uses the correct HackMode="syotes_room" + if (name == "syotes_room_0") + { + hackMode = "syotes_room"; + } + + std::string nodeName = std::string(reader->Name()); + if (nodeName == "Scene") + { + zroomType = ZResourceType::Scene; + } + else if (nodeName == "Room") + zroomType = ZResourceType::Room; + else if (nodeName == "AltHeader") + zroomType = ZResourceType::AltHeader; + + if (reader->Attribute("HackMode") != nullptr) + { + hackMode = std::string(reader->Attribute("HackMode")); + if (hackMode != "syotes_room") + throw std::runtime_error( + StringHelper::Sprintf("ZRoom::ParseXML: Fatal error in '%s'.\n" + "\t Invalid value for attribute 'HackMode': '%s'\n", + name.c_str(), hackMode.c_str())); + } +} + +void ZRoom::ParseRawData() +{ + if (hackMode == "syotes_room") + return; + bool shouldContinue = true; uint32_t currentIndex = 0; - uint32_t rawDataIndex = GETSEGOFFSET(commandSet.address); - - uint32_t commandsLeft = commandSet.commandCount; + uint32_t currentPtr = rawDataIndex; const auto& rawData = parent->GetRawData(); while (shouldContinue) { - if (commandsLeft <= 0) - break; - - RoomCommand opcode = static_cast(rawData.at(rawDataIndex)); + RoomCommand opcode = static_cast(rawData.at(currentPtr)); ZRoomCommand* cmd = nullptr; @@ -287,8 +250,8 @@ void ZRoom::ParseCommands(std::vector& commandList, CommandSet co cmd = new ZRoomCommandUnk(parent); } - cmd->ExtractCommandFromRoom(this, rawDataIndex); - cmd->DeclareReferences(GetName()); + cmd->commandSet = rawDataIndex; + cmd->ExtractCommandFromRoom(this, currentPtr); if (Globals::Instance->profile) { @@ -300,74 +263,82 @@ void ZRoom::ParseCommands(std::vector& commandList, CommandSet co cmd->cmdIndex = currentIndex; - commandList.push_back(cmd); + commands.push_back(cmd); if (opcode == RoomCommand::EndMarker) shouldContinue = false; - rawDataIndex += 8; + currentPtr += 8; currentIndex++; - - commandsLeft--; } } -void ZRoom::ProcessCommandSets() +void ZRoom::DeclareReferences(const std::string& prefix) { - while (commandSets.size() > 0) + for (auto& cmd : commands) + cmd->DeclareReferences(prefix); +} + +void ZRoom::ParseRawDataLate() +{ + for (auto& cmd : commands) + cmd->ParseRawDataLate(); +} + +void ZRoom::DeclareReferencesLate(const std::string& prefix) +{ + for (auto& cmd : commands) + cmd->DeclareReferencesLate(prefix); +} + +Declaration* ZRoom::DeclareVar(const std::string& prefix, const std::string& body) +{ + std::string auxName = name; + if (auxName == "") + auxName = GetDefaultName(prefix); + if (zroomType == ZResourceType::Scene || zroomType == ZResourceType::Room) + auxName = StringHelper::Sprintf("%sCommands", name.c_str()); + + Declaration* decl = + parent->AddDeclarationArray(rawDataIndex, GetDeclarationAlignment(), GetRawDataSize(), + GetSourceTypeName(), auxName, commands.size(), body); + decl->staticConf = staticConf; + return decl; +} + +std::string ZRoom::GetBodySourceCode() const +{ + std::string declaration; + + for (size_t i = 0; i < commands.size(); i++) { - std::vector setCommands = std::vector(); + ZRoomCommand* cmd = commands[i]; + declaration += StringHelper::Sprintf("\t%s,", cmd->GetBodySourceCode().c_str()); - int32_t commandSet = commandSets[0].address; - ParseCommands(setCommands, commandSets[0]); - commandSets.erase(commandSets.begin()); - - for (auto& cmd : setCommands) - { - cmd->ParseRawDataLate(); - cmd->DeclareReferencesLate(name); - } - - if (!setCommands.empty()) - { - std::string declaration = ""; - - for (size_t i = 0; i < setCommands.size(); i++) - { - ZRoomCommand* cmd = setCommands[i]; - cmd->commandSet = GETSEGOFFSET(commandSet); - declaration += StringHelper::Sprintf("\t%s,", cmd->GetBodySourceCode().c_str()); - - if (i + 1 < setCommands.size()) - declaration += "\n"; - } - - parent->AddDeclarationArray( - GETSEGOFFSET(commandSet), DeclarationAlignment::Align16, 8 * setCommands.size(), - "static SCmdBase", - StringHelper::Sprintf("%sSet%04X", name.c_str(), GETSEGOFFSET(commandSet)), - setCommands.size(), declaration); - - sourceOutput += "\n"; - - for (ZRoomCommand* cmd : setCommands) - commands.push_back(cmd); - } + if (i + 1 < commands.size()) + declaration += "\n"; } + + return declaration; +} + +std::string ZRoom::GetDefaultName(const std::string& prefix) const +{ + return StringHelper::Sprintf("%sSet_%06X", prefix.c_str(), rawDataIndex); } /* - * There is one room in Ocarina of Time that lacks a header. Room 120, "Syotes", dates back to very - * early in the game's development. Since this room is a special case, this hack adds back a header - * so that the room can be processed properly. + * There is one room in Ocarina of Time that lacks a header. Room 120, "Syotes", dates + * back to very early in the game's development. Since this room is a special case, + * declare automatically the data its contains whitout the need of a header. */ void ZRoom::SyotesRoomHack() { - PolygonType2 poly(parent, parent->GetRawData(), 0, this); + PolygonType2 poly(parent, 0, this); poly.ParseRawData(); poly.DeclareReferences(GetName()); - parent->AddDeclaration(0, DeclarationAlignment::Align4, poly.GetRawDataSize(), + parent->AddDeclaration(0, poly.GetDeclarationAlignment(), poly.GetRawDataSize(), poly.GetSourceTypeName(), poly.GetDefaultName(GetName()), poly.GetBodySourceCode()); } @@ -421,26 +392,14 @@ size_t ZRoom::GetCommandSizeFromNeighbor(ZRoomCommand* cmd) return 0; } -std::string ZRoom::GetSourceOutputHeader(const std::string& prefix) +std::string ZRoom::GetSourceOutputCode([[maybe_unused]] const std::string& prefix) { - return "\n" + extDefines + "\n\n"; -} + if (hackMode == "syotes_room") + return ""; -std::string ZRoom::GetSourceOutputCode(const std::string& prefix) -{ - sourceOutput = ""; + DeclareVar(prefix, GetBodySourceCode()); - sourceOutput += "#include \"segment_symbols.h\"\n"; - sourceOutput += "#include \"command_macros_base.h\"\n"; - sourceOutput += "#include \"z64cutscene_commands.h\"\n"; - sourceOutput += "#include \"variables.h\"\n"; - - if (scene != nullptr) - sourceOutput += scene->parent->GetHeaderInclude(); - - ProcessCommandSets(); - - return sourceOutput; + return ""; } size_t ZRoom::GetRawDataSize() const @@ -453,21 +412,14 @@ size_t ZRoom::GetRawDataSize() const return size; } +std::string ZRoom::GetSourceTypeName() const +{ + return "SceneCmd"; +} + ZResourceType ZRoom::GetResourceType() const { - return ZResourceType::Room; -} - -void ZRoom::PreGenSourceFiles() -{ - for (ZRoomCommand* cmd : commands) - cmd->PreGenSourceFiles(); -} - -/* CommandSet */ - -CommandSet::CommandSet(uint32_t nAddress, uint32_t nCommandCount) -{ - address = nAddress; - commandCount = nCommandCount; + assert(zroomType == ZResourceType::Scene || zroomType == ZResourceType::Room || + zroomType == ZResourceType::AltHeader); + return zroomType; } diff --git a/tools/ZAPD/ZAPD/ZRoom/ZRoom.h b/tools/ZAPD/ZAPD/ZRoom/ZRoom.h index 518ca82bb8..0993a9d302 100644 --- a/tools/ZAPD/ZAPD/ZRoom/ZRoom.h +++ b/tools/ZAPD/ZAPD/ZRoom/ZRoom.h @@ -8,42 +8,43 @@ #include "ZRoomCommand.h" #include "tinyxml2.h" -struct CommandSet -{ - uint32_t address; - uint32_t commandCount; // Only used if explicitly specified in the XML - - CommandSet(uint32_t nAddress, uint32_t nCommandCount = UINT32_MAX); -}; - class ZRoom : public ZResource { -protected: - std::vector commands; - - std::string GetSourceOutputHeader(const std::string& prefix) override; - std::string GetSourceOutputCode(const std::string& prefix) override; - void ProcessCommandSets(); - void SyotesRoomHack(); - public: - ZRoom* scene; - std::vector commandSets; + std::vector commands; int32_t roomCount; // Only valid for scenes - std::string extDefines; + std::string hackMode; + + ZResourceType zroomType = ZResourceType::Error; + ZResourceType parentZroomType = ZResourceType::Error; ZRoom(ZFile* nParent); virtual ~ZRoom(); void ExtractFromXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex) override; + void ExtractFromBinary(uint32_t nRawDataIndex, ZResourceType parentType); - void ParseCommands(std::vector& commandList, CommandSet commandSet); + void ParseXML(tinyxml2::XMLElement* reader) override; + void ParseRawData() override; + void DeclareReferences(const std::string& prefix) override; + void ParseRawDataLate() override; + void DeclareReferencesLate(const std::string& prefix) override; + + Declaration* DeclareVar(const std::string& prefix, const std::string& body) override; + std::string GetBodySourceCode() const override; + + std::string GetSourceOutputCode(const std::string& prefix) override; + + std::string GetDefaultName(const std::string& prefix) const override; size_t GetDeclarationSizeFromNeighbor(uint32_t declarationAddress); size_t GetCommandSizeFromNeighbor(ZRoomCommand* cmd); ZRoomCommand* FindCommandOfType(RoomCommand cmdType); size_t GetRawDataSize() const override; + std::string GetSourceTypeName() const override; ZResourceType GetResourceType() const override; - void PreGenSourceFiles() override; + +protected: + void SyotesRoomHack(); }; diff --git a/tools/ZAPD/ZAPD/ZRoom/ZRoomCommand.cpp b/tools/ZAPD/ZAPD/ZRoom/ZRoomCommand.cpp index 6c45c32c65..711c86a409 100644 --- a/tools/ZAPD/ZAPD/ZRoom/ZRoomCommand.cpp +++ b/tools/ZAPD/ZAPD/ZRoom/ZRoomCommand.cpp @@ -1,7 +1,7 @@ #include "ZRoomCommand.h" -#include "BitConverter.h" -#include "StringHelper.h" +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" #include "ZRoom.h" ZRoomCommand::ZRoomCommand(ZFile* nParent) : ZResource(nParent) @@ -24,25 +24,12 @@ void ZRoomCommand::ParseRawData() cmdArg1 = parentRawData.at(rawDataIndex + 1); cmdArg2 = BitConverter::ToUInt32BE(parentRawData, rawDataIndex + 4); - segmentOffset = GETSEGOFFSET(cmdArg2); + segmentOffset = Seg2Filespace(cmdArg2, parent->baseAddress); } -void ZRoomCommand::ParseRawDataLate() +RoomCommand ZRoomCommand::GetRoomCommand() const { -} - -void ZRoomCommand::DeclareReferencesLate(const std::string& prefix) -{ -} - -std::string ZRoomCommand::GetCommandCName() const -{ - return "SCmdBase"; -} - -ZResourceType ZRoomCommand::GetResourceType() const -{ - return ZResourceType::RoomCommand; + return RoomCommand::Error; } size_t ZRoomCommand::GetRawDataSize() const @@ -50,6 +37,21 @@ size_t ZRoomCommand::GetRawDataSize() const return 0x08; } +std::string ZRoomCommand::GetSourceTypeName() const +{ + return GetCommandCName(); +} + +ZResourceType ZRoomCommand::GetResourceType() const +{ + return ZResourceType::RoomCommand; +} + +std::string ZRoomCommand::GetCommandCName() const +{ + return "SceneCmd"; +} + std::string ZRoomCommand::GetCommandHex() const { return StringHelper::Sprintf("0x%02X", static_cast(cmdID)); diff --git a/tools/ZAPD/ZAPD/ZRoom/ZRoomCommand.h b/tools/ZAPD/ZAPD/ZRoom/ZRoomCommand.h index e428704fd0..e4029984c9 100644 --- a/tools/ZAPD/ZAPD/ZRoom/ZRoomCommand.h +++ b/tools/ZAPD/ZAPD/ZRoom/ZRoomCommand.h @@ -56,6 +56,8 @@ public: int32_t cmdAddress; uint32_t cmdIndex; uint32_t commandSet; + RoomCommand cmdID; + offset_t segmentOffset; ZRoomCommand(ZFile* nParent); virtual ~ZRoomCommand() = default; @@ -64,16 +66,12 @@ public: void ParseRawData() override; - virtual void ParseRawDataLate(); - virtual void DeclareReferencesLate(const std::string& prefix); - - virtual std::string GetBodySourceCode() const = 0; - + std::string GetSourceTypeName() const override; ZResourceType GetResourceType() const override; // Getters/Setters virtual RoomCommand GetRoomCommand() const = 0; - size_t GetRawDataSize() const override; + size_t GetRawDataSize() const final override; virtual std::string GetCommandCName() const; virtual std::string GetCommandHex() const; @@ -81,8 +79,6 @@ public: protected: ZRoom* zRoom; - RoomCommand cmdID; uint8_t cmdArg1; segptr_t cmdArg2; - uint32_t segmentOffset; }; diff --git a/tools/ZAPD/ZAPD/ZScalar.cpp b/tools/ZAPD/ZAPD/ZScalar.cpp index 2f631acd44..062fb0e079 100644 --- a/tools/ZAPD/ZAPD/ZScalar.cpp +++ b/tools/ZAPD/ZAPD/ZScalar.cpp @@ -1,8 +1,9 @@ #include "ZScalar.h" -#include "BitConverter.h" -#include "File.h" + #include "Globals.h" -#include "StringHelper.h" +#include "Utils/BitConverter.h" +#include "Utils/File.h" +#include "Utils/StringHelper.h" #include "ZFile.h" REGISTER_ZFILENODE(Scalar, ZScalar); @@ -14,9 +15,16 @@ ZScalar::ZScalar(ZFile* nParent) : ZResource(nParent) RegisterRequiredAttribute("Type"); } -ZScalar::ZScalar(const ZScalarType scalarType, ZFile* nParent) : ZScalar(nParent) +void ZScalar::ExtractFromBinary(uint32_t nRawDataIndex, ZScalarType nScalarType) { - this->scalarType = scalarType; + rawDataIndex = nRawDataIndex; + scalarType = nScalarType; + + // Don't parse raw data of external files + if (parent->GetMode() == ZFileMode::ExternalFile) + return; + + ParseRawData(); } void ZScalar::ParseXML(tinyxml2::XMLElement* reader) @@ -247,15 +255,6 @@ std::string ZScalar::GetBodySourceCode() const } } -std::string ZScalar::GetSourceOutputCode(const std::string& prefix) -{ - if (parent != nullptr) - parent->AddDeclaration(rawDataIndex, DeclarationAlignment::None, GetRawDataSize(), - GetSourceTypeName(), GetName(), GetBodySourceCode()); - - return ""; -} - ZResourceType ZScalar::GetResourceType() const { return ZResourceType::Scalar; @@ -265,3 +264,16 @@ bool ZScalar::DoesSupportArray() const { return true; } + +DeclarationAlignment ZScalar::GetDeclarationAlignment() const +{ + switch (scalarType) + { + case ZScalarType::ZSCALAR_S64: + case ZScalarType::ZSCALAR_U64: + case ZScalarType::ZSCALAR_F64: + return DeclarationAlignment::Align8; + default: + return DeclarationAlignment::Align4; + } +} diff --git a/tools/ZAPD/ZAPD/ZScalar.h b/tools/ZAPD/ZAPD/ZScalar.h index ca2082756b..d269995cca 100644 --- a/tools/ZAPD/ZAPD/ZScalar.h +++ b/tools/ZAPD/ZAPD/ZScalar.h @@ -44,25 +44,25 @@ class ZScalar : public ZResource friend class ZVector; public: + ZScalarData scalarData; + ZScalarType scalarType; + ZScalar(ZFile* nParent); - ZScalar(const ZScalarType scalarType, ZFile* nParent); + + void ExtractFromBinary(uint32_t nRawDataIndex, ZScalarType nScalarType); void ParseRawData() override; void ParseXML(tinyxml2::XMLElement* reader) override; std::string GetBodySourceCode() const override; - std::string GetSourceOutputCode(const std::string& prefix) override; bool DoesSupportArray() const override; std::string GetSourceTypeName() const override; ZResourceType GetResourceType() const override; size_t GetRawDataSize() const override; + DeclarationAlignment GetDeclarationAlignment() const override; static size_t MapTypeToSize(const ZScalarType scalarType); static ZScalarType MapOutputTypeToScalarType(const std::string& type); static std::string MapScalarTypeToOutputType(const ZScalarType scalarType); - -protected: - ZScalarData scalarData; - ZScalarType scalarType; }; diff --git a/tools/ZAPD/ZAPD/ZSkeleton.cpp b/tools/ZAPD/ZAPD/ZSkeleton.cpp index 3e530a14fd..ebdf6455e6 100644 --- a/tools/ZAPD/ZAPD/ZSkeleton.cpp +++ b/tools/ZAPD/ZAPD/ZSkeleton.cpp @@ -1,9 +1,10 @@ #include "ZSkeleton.h" #include -#include "BitConverter.h" -#include "HighLevel/HLModelIntermediette.h" -#include "StringHelper.h" + +#include "Globals.h" +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" REGISTER_ZFILENODE(Skeleton, ZSkeleton); REGISTER_ZFILENODE(LimbTable, ZLimbTable); @@ -14,14 +15,6 @@ ZSkeleton::ZSkeleton(ZFile* nParent) : ZResource(nParent), limbsTable(nParent) RegisterRequiredAttribute("LimbType"); } -void ZSkeleton::ExtractFromXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex) -{ - ZResource::ExtractFromXML(reader, nRawDataIndex); - - parent->AddDeclaration(rawDataIndex, DeclarationAlignment::Align4, GetRawDataSize(), - GetSourceTypeName(), name, ""); -} - void ZSkeleton::ParseXML(tinyxml2::XMLElement* reader) { ZResource::ParseXML(reader); @@ -34,24 +27,18 @@ void ZSkeleton::ParseXML(tinyxml2::XMLElement* reader) type = ZSkeletonType::Curve; else if (skelTypeXml != "Normal") { - fprintf(stderr, - "ZSkeleton::ParseXML: Warning in '%s'.\n" - "\t Invalid Type found: '%s'.\n" - "\t Defaulting to 'Normal'.\n", - name.c_str(), skelTypeXml.c_str()); - type = ZSkeletonType::Normal; + throw std::runtime_error(StringHelper::Sprintf("ZSkeleton::ParseXML: Error in '%s'.\n" + "\t Invalid Type found: '%s'.\n", + name.c_str(), skelTypeXml.c_str())); } std::string limbTypeXml = registeredAttributes.at("LimbType").value; limbType = ZLimb::GetTypeByAttributeName(limbTypeXml); if (limbType == ZLimbType::Invalid) { - fprintf(stderr, - "ZSkeleton::ParseXML: Warning in '%s'.\n" - "\t Invalid LimbType found: '%s'.\n" - "\t Defaulting to 'Standard'.\n", - name.c_str(), limbTypeXml.c_str()); - limbType = ZLimbType::Standard; + throw std::runtime_error(StringHelper::Sprintf("ZSkeleton::ParseXML: Error in '%s'.\n" + "\t Invalid LimbType found: '%s'.\n", + name.c_str(), limbTypeXml.c_str())); } } @@ -77,6 +64,8 @@ void ZSkeleton::DeclareReferences(const std::string& prefix) if (defaultPrefix == "") defaultPrefix = prefix; + ZResource::DeclareReferences(defaultPrefix); + if (limbsArrayAddress != 0 && GETSEGNUM(limbsArrayAddress) == parent->segment) { uint32_t ptr = Seg2Filespace(limbsArrayAddress, parent->baseAddress); @@ -91,29 +80,22 @@ void ZSkeleton::DeclareReferences(const std::string& prefix) std::string ZSkeleton::GetBodySourceCode() const { - std::string limbTableName = parent->GetDeclarationPtrName(limbsArrayAddress); + std::string limbArrayName; + Globals::Instance->GetSegmentedPtrName(limbsArrayAddress, parent, "", limbArrayName); - std::string headerStr; switch (type) { case ZSkeletonType::Normal: case ZSkeletonType::Curve: - headerStr = StringHelper::Sprintf("\n\t%s, %i\n", limbTableName.c_str(), limbCount); - break; + return StringHelper::Sprintf("\n\t%s, %i\n", limbArrayName.c_str(), limbCount); + case ZSkeletonType::Flex: - headerStr = StringHelper::Sprintf("\n\t{ %s, %i }, %i\n", limbTableName.c_str(), limbCount, - dListCount); - break; + return StringHelper::Sprintf("\n\t{ %s, %i }, %i\n", limbArrayName.c_str(), limbCount, + dListCount); } - return headerStr; -} - -void ZSkeleton::GenerateHLIntermediette(HLFileIntermediette& hlFile) -{ - HLModelIntermediette* mdl = (HLModelIntermediette*)&hlFile; - HLModelIntermediette::FromZSkeleton(mdl, this); - mdl->blocks.push_back(new HLTerminator()); + // TODO: Throw exception? + return "ERROR"; } size_t ZSkeleton::GetRawDataSize() const @@ -129,25 +111,6 @@ size_t ZSkeleton::GetRawDataSize() const } } -std::string ZSkeleton::GetSourceOutputCode(const std::string& prefix) -{ - std::string headerStr = GetBodySourceCode(); - - Declaration* decl = parent->GetDeclaration(GetAddress()); - - if (decl == nullptr) - { - parent->AddDeclaration(GetAddress(), DeclarationAlignment::Align16, GetRawDataSize(), - GetSourceTypeName(), name, headerStr); - } - else - { - decl->text = headerStr; - } - - return ""; -} - std::string ZSkeleton::GetSourceTypeName() const { switch (type) @@ -168,9 +131,9 @@ ZResourceType ZSkeleton::GetResourceType() const return ZResourceType::Skeleton; } -segptr_t ZSkeleton::GetAddress() +DeclarationAlignment ZSkeleton::GetDeclarationAlignment() const { - return rawDataIndex; + return DeclarationAlignment::Align16; } uint8_t ZSkeleton::GetLimbCount() @@ -186,14 +149,6 @@ ZLimbTable::ZLimbTable(ZFile* nParent) : ZResource(nParent) RegisterRequiredAttribute("Count"); } -void ZLimbTable::ExtractFromXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex) -{ - ZResource::ExtractFromXML(reader, nRawDataIndex); - - parent->AddDeclarationArray(rawDataIndex, DeclarationAlignment::Align4, GetRawDataSize(), - GetSourceTypeName(), name, limbsAddresses.size(), ""); -} - void ZLimbTable::ExtractFromBinary(uint32_t nRawDataIndex, ZLimbType nLimbType, size_t nCount) { rawDataIndex = nRawDataIndex; @@ -237,9 +192,9 @@ void ZLimbTable::ParseRawData() void ZLimbTable::DeclareReferences(const std::string& prefix) { - std::string varPrefix = prefix; - if (name != "") - varPrefix = name; + std::string varPrefix = name; + if (varPrefix == "") + varPrefix = prefix; ZResource::DeclareReferences(varPrefix); @@ -252,22 +207,39 @@ void ZLimbTable::DeclareReferences(const std::string& prefix) uint32_t limbOffset = Seg2Filespace(limbAddress, parent->baseAddress); if (!parent->HasDeclaration(limbOffset)) { - ZLimb* limb = new ZLimb(limbType, varPrefix, limbOffset, parent); + ZLimb* limb = new ZLimb(parent); + limb->ExtractFromBinary(limbOffset, limbType); + limb->SetName(limb->GetDefaultName(varPrefix)); + limb->DeclareVar(varPrefix, ""); limb->DeclareReferences(varPrefix); - limb->GetSourceOutputCode(varPrefix); parent->AddResource(limb); } } } } +Declaration* ZLimbTable::DeclareVar(const std::string& prefix, const std::string& bodyStr) +{ + std::string auxName = name; + + if (name == "") + auxName = GetDefaultName(prefix); + + Declaration* decl = + parent->AddDeclarationArray(rawDataIndex, GetDeclarationAlignment(), GetRawDataSize(), + GetSourceTypeName(), auxName, limbsAddresses.size(), bodyStr); + decl->staticConf = staticConf; + return decl; +} + std::string ZLimbTable::GetBodySourceCode() const { - std::string body = ""; + std::string body; for (size_t i = 0; i < count; i++) { - std::string limbName = parent->GetDeclarationPtrName(limbsAddresses[i]); + std::string limbName; + Globals::Instance->GetSegmentedPtrName(limbsAddresses[i], parent, "", limbName); body += StringHelper::Sprintf("\t%s,", limbName.c_str()); if (i + 1 < count) @@ -277,20 +249,6 @@ std::string ZLimbTable::GetBodySourceCode() const return body; } -std::string ZLimbTable::GetSourceOutputCode(const std::string& prefix) -{ - std::string body = GetBodySourceCode(); - - Declaration* decl = parent->GetDeclaration(rawDataIndex); - if (decl == nullptr || decl->isPlaceholder) - parent->AddDeclarationArray(rawDataIndex, DeclarationAlignment::Align4, GetRawDataSize(), - GetSourceTypeName(), name, limbsAddresses.size(), body); - else - decl->text = body; - - return ""; -} - std::string ZLimbTable::GetSourceTypeName() const { switch (limbType) @@ -305,6 +263,7 @@ std::string ZLimbTable::GetSourceTypeName() const return StringHelper::Sprintf("%s*", ZLimb::GetSourceTypeName(limbType)); case ZLimbType::Invalid: + // TODO: Proper error message or something. assert("Invalid limb type.\n"); } diff --git a/tools/ZAPD/ZAPD/ZSkeleton.h b/tools/ZAPD/ZAPD/ZSkeleton.h index 29720fcb9c..ed003ceafd 100644 --- a/tools/ZAPD/ZAPD/ZSkeleton.h +++ b/tools/ZAPD/ZAPD/ZSkeleton.h @@ -20,15 +20,15 @@ class ZLimbTable : public ZResource public: ZLimbTable(ZFile* nParent); - void ExtractFromXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex) override; void ExtractFromBinary(uint32_t nRawDataIndex, ZLimbType nLimbType, size_t nCount); void ParseXML(tinyxml2::XMLElement* reader) override; void ParseRawData() override; void DeclareReferences(const std::string& prefix) override; - std::string GetBodySourceCode() const override; - std::string GetSourceOutputCode(const std::string& prefix) override; + Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override; + + std::string GetBodySourceCode() const override; std::string GetSourceTypeName() const override; ZResourceType GetResourceType() const override; @@ -53,22 +53,18 @@ public: ZSkeleton(ZFile* nParent); - void ExtractFromXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex) override; - void ParseXML(tinyxml2::XMLElement* reader) override; void ParseRawData() override; void DeclareReferences(const std::string& prefix) override; + std::string GetBodySourceCode() const override; - std::string GetSourceOutputCode(const std::string& prefix) override; - void GenerateHLIntermediette(HLFileIntermediette& hlFile) override; - - size_t GetRawDataSize() const override; - std::string GetSourceTypeName() const override; ZResourceType GetResourceType() const override; - segptr_t GetAddress(); + size_t GetRawDataSize() const override; + DeclarationAlignment GetDeclarationAlignment() const override; + uint8_t GetLimbCount(); protected: diff --git a/tools/ZAPD/ZAPD/ZString.cpp b/tools/ZAPD/ZAPD/ZString.cpp index 50545dafcb..965d4d6360 100644 --- a/tools/ZAPD/ZAPD/ZString.cpp +++ b/tools/ZAPD/ZAPD/ZString.cpp @@ -1,7 +1,7 @@ #include "ZString.h" -#include "File.h" -#include "StringHelper.h" +#include "Utils/File.h" +#include "Utils/StringHelper.h" #include "ZFile.h" REGISTER_ZFILENODE(String, ZString); @@ -29,20 +29,26 @@ void ZString::ParseRawData() strData.assign(dataStart, dataStart + size); } +Declaration* ZString::DeclareVar(const std::string& prefix, const std::string& bodyStr) +{ + std::string auxName = name; + + if (name == "") + auxName = GetDefaultName(prefix); + + Declaration* decl = + parent->AddDeclarationArray(rawDataIndex, GetDeclarationAlignment(), GetRawDataSize(), + GetSourceTypeName(), auxName, 0, bodyStr); + decl->staticConf = staticConf; + return decl; +} + std::string ZString::GetBodySourceCode() const { return StringHelper::Sprintf("\t\"%s\"", strData.data()); } -std::string ZString::GetSourceOutputCode(const std::string& prefix) -{ - parent->AddDeclarationArray(rawDataIndex, DeclarationAlignment::None, GetRawDataSize(), - GetSourceTypeName(), name, 0, GetBodySourceCode()); - - return ""; -} - -std::string ZString::GetSourceOutputHeader(const std::string& prefix) +std::string ZString::GetSourceOutputHeader([[maybe_unused]] const std::string& prefix) { return StringHelper::Sprintf("#define %s_macro \"%s\"", name.c_str(), strData.data()); } diff --git a/tools/ZAPD/ZAPD/ZString.h b/tools/ZAPD/ZAPD/ZString.h index 3c0c2905a1..6c58ebdcb5 100644 --- a/tools/ZAPD/ZAPD/ZString.h +++ b/tools/ZAPD/ZAPD/ZString.h @@ -9,8 +9,9 @@ public: ZString(ZFile* nParent); void ParseRawData() override; - std::string GetBodySourceCode() const; - std::string GetSourceOutputCode(const std::string& prefix) override; + + Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override; + std::string GetBodySourceCode() const override; std::string GetSourceOutputHeader(const std::string& prefix) override; std::string GetSourceTypeName() const override; diff --git a/tools/ZAPD/ZAPD/ZSymbol.cpp b/tools/ZAPD/ZAPD/ZSymbol.cpp index 25a1e49581..b24c3de4b0 100644 --- a/tools/ZAPD/ZAPD/ZSymbol.cpp +++ b/tools/ZAPD/ZAPD/ZSymbol.cpp @@ -1,5 +1,6 @@ #include "ZSymbol.h" -#include "StringHelper.h" + +#include "Utils/StringHelper.h" #include "ZFile.h" REGISTER_ZFILENODE(Symbol, ZSymbol); @@ -54,6 +55,18 @@ void ZSymbol::ParseXML(tinyxml2::XMLElement* reader) if (countXml != "") count = StringHelper::StrToL(countXml, 0); } + + if (registeredAttributes.at("Static").value == "On") + { + fprintf(stderr, "A can't be marked as static.\n\t Disabling static\n"); + } + staticConf = StaticConfig::Off; +} + +Declaration* ZSymbol::DeclareVar([[maybe_unused]] const std::string& prefix, + [[maybe_unused]] const std::string& bodyStr) +{ + return nullptr; } size_t ZSymbol::GetRawDataSize() const @@ -64,19 +77,17 @@ size_t ZSymbol::GetRawDataSize() const return typeSize; } -std::string ZSymbol::GetSourceOutputHeader(const std::string& prefix) +std::string ZSymbol::GetSourceOutputHeader([[maybe_unused]] const std::string& prefix) { if (isArray) { if (count == 0) - return StringHelper::Sprintf("extern %s %s%s[];\n", type.c_str(), prefix.c_str(), - name.c_str()); + return StringHelper::Sprintf("extern %s %s[];\n", type.c_str(), name.c_str()); else - return StringHelper::Sprintf("extern %s %s%s[%i];\n", type.c_str(), prefix.c_str(), - name.c_str(), count); + return StringHelper::Sprintf("extern %s %s[%i];\n", type.c_str(), name.c_str(), count); } - return StringHelper::Sprintf("extern %s %s%s;\n", type.c_str(), prefix.c_str(), name.c_str()); + return StringHelper::Sprintf("extern %s %s;\n", type.c_str(), name.c_str()); } std::string ZSymbol::GetSourceTypeName() const diff --git a/tools/ZAPD/ZAPD/ZSymbol.h b/tools/ZAPD/ZAPD/ZSymbol.h index 1094a0222c..7cb14aa9b4 100644 --- a/tools/ZAPD/ZAPD/ZSymbol.h +++ b/tools/ZAPD/ZAPD/ZSymbol.h @@ -16,10 +16,12 @@ public: void ParseXML(tinyxml2::XMLElement* reader) override; - size_t GetRawDataSize() const override; + Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override; std::string GetSourceOutputHeader(const std::string& prefix) override; std::string GetSourceTypeName() const override; ZResourceType GetResourceType() const override; + + size_t GetRawDataSize() const override; }; diff --git a/tools/ZAPD/ZAPD/ZTexture.cpp b/tools/ZAPD/ZAPD/ZTexture.cpp index 956a2f7b40..33ee54d1bc 100644 --- a/tools/ZAPD/ZAPD/ZTexture.cpp +++ b/tools/ZAPD/ZAPD/ZTexture.cpp @@ -1,12 +1,13 @@ #include "ZTexture.h" #include -#include "BitConverter.h" + #include "CRC32.h" -#include "Directory.h" -#include "File.h" #include "Globals.h" -#include "Path.h" +#include "Utils/BitConverter.h" +#include "Utils/Directory.h" +#include "Utils/File.h" +#include "Utils/Path.h" REGISTER_ZFILENODE(Texture, ZTexture); @@ -21,21 +22,8 @@ ZTexture::ZTexture(ZFile* nParent) : ZResource(nParent) RegisterOptionalAttribute("TlutOffset"); } -void ZTexture::ExtractFromXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex) -{ - ZResource::ExtractFromXML(reader, nRawDataIndex); - - auto filepath = Globals::Instance->outputPath / fs::path(name).stem(); - - std::string incStr = - StringHelper::Sprintf("%s.%s.inc.c", filepath.c_str(), GetExternalExtension().c_str()); - - parent->AddDeclarationIncludeArray(rawDataIndex, incStr, GetRawDataSize(), GetSourceTypeName(), - name, 0); -} - -void ZTexture::FromBinary(uint32_t nRawDataIndex, int32_t nWidth, int32_t nHeight, - TextureType nType, bool nIsPalette) +void ZTexture::ExtractFromBinary(uint32_t nRawDataIndex, int32_t nWidth, int32_t nHeight, + TextureType nType, bool nIsPalette) { width = nWidth; height = nHeight; @@ -45,6 +33,10 @@ void ZTexture::FromBinary(uint32_t nRawDataIndex, int32_t nWidth, int32_t nHeigh name = GetDefaultName(parent->GetName()); outName = name; + // Don't parse raw data of external files + if (parent->GetMode() == ZFileMode::ExternalFile) + return; + ParseRawData(); CalcHash(); } @@ -52,17 +44,10 @@ void ZTexture::FromBinary(uint32_t nRawDataIndex, int32_t nWidth, int32_t nHeigh void ZTexture::FromPNG(const fs::path& pngFilePath, TextureType texType) { format = texType; - name = StringHelper::Split(Path::GetFileNameWithoutExtension(pngFilePath), ".")[0]; + name = StringHelper::Split(Path::GetFileNameWithoutExtension(pngFilePath.string()), ".")[0]; PrepareRawDataFromFile(pngFilePath); } -void ZTexture::FromHLTexture(HLTexture* hlTex) -{ - width = hlTex->width; - height = hlTex->height; - format = static_cast(hlTex->type); -} - void ZTexture::ParseXML(tinyxml2::XMLElement* reader) { ZResource::ParseXML(reader); @@ -116,6 +101,12 @@ void ZTexture::ParseXML(tinyxml2::XMLElement* reader) void ZTexture::ParseRawData() { + if (rawDataIndex % 8 != 0) + fprintf(stderr, + "ZTexture::ParseXML: Warning in '%s'.\n" + "\t This texture is not 64-bit aligned.\n", + name.c_str()); + switch (format) { case TextureType::RGBA16bpp: @@ -329,7 +320,7 @@ void ZTexture::PrepareBitmapPalette8() } } -void ZTexture::DeclareReferences(const std::string& prefix) +void ZTexture::DeclareReferences([[maybe_unused]] const std::string& prefix) { if (tlutOffset != static_cast(-1)) { @@ -340,15 +331,10 @@ void ZTexture::DeclareReferences(const std::string& prefix) if (format == TextureType::Palette4bpp) tlutDim = 4; - auto filepath = Globals::Instance->outputPath / fs::path(name).stem(); - std::string incStr = StringHelper::Sprintf("%s.%s.inc.c", filepath.c_str(), - GetExternalExtension().c_str()); - tlut = new ZTexture(parent); - tlut->FromBinary(tlutOffset, tlutDim, tlutDim, TextureType::RGBA16bpp, true); + tlut->ExtractFromBinary(tlutOffset, tlutDim, tlutDim, TextureType::RGBA16bpp, true); parent->AddTextureResource(tlutOffset, tlut); - parent->AddDeclarationIncludeArray(tlutOffset, incStr, tlut->GetRawDataSize(), - tlut->GetSourceTypeName(), tlut->GetName(), 0); + tlut->DeclareVar(prefix, ""); } else { @@ -686,7 +672,7 @@ std::string ZTexture::GetIMSizFromType() } } -std::string ZTexture::GetDefaultName(const std::string& prefix) +std::string ZTexture::GetDefaultName(const std::string& prefix) const { const char* suffix = "Tex"; if (isPalette) @@ -722,14 +708,14 @@ void ZTexture::Save(const fs::path& outFolder) // process for generating the Texture Pool XML. if (Globals::Instance->outputCrc) { - File::WriteAllText(Globals::Instance->outputPath / (outName + ".txt"), + File::WriteAllText((Globals::Instance->outputPath / (outName + ".txt")).string(), StringHelper::Sprintf("%08lX", hash)); } auto outPath = GetPoolOutPath(outFolder); - if (!Directory::Exists(outPath)) - Directory::CreateDirectory(outPath); + if (!Directory::Exists(outPath.string())) + Directory::CreateDirectory(outPath.string()); auto outFileName = outPath / (outName + "." + GetExternalExtension() + ".png"); @@ -747,9 +733,45 @@ void ZTexture::Save(const fs::path& outFolder) #endif } +Declaration* ZTexture::DeclareVar(const std::string& prefix, + [[maybe_unused]] const std::string& bodyStr) +{ + std::string auxName = name; + std::string auxOutName = outName; + + if (auxName == "") + auxName = GetDefaultName(prefix); + + if (auxOutName == "") + auxOutName = GetDefaultName(prefix); + + auto filepath = Globals::Instance->outputPath / fs::path(auxOutName).stem(); + + std::string incStr = + StringHelper::Sprintf("%s.%s.inc.c", filepath.c_str(), GetExternalExtension().c_str()); + + if (!Globals::Instance->cfg.texturePool.empty()) + { + CalcHash(); + + // TEXTURE POOL CHECK + const auto& poolEntry = Globals::Instance->cfg.texturePool.find(hash); + if (poolEntry != Globals::Instance->cfg.texturePool.end()) + { + incStr = StringHelper::Sprintf("%s.%s.inc.c", poolEntry->second.path.c_str(), + GetExternalExtension().c_str()); + } + } + + Declaration* decl = parent->AddDeclarationIncludeArray( + rawDataIndex, incStr, GetRawDataSize(), GetSourceTypeName(), auxName, GetRawDataSize() / 8); + decl->staticConf = staticConf; + return decl; +} + std::string ZTexture::GetBodySourceCode() const { - std::string sourceOutput = ""; + std::string sourceOutput; for (size_t i = 0; i < textureDataRaw.size(); i += 8) { @@ -827,7 +849,7 @@ fs::path ZTexture::GetPoolOutPath(const fs::path& defaultValue) return defaultValue; } -TextureType ZTexture::GetTextureTypeFromString(std::string str) +TextureType ZTexture::GetTextureTypeFromString(const std::string& str) { TextureType texType = TextureType::Error; @@ -839,11 +861,11 @@ TextureType ZTexture::GetTextureTypeFromString(std::string str) { texType = TextureType::RGBA16bpp; #ifdef DEPRECATION_ON - fprintf(stderr, - "ZTexture::GetTextureTypeFromString: Deprecation warning.\n" - "\t The texture format 'rgb5a1' is currently deprecated, and will be removed in a future " - "version.\n" - "\t Use the format 'rgba16' instead.\n"); + fprintf(stderr, "ZTexture::GetTextureTypeFromString: Deprecation warning.\n" + "\t The texture format 'rgb5a1' is currently deprecated, and will be " + "removed in a future " + "version.\n" + "\t Use the format 'rgba16' instead.\n"); #endif } else if (str == "i4") diff --git a/tools/ZAPD/ZAPD/ZTexture.h b/tools/ZAPD/ZAPD/ZTexture.h index 807468a627..ef67c3f6ef 100644 --- a/tools/ZAPD/ZAPD/ZTexture.h +++ b/tools/ZAPD/ZAPD/ZTexture.h @@ -1,8 +1,5 @@ #pragma once -#include - -#include "HighLevel/HLTexture.h" #include "ImageBackend.h" #include "ZResource.h" #include "tinyxml2.h" @@ -58,18 +55,17 @@ public: bool isPalette = false; - void ExtractFromXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex) override; - void FromBinary(uint32_t nRawDataIndex, int32_t nWidth, int32_t nHeight, TextureType nType, - bool nIsPalette); + void ExtractFromBinary(uint32_t nRawDataIndex, int32_t nWidth, int32_t nHeight, + TextureType nType, bool nIsPalette); void FromPNG(const fs::path& pngFilePath, TextureType texType); - void FromHLTexture(HLTexture* hlTex); - - static TextureType GetTextureTypeFromString(std::string str); + static TextureType GetTextureTypeFromString(const std::string& str); void ParseXML(tinyxml2::XMLElement* reader) override; void ParseRawData() override; void DeclareReferences(const std::string& prefix) override; - std::string GetBodySourceCode() const; + + Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override; + std::string GetBodySourceCode() const override; void CalcHash() override; void Save(const fs::path& outFolder) override; @@ -81,7 +77,7 @@ public: size_t GetRawDataSize() const override; std::string GetIMFmtFromType(); std::string GetIMSizFromType(); - std::string GetDefaultName(const std::string& prefix); + std::string GetDefaultName(const std::string& prefix) const override; uint32_t GetWidth() const; uint32_t GetHeight() const; void SetDimensions(uint32_t nWidth, uint32_t nHeight); diff --git a/tools/ZAPD/ZAPD/ZTextureAnimation.cpp b/tools/ZAPD/ZAPD/ZTextureAnimation.cpp new file mode 100644 index 0000000000..4332fcf1e5 --- /dev/null +++ b/tools/ZAPD/ZAPD/ZTextureAnimation.cpp @@ -0,0 +1,702 @@ +/** + * File: ZTextureAnimation.cpp + * ZResources defined: ZTextureAnimation, ZTextureAnimationParams (XML declaration not supported for + * the latter) + * Purpose: extracting texture animating structures from asset files Note: data type is exclusive to + * Majora's Mask + * + * Structure of data: + * A texture animation consists of a main array of data of the form + * `SS 00 00 0T PPPPPPPP`, + * where `S` is the segment that the functionality is sent to (and read by DLists), `T` is the + * "type" (see below), and `P` is a pointer to the type's subsidiary information, which is + * invariably just above this main array. Details of this subsidiary data are given below. + * + * Segment + * === + * The segment starts at 1 and is incremented in each entry; the final one is negated, which is used + * as the indication to stop reading. The actual segment the game will use to draw is S + 7. + * + * Types + * === + * There are 7 values that `T` can take: + * `0`: A single texture scroll (Implemented by Gfx_TexScroll): subsidiary params are given as + * an array with one entry, a struct `XX YY WW HH` containing xStep, yStep, width, height + * (all u8). + * + * `1`: A dual texture scroll (Implementated by Gfx_TwoTexScroll): same as type `0`, but with + * two entries in the params array. + * + * `2`: Color changing: Changes the primColor (with a LOD factor) and envColor + * `KKKK LLLL PPPPPPPP QQQQQQQQ RRRRRRRR` + * - `K` (u16) is the total length of the animation (and in this case, the total number of + * colors) + * - `L` (u16) is seemingly always 0 for this type, and not used in the code + * - `P` segmented pointer to array of augmented primColors + * - `Q` segmented pointer to array of envColors, and can be NULL + * - `R` segmented pointer to array of frameData (u8), which is also seemingly always NULL + * for this type. + * + * envColors take the form `RR GG BB AA` as usual, while primColors have an extra LODFrac + * element: RR GG BB AA LL + * + * `3`: Color changing (LERP): similar to type `2`, but uses linear interpolation. The structure + * is similar to `2`, but + * - `K` is now just the animation length, while + * - `L` is the total number of colors, and + * - the frameData is used to determine which colors to interpolate. + * + * `4`: Color changing (Lagrange interpolation): For extraction purposes identical to type 3. + * Uses a nonlinear interpolation formula to change the colours more smoothly. + * + * `5`: Texture cycle: functions like a gif. Subsidiary params: + * `FFFF 0000 PPPPPPPP QQQQQQQQ` + * where + * - `F` (u16) time between changes in frames + * - `P` pointer to array of segmented pointers to textures to cycle through + * - `Q` array of indices, indicating which texture to use next when a change frame is + * reached. The maximum indicates the number of textures in the texture array. + * + * `6`: This is used to indicate an empty/unimplemented params set. It is ignored by the game's + * function provided that the segment is 0. A generic empty one takes the form + * `00 00 00 06 00000000`, + * and has no extra data. + * + * Implementation + * === + * - ZTextureAnimation requires a declaration in the XML to extract anything. It handles the main + * array. It uses a POD struct for each entry, and declares references to the params structs. + * + * - ZTextureAnimationParams is not (currently) declarable in an XML. It is a parent class for the + * three classes that handle the various cases: + * - TextureScrollingParams for types `0` and `1` + * - TextureColorChangingParams for types `2`,`3`,`4` + * - TextureCyclingParams for type `5` + * Each of these will declare all its subsidiary arrays, using POD structs. + */ +#include "ZTextureAnimation.h" + +#include +#include +#include + +#include "Globals.h" +#include "Utils/BitConverter.h" +#include "ZFile.h" +#include "ZResource.h" +#include "tinyxml2.h" + +REGISTER_ZFILENODE(TextureAnimation, ZTextureAnimation); + +/* Constructors */ +ZTextureAnimationParams::ZTextureAnimationParams(ZFile* parent) : ZResource::ZResource(parent) +{ +} +TextureScrollingParams::TextureScrollingParams(ZFile* parent) + : ZTextureAnimationParams::ZTextureAnimationParams(parent) +{ +} +TextureColorChangingParams::TextureColorChangingParams(ZFile* parent) + : ZTextureAnimationParams::ZTextureAnimationParams(parent) +{ +} +TextureCyclingParams::TextureCyclingParams(ZFile* parent) + : ZTextureAnimationParams::ZTextureAnimationParams(parent) +{ +} + +/* TextureAnimationParams */ +/* This class only implements the functions common to all or most its inheritors */ + +void ZTextureAnimationParams::ExtractFromBinary(uint32_t nRawDataIndex) +{ + rawDataIndex = nRawDataIndex; + + ParseRawData(); +} + +// Implemented by TextureScrollingParams only[ +void ZTextureAnimationParams::ExtractFromBinary([[maybe_unused]] uint32_t nRawDataIndex, + [[maybe_unused]] int count) +{ +} + +std::string +ZTextureAnimationParams::GetDefaultName([[maybe_unused]] const std::string& prefix) const +{ + return "ShouldNotBeVIsible"; +} + +ZResourceType ZTextureAnimationParams::GetResourceType() const +{ + return ZResourceType::TextureAnimationParams; +} + +/* TextureScrollingParams */ + +void TextureScrollingParams::ParseRawData() +{ + const auto& rawData = parent->GetRawData(); + + for (int i = 0; i < count; i++) + { + rows[i].xStep = BitConverter::ToUInt8BE(rawData, rawDataIndex + 4 * i); + rows[i].yStep = BitConverter::ToUInt8BE(rawData, rawDataIndex + 4 * i + 1); + rows[i].width = BitConverter::ToUInt8BE(rawData, rawDataIndex + 4 * i + 2); + rows[i].height = BitConverter::ToUInt8BE(rawData, rawDataIndex + 4 * i + 3); + } +} + +void TextureScrollingParams::ExtractFromBinary(uint32_t nRawDataIndex, int nCount) +{ + rawDataIndex = nRawDataIndex; + count = nCount; + + ParseRawData(); +} + +std::string TextureScrollingParams::GetSourceTypeName() const +{ + return "AnimatedMatTexScrollParams"; // TODO: Better name +} + +std::string TextureScrollingParams::GetDefaultName(const std::string& prefix) const +{ + return StringHelper::Sprintf("%sTexScrollParams_%06X", prefix.c_str(), rawDataIndex); +} + +size_t TextureScrollingParams::GetRawDataSize() const +{ + return 4 * count; +} + +/** + * Overrides the parent version to declare an array of the params rather than just one entry. + */ +Declaration* TextureScrollingParams::DeclareVar(const std::string& prefix, + const std::string& bodyStr) +{ + std::string auxName = name; + + if (name == "") + auxName = GetDefaultName(prefix); + + return parent->AddDeclarationArray(rawDataIndex, GetDeclarationAlignment(), GetRawDataSize(), + GetSourceTypeName(), auxName, count, bodyStr); +} + +std::string TextureScrollingParams::GetBodySourceCode() const +{ + std::string bodyStr; + + for (int i = 0; i < count; i++) + { + bodyStr += StringHelper::Sprintf("\t{ %d, %d, 0x%02X, 0x%02X },\n", rows[i].xStep, + rows[i].yStep, rows[i].width, rows[i].height); + } + + bodyStr.pop_back(); + + return bodyStr; +} + +/* TextureColorChangingParams */ + +/** + * Also parses the color and frameData arrays + */ +void TextureColorChangingParams::ParseRawData() +{ + const auto& rawData = parent->GetRawData(); + + animLength = BitConverter::ToUInt16BE(rawData, rawDataIndex); + colorListCount = BitConverter::ToUInt16BE(rawData, rawDataIndex + 2); + + // Handle type 2 separately + uint16_t listLength = + ((type == TextureAnimationParamsType::ColorChange) ? animLength : colorListCount); + + if (listLength == 0) + throw std::runtime_error(StringHelper::Sprintf( + "When processing file %s: in input binary file %s, offset 0x%06X:" + "\n\t" + "\033[97m" + "TextureColorChangingParams::ParseRawData:" + "\033[0m" + "\033[91m" + " error: " + "\033[0m" + "\033[97m" + "color list length cannot be 0\n" + "\033[0m", + Globals::Instance->inputPath.c_str(), parent->GetName().c_str(), rawDataIndex)); + + primColorListAddress = BitConverter::ToUInt32BE(rawData, rawDataIndex + 4); + envColorListAddress = BitConverter::ToUInt32BE(rawData, rawDataIndex + 8); + frameDataListAddress = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0xC); + + uint32_t primColorListOffset = Seg2Filespace(primColorListAddress, parent->baseAddress); + uint32_t envColorListOffset = Seg2Filespace(envColorListAddress, parent->baseAddress); + uint32_t frameDataListOffset = Seg2Filespace(frameDataListAddress, parent->baseAddress); + + uint32_t currentPtr; + + F3DPrimColor currentPrimColor; + + for (currentPtr = primColorListOffset; currentPtr < primColorListOffset + 5 * listLength; + currentPtr += 5) + { + currentPrimColor = {BitConverter::ToUInt8BE(rawData, currentPtr), + BitConverter::ToUInt8BE(rawData, currentPtr + 1), + BitConverter::ToUInt8BE(rawData, currentPtr + 2), + BitConverter::ToUInt8BE(rawData, currentPtr + 3), + BitConverter::ToUInt8BE(rawData, currentPtr + 4)}; + primColorList.push_back(currentPrimColor); + } + + F3DEnvColor currentEnvColor; + + for (currentPtr = envColorListOffset; currentPtr < envColorListOffset + 4 * listLength; + currentPtr += 4) + { + currentEnvColor = {BitConverter::ToUInt8BE(rawData, currentPtr), + BitConverter::ToUInt8BE(rawData, currentPtr + 1), + BitConverter::ToUInt8BE(rawData, currentPtr + 2), + BitConverter::ToUInt8BE(rawData, currentPtr + 3)}; + envColorList.push_back(currentEnvColor); + } + + uint16_t currentFrameData; + + for (currentPtr = frameDataListOffset; currentPtr < frameDataListOffset + 2 * listLength; + currentPtr += 2) + { + currentFrameData = BitConverter::ToUInt16BE(rawData, currentPtr); + frameDataList.push_back(currentFrameData); + } +} + +std::string TextureColorChangingParams::GetSourceTypeName() const +{ + return "AnimatedMatColorParams"; // TODO: Better name +} + +std::string TextureColorChangingParams::GetDefaultName(const std::string& prefix) const +{ + return StringHelper::Sprintf("%sColorParams_%06X", prefix.c_str(), rawDataIndex); +} + +size_t TextureColorChangingParams::GetRawDataSize() const +{ + return 0x10; +} + +void TextureColorChangingParams::DeclareReferences([[maybe_unused]] const std::string& prefix) +{ + if (primColorListAddress != 0) // NULL + { + std::string primColorBodyStr; + + for (const auto& color : primColorList) + { + primColorBodyStr += StringHelper::Sprintf("\t{ %d, %d, %d, %d, %d },\n", color.r, + color.g, color.b, color.a, color.lodFrac); + } + + primColorBodyStr.pop_back(); + + parent->AddDeclarationArray( + Seg2Filespace(primColorListAddress, parent->baseAddress), DeclarationAlignment::Align4, + primColorList.size() * 5, "F3DPrimColor", + StringHelper::Sprintf("%sTexColorChangingPrimColors_%06X", parent->GetName().c_str(), + Seg2Filespace(primColorListAddress, parent->baseAddress)), + primColorList.size(), primColorBodyStr); + } + + if (envColorListAddress != 0) // NULL + { + std::string envColorBodyStr; + + for (const auto& color : envColorList) + { + envColorBodyStr += StringHelper::Sprintf("\t{ %d, %d, %d, %d },\n", color.r, color.g, + color.b, color.a); + } + + envColorBodyStr.pop_back(); + + parent->AddDeclarationArray( + Seg2Filespace(envColorListAddress, parent->baseAddress), DeclarationAlignment::Align4, + envColorList.size() * 4, "F3DEnvColor", + StringHelper::Sprintf("%sTexColorChangingEnvColors_%06X", parent->GetName().c_str(), + Seg2Filespace(envColorListAddress, parent->baseAddress)), + envColorList.size(), envColorBodyStr); + } + + if (frameDataListAddress != 0) // NULL + { + std::string frameDataBodyStr = "\t"; + + for (const auto& frame : frameDataList) + { + frameDataBodyStr += StringHelper::Sprintf("%d, ", frame); + } + + frameDataBodyStr.pop_back(); + + parent->AddDeclarationArray( + Seg2Filespace(frameDataListAddress, parent->baseAddress), DeclarationAlignment::Align4, + frameDataList.size() * 2, "u16", + StringHelper::Sprintf("%sTexColorChangingFrameData_%06X", parent->GetName().c_str(), + Seg2Filespace(frameDataListAddress, parent->baseAddress)), + frameDataList.size(), frameDataBodyStr); + } +} + +std::string TextureColorChangingParams::GetBodySourceCode() const +{ + std::string primColorListName; + std::string envColorListName; + std::string frameDataListName; + + Globals::Instance->GetSegmentedPtrName(primColorListAddress, parent, "", primColorListName); + Globals::Instance->GetSegmentedPtrName(envColorListAddress, parent, "", envColorListName); + Globals::Instance->GetSegmentedPtrName(frameDataListAddress, parent, "", frameDataListName); + + std::string bodyStr = StringHelper::Sprintf( + "\n %d, %d, %s, %s, %s,\n", animLength, colorListCount, primColorListName.c_str(), + envColorListName.c_str(), frameDataListName.c_str()); + + return bodyStr; +} + +/* TextureCyclingParams */ + +void TextureCyclingParams::ParseRawData() +{ + const auto& rawData = parent->GetRawData(); + + cycleLength = BitConverter::ToUInt16BE(rawData, rawDataIndex); + if (cycleLength == 0) + throw std::runtime_error( + StringHelper::Sprintf("When processing file %s: in input binary file %s, offset 0x%06X:" + "\n\t" + "\033[97m" + "TextureCyclingParams::ParseRawData:" + "\033[0m" + "\033[91m" + " error: " + "\033[0m" + "\033[97m" + "cycleLength cannot be 0\n" + "\033[0m", + Globals::Instance->inputPath.c_str(), parent->GetName().c_str(), + Seg2Filespace(rawDataIndex, 0))); + + textureListAddress = BitConverter::ToUInt32BE(rawData, rawDataIndex + 4); + textureIndexListAddress = BitConverter::ToUInt32BE(rawData, rawDataIndex + 8); + + uint32_t textureListOffset = Seg2Filespace(textureListAddress, parent->baseAddress); + uint32_t textureIndexListOffset = Seg2Filespace(textureIndexListAddress, parent->baseAddress); + + uint32_t currentPtr; + + uint8_t currentIndex; + uint8_t maxIndex = 0; // To find the length of the texture list + + for (currentPtr = textureIndexListOffset; currentPtr < textureIndexListOffset + cycleLength; + currentPtr++) + { + currentIndex = BitConverter::ToUInt8BE(rawData, currentPtr); + textureIndexList.push_back(currentIndex); + if (currentIndex > maxIndex) + maxIndex = currentIndex; + } + + for (currentPtr = textureListOffset; currentPtr <= textureListOffset + 4 * maxIndex; + currentPtr += 4) + { + textureList.push_back(BitConverter::ToUInt32BE(rawData, currentPtr)); + } +} + +std::string TextureCyclingParams::GetSourceTypeName() const +{ + return "AnimatedMatTexCycleParams"; // TODO: Better name +} + +std::string TextureCyclingParams::GetDefaultName(const std::string& prefix) const +{ + return StringHelper::Sprintf("%sTexCycleParams_%06X", prefix.c_str(), rawDataIndex); +} + +size_t TextureCyclingParams::GetRawDataSize() const +{ + return 0xC; +} + +void TextureCyclingParams::DeclareReferences([[maybe_unused]] const std::string& prefix) +{ + if (textureListAddress != 0) // NULL + { + std::string texturesBodyStr; + std::string texName; + std::string comment; + + for (const auto& tex : textureList) + { + bool texFound = Globals::Instance->GetSegmentedPtrName(tex, parent, "", texName); + + // texName is a raw segmented pointer. This occurs if the texture is not declared + // separately since we cannot read the format. In theory we could scan DLists for the + // format on the appropriate segments. + if (!texFound) + { + comment = " // Raw pointer, declare texture in XML to use proper symbol"; + + fprintf(stderr, + "When processing file %s: in input binary file %s, offset 0x%06X:" + "\n\t" + "\033[97m" + "TextureCyclingParams::DeclareReferences:" + "\033[0m" + "\033[95m" + " warning: " + "\033[0m" + "\033[97m" + "TexCycle declared here points to unknown texture at address %s. " + "Please declare the texture in the XML to use the proper symbol.\n" + "\033[0m", + Globals::Instance->inputPath.c_str(), parent->GetName().c_str(), + Seg2Filespace(textureListAddress, parent->baseAddress), texName.c_str()); + } + texturesBodyStr += StringHelper::Sprintf("\t%s,%s\n", texName.c_str(), comment.c_str()); + } + + texturesBodyStr.pop_back(); + + parent->AddDeclarationArray( + Seg2Filespace(textureListAddress, parent->baseAddress), DeclarationAlignment::Align4, + textureList.size() * 4, "TexturePtr", + StringHelper::Sprintf("%sTexCycleTexPtrs_%06X", parent->GetName().c_str(), + Seg2Filespace(textureListAddress, parent->baseAddress)), + textureList.size(), texturesBodyStr); + } + + if (textureIndexListAddress != 0) // NULL + { + std::string indicesBodyStr = "\t"; + + for (uint8_t index : textureIndexList) + { + indicesBodyStr += StringHelper::Sprintf("%d, ", index); + } + + indicesBodyStr.pop_back(); + + parent->AddDeclarationArray( + Seg2Filespace(textureIndexListAddress, parent->baseAddress), + DeclarationAlignment::Align4, textureIndexList.size(), "u8", + StringHelper::Sprintf("%sTexCycleTexIndices_%06X", parent->GetName().c_str(), + Seg2Filespace(textureIndexListAddress, parent->baseAddress)), + textureIndexList.size(), indicesBodyStr); + } +} + +std::string TextureCyclingParams::GetBodySourceCode() const +{ + std::string textureListName; + std::string textureIndexListName; + + Globals::Instance->GetSegmentedPtrName(textureListAddress, parent, "", textureListName); + Globals::Instance->GetSegmentedPtrName(textureIndexListAddress, parent, "", + textureIndexListName); + + std::string bodyStr = StringHelper::Sprintf( + "\n %d, %s, %s,\n", cycleLength, textureListName.c_str(), textureIndexListName.c_str()); + + return bodyStr; +} + +/* ZTextureAnimation */ + +ZTextureAnimation::ZTextureAnimation(ZFile* nParent) : ZResource(nParent) +{ +} + +/** + * Builds the array of params + */ +void ZTextureAnimation::ParseRawData() +{ + ZResource::ParseRawData(); + + TextureAnimationEntry currentEntry; + auto rawData = parent->GetRawData(); + int16_t type; + + for (uint32_t currentPtr = rawDataIndex;; currentPtr += 8) + { + type = BitConverter::ToInt16BE(rawData, currentPtr + 2); + + currentEntry.segment = BitConverter::ToInt8BE(rawData, currentPtr); + currentEntry.type = (TextureAnimationParamsType)type; + currentEntry.paramsPtr = BitConverter::ToUInt32BE(rawData, currentPtr + 4); + entries.push_back(currentEntry); + + if ((type < 0) || (type > 6)) + { + throw std::runtime_error(StringHelper::Sprintf( + "When processing file %s: in input binary file %s, offset 0x%06X:" + "\n\t" + "\033[97m" + "ZTextureAnimation::ParseRawData:" + "\033[0m" + "\033[91m" + " error: " + "\033[0m" + "\033[97m" + "unknown TextureAnimationParams type 0x%02X in TextureAnimation: entry reads\n\t{ " + "0x%02X, 0x%02X, 0x%08X }\n(type should be between " + "0x00 and 0x06)\n" + "\033[0m", + Globals::Instance->inputPath.c_str(), parent->GetName().c_str(), rawDataIndex, type, + currentEntry.segment, type, currentEntry.paramsPtr)); + } + + if (currentEntry.segment <= 0) + break; + } +} + +#include +/** + * For each params entry, + */ +void ZTextureAnimation::DeclareReferences(const std::string& prefix) +{ + std::string varPrefix = name; + if (varPrefix == "") + varPrefix = prefix; + + ZResource::DeclareReferences(varPrefix); + + for (const auto& entry : entries) + { + if (entry.paramsPtr != 0 && GETSEGNUM(entry.paramsPtr) == parent->segment) + { + uint32_t paramsOffset = Seg2Filespace(entry.paramsPtr, parent->baseAddress); + if (!parent->HasDeclaration(paramsOffset)) + { + ZTextureAnimationParams* params; + int count = 2; + switch (entry.type) + { + case TextureAnimationParamsType::SingleScroll: + count = 1; + [[fallthrough]]; + case TextureAnimationParamsType::DualScroll: + params = new TextureScrollingParams(parent); + params->ExtractFromBinary(paramsOffset, count); + break; + + case TextureAnimationParamsType::ColorChange: + case TextureAnimationParamsType::ColorChangeLERP: + case TextureAnimationParamsType::ColorChangeLagrange: + params = new TextureColorChangingParams(parent); + params->type = entry.type; + params->ExtractFromBinary(paramsOffset); + break; + + case TextureAnimationParamsType::TextureCycle: + params = new TextureCyclingParams(parent); + params->ExtractFromBinary(paramsOffset); + break; + + case TextureAnimationParamsType::Empty: + fprintf(stderr, + "When processing file %s: in input binary file %s: offset 0x%06X:" + "\n\t" + "\033[97m" + "ZTextureAnimation::DeclareReferences:" + "\033[0m" + "\033[95m" + " warning: " + "\033[0m" + "\033[97m" + "TextureAnimationParams entry has empty type (6), but params pointer " + "is not NULL. Params read\n\t\t" + "{ 0x%02X, 0x%02X, 0x%08X }\n" + "\033[0m", + Globals::Instance->inputPath.c_str(), parent->GetName().c_str(), + rawDataIndex, entry.segment, (int)entry.type, entry.paramsPtr); + return; + default: + // Because GCC is worried this could happen + assert(entry.type < TextureAnimationParamsType::SingleScroll || + entry.type > TextureAnimationParamsType::Empty); + return; + } + + params->SetName(params->GetDefaultName(varPrefix)); + params->DeclareVar(varPrefix, ""); + parent->AddResource(params); + } + } + } +} + +std::string ZTextureAnimation::GetSourceTypeName() const +{ + return "AnimatedMaterial"; // TODO: Better name +} + +ZResourceType ZTextureAnimation::GetResourceType() const +{ + return ZResourceType::TextureAnimation; +} + +/** + * The size of the main array + */ +size_t ZTextureAnimation::GetRawDataSize() const +{ + return entries.size() * 8; +} + +std::string ZTextureAnimation::GetDefaultName(const std::string& prefix) const +{ + return StringHelper::Sprintf("%sTexAnim_%06X", prefix.c_str(), rawDataIndex); +} + +Declaration* ZTextureAnimation::DeclareVar(const std::string& prefix, const std::string& bodyStr) +{ + std::string auxName = name; + + if (name == "") + auxName = GetDefaultName(prefix); + + Declaration* decl = + parent->AddDeclarationArray(rawDataIndex, GetDeclarationAlignment(), GetRawDataSize(), + GetSourceTypeName(), auxName, entries.size(), bodyStr); + decl->staticConf = staticConf; + return decl; +} + +std::string ZTextureAnimation::GetBodySourceCode() const +{ + std::string bodyStr; + + for (const auto& entry : entries) + { + std::string paramName; + Globals::Instance->GetSegmentedPtrName(entry.paramsPtr, parent, "", paramName); + + bodyStr += StringHelper::Sprintf("\t{ %d, %d, %s },\n", entry.segment, entry.type, + paramName.c_str()); + } + + bodyStr.pop_back(); + + return bodyStr; +} diff --git a/tools/ZAPD/ZAPD/ZTextureAnimation.h b/tools/ZAPD/ZAPD/ZTextureAnimation.h new file mode 100644 index 0000000000..6b03eb7cf4 --- /dev/null +++ b/tools/ZAPD/ZAPD/ZTextureAnimation.h @@ -0,0 +1,151 @@ +#pragma once + +#include +#include +#include +#include + +#include "ZResource.h" + +enum class TextureAnimationParamsType +{ + /* 0 */ SingleScroll, + /* 1 */ DualScroll, + /* 2 */ ColorChange, + /* 3 */ ColorChangeLERP, + /* 4 */ ColorChangeLagrange, + /* 5 */ TextureCycle, + /* 6 */ Empty // An empty TextureAnimation has the form 00 00 00 06 00000000 +}; + +class ZTextureAnimationParams : public ZResource +{ +public: + ZTextureAnimationParams(ZFile* parent); + + void ExtractFromBinary(uint32_t nRawDataIndex); + virtual void ExtractFromBinary(uint32_t nRawDataIndex, int count); + + virtual std::string GetDefaultName(const std::string& prefix) const; + ZResourceType GetResourceType() const; + + TextureAnimationParamsType type; +}; + +struct TextureScrollingParamsEntry +{ + int8_t xStep; + int8_t yStep; + uint8_t width; + uint8_t height; +}; + +class TextureScrollingParams : public ZTextureAnimationParams +{ +public: + TextureScrollingParams(ZFile* parent); + + void ParseRawData() override; + void ExtractFromBinary(uint32_t nRawDataIndex, int count) override; + + std::string GetSourceTypeName() const override; + std::string GetDefaultName(const std::string& prefix) const override; + size_t GetRawDataSize() const override; + + Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override; + std::string GetBodySourceCode() const override; + + int count; // 1 for Single, 2 for Dual + TextureScrollingParamsEntry rows[2]; // Too small to make a vector worth it +}; + +struct F3DPrimColor +{ + uint8_t r; + uint8_t g; + uint8_t b; + uint8_t a; + uint8_t lodFrac; +}; + +struct F3DEnvColor +{ + uint8_t r; + uint8_t g; + uint8_t b; + uint8_t a; +}; + +class TextureColorChangingParams : public ZTextureAnimationParams +{ +public: + TextureColorChangingParams(ZFile* parent); + + void ParseRawData() override; + + std::string GetSourceTypeName() const override; + std::string GetDefaultName(const std::string& prefix) const override; + size_t GetRawDataSize() const override; + + void DeclareReferences(const std::string& prefix) override; + + std::string GetBodySourceCode() const override; + + uint16_t animLength; // size of list for type 2 + uint16_t colorListCount; + segptr_t primColorListAddress; + segptr_t envColorListAddress; + segptr_t frameDataListAddress; + std::vector primColorList; + std::vector envColorList; + std::vector frameDataList; +}; + +class TextureCyclingParams : public ZTextureAnimationParams +{ +public: + TextureCyclingParams(ZFile* parent); + + void ParseRawData() override; + + std::string GetSourceTypeName() const override; + std::string GetDefaultName(const std::string& prefix) const override; + size_t GetRawDataSize() const override; + + void DeclareReferences(const std::string& prefix) override; + + std::string GetBodySourceCode() const override; + + uint16_t cycleLength; + segptr_t textureListAddress; + segptr_t textureIndexListAddress; + std::vector textureList; + std::vector textureIndexList; +}; + +struct TextureAnimationEntry +{ + int8_t segment; + TextureAnimationParamsType type; + segptr_t paramsPtr; +}; + +class ZTextureAnimation : public ZResource +{ +public: + ZTextureAnimation(ZFile* nParent); + + void ParseRawData() override; + void DeclareReferences(const std::string& prefix) override; + + std::string GetSourceTypeName() const override; + ZResourceType GetResourceType() const override; + size_t GetRawDataSize() const override; + std::string GetDefaultName(const std::string& prefix) const override; + + Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override; + std::string GetBodySourceCode() const override; + +private: + std::vector entries; +}; diff --git a/tools/ZAPD/ZAPD/ZVector.cpp b/tools/ZAPD/ZAPD/ZVector.cpp index d1aef444f5..c940b0b0de 100644 --- a/tools/ZAPD/ZAPD/ZVector.cpp +++ b/tools/ZAPD/ZAPD/ZVector.cpp @@ -1,9 +1,11 @@ #include "ZVector.h" -#include -#include "BitConverter.h" -#include "File.h" + +#include + #include "Globals.h" -#include "StringHelper.h" +#include "Utils/BitConverter.h" +#include "Utils/File.h" +#include "Utils/StringHelper.h" #include "ZFile.h" REGISTER_ZFILENODE(Vector, ZVector); @@ -12,10 +14,25 @@ ZVector::ZVector(ZFile* nParent) : ZResource(nParent) { scalarType = ZScalarType::ZSCALAR_NONE; dimensions = 0; + RegisterRequiredAttribute("Type"); RegisterRequiredAttribute("Dimensions"); } +void ZVector::ExtractFromBinary(uint32_t nRawDataIndex, ZScalarType nScalarType, + uint32_t nDimensions) +{ + rawDataIndex = nRawDataIndex; + scalarType = nScalarType; + dimensions = nDimensions; + + // Don't parse raw data of external files + if (parent->GetMode() == ZFileMode::ExternalFile) + return; + + ParseRawData(); +} + void ZVector::ParseXML(tinyxml2::XMLElement* reader) { ZResource::ParseXML(reader); @@ -33,9 +50,8 @@ void ZVector::ParseRawData() for (uint32_t i = 0; i < dimensions; i++) { - ZScalar scalar(scalarType, parent); - scalar.rawDataIndex = currentRawDataIndex; - scalar.ParseRawData(); + ZScalar scalar(parent); + scalar.ExtractFromBinary(currentRawDataIndex, scalarType); currentRawDataIndex += scalar.GetRawDataSize(); scalars.push_back(scalar); @@ -83,21 +99,17 @@ std::string ZVector::GetSourceTypeName() const std::string ZVector::GetBodySourceCode() const { - std::string body = ""; + std::string body; - for (size_t i = 0; i < this->scalars.size(); i++) - body += StringHelper::Sprintf("%6s, ", scalars[i].GetBodySourceCode().c_str()); + for (size_t i = 0; i < scalars.size(); i++) + { + body += StringHelper::Sprintf("%6s", scalars[i].GetBodySourceCode().c_str()); - return "{ " + body + "}"; -} + if (i + 1 < scalars.size()) + body += ", "; + } -std::string ZVector::GetSourceOutputCode(const std::string& prefix) -{ - if (parent != nullptr) - parent->AddDeclaration(rawDataIndex, DeclarationAlignment::None, GetRawDataSize(), - GetSourceTypeName(), GetName(), GetBodySourceCode()); - - return ""; + return body; } ZResourceType ZVector::GetResourceType() const @@ -105,12 +117,11 @@ ZResourceType ZVector::GetResourceType() const return ZResourceType::Vector; } -void ZVector::SetScalarType(ZScalarType type) +DeclarationAlignment ZVector::GetDeclarationAlignment() const { - scalarType = type; -} - -void ZVector::SetDimensions(uint32_t dim) -{ - dimensions = dim; + if (scalars.size() == 0) + { + return DeclarationAlignment::Align4; + } + return scalars.at(0).GetDeclarationAlignment(); } diff --git a/tools/ZAPD/ZAPD/ZVector.h b/tools/ZAPD/ZAPD/ZVector.h index d700d43963..d1a738968d 100644 --- a/tools/ZAPD/ZAPD/ZVector.h +++ b/tools/ZAPD/ZAPD/ZVector.h @@ -10,24 +10,22 @@ class ZVector : public ZResource { public: + std::vector scalars; + ZScalarType scalarType; + uint32_t dimensions; + ZVector(ZFile* nParent); + void ExtractFromBinary(uint32_t nRawDataIndex, ZScalarType nScalarType, uint32_t nDimensions); + void ParseXML(tinyxml2::XMLElement* reader) override; void ParseRawData() override; std::string GetBodySourceCode() const override; - std::string GetSourceOutputCode(const std::string& prefix) override; bool DoesSupportArray() const override; std::string GetSourceTypeName() const override; ZResourceType GetResourceType() const override; size_t GetRawDataSize() const override; - - void SetScalarType(ZScalarType type); - void SetDimensions(uint32_t dim); - -protected: - std::vector scalars; - ZScalarType scalarType; - uint32_t dimensions; + DeclarationAlignment GetDeclarationAlignment() const override; }; diff --git a/tools/ZAPD/ZAPD/ZVtx.cpp b/tools/ZAPD/ZAPD/ZVtx.cpp index bead96fee9..d5214e840a 100644 --- a/tools/ZAPD/ZAPD/ZVtx.cpp +++ b/tools/ZAPD/ZAPD/ZVtx.cpp @@ -1,6 +1,7 @@ #include "ZVtx.h" -#include "BitConverter.h" -#include "StringHelper.h" + +#include "Utils/BitConverter.h" +#include "Utils/StringHelper.h" #include "ZFile.h" REGISTER_ZFILENODE(Vtx, ZVtx); @@ -36,27 +37,19 @@ void ZVtx::ParseRawData() a = rawData[rawDataIndex + 15]; } +Declaration* ZVtx::DeclareVar(const std::string& prefix, const std::string& bodyStr) +{ + Declaration* decl = ZResource::DeclareVar(prefix, bodyStr); + decl->isExternal = true; + return decl; +} + std::string ZVtx::GetBodySourceCode() const { return StringHelper::Sprintf("VTX(%i, %i, %i, %i, %i, %i, %i, %i, %i)", x, y, z, s, t, r, g, b, a); } -std::string ZVtx::GetSourceOutputCode(const std::string& prefix) -{ - std::string output = GetBodySourceCode(); - - if (parent != nullptr) - { - Declaration* decl = - parent->AddDeclaration(rawDataIndex, DeclarationAlignment::Align16, GetRawDataSize(), - GetSourceTypeName(), name, output); - decl->isExternal = true; - } - - return ""; -} - size_t ZVtx::GetRawDataSize() const { return 16; @@ -86,3 +79,8 @@ std::string ZVtx::GetExternalExtension() const { return "vtx"; } + +DeclarationAlignment ZVtx::GetDeclarationAlignment() const +{ + return DeclarationAlignment::Align16; +} diff --git a/tools/ZAPD/ZAPD/ZVtx.h b/tools/ZAPD/ZAPD/ZVtx.h index feed307665..018a1d4a9a 100644 --- a/tools/ZAPD/ZAPD/ZVtx.h +++ b/tools/ZAPD/ZAPD/ZVtx.h @@ -18,8 +18,9 @@ public: ZVtx(ZFile* nParent); void ParseRawData() override; + + Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override; std::string GetBodySourceCode() const override; - std::string GetSourceOutputCode(const std::string& prefix) override; bool IsExternalResource() const override; bool DoesSupportArray() const override; @@ -28,6 +29,5 @@ public: std::string GetExternalExtension() const override; size_t GetRawDataSize() const override; - -protected: -}; \ No newline at end of file + DeclarationAlignment GetDeclarationAlignment() const override; +}; diff --git a/tools/ZAPD/ZAPD/genbuildinfo.py b/tools/ZAPD/ZAPD/genbuildinfo.py index fedd3ed575..91a567d317 100644 --- a/tools/ZAPD/ZAPD/genbuildinfo.py +++ b/tools/ZAPD/ZAPD/genbuildinfo.py @@ -9,10 +9,10 @@ parser = argparse.ArgumentParser() parser.add_argument("--devel", action="store_true") args = parser.parse_args() -with open("ZAPD/BuildInfo.h", "w+") as buildFile: +with open("build/ZAPD/BuildInfo.cpp", "w+") as buildFile: label = subprocess.check_output(["git", "describe", "--always"]).strip().decode("utf-8") now = datetime.now() if args.devel: label += " ~ Development version" - buildFile.write("const char gBuildHash[] = \"" + label + "\";\n") - #buildFile.write("const char gBuildDate[] = \"" + now.strftime("%Y-%m-%d %H:%M:%S") + "\";\n") + buildFile.write("extern const char gBuildHash[] = \"" + label + "\";\n") + #buildFile.write("extern const char gBuildDate[] = \"" + now.strftime("%Y-%m-%d %H:%M:%S") + "\";\n") diff --git a/tools/ZAPD/ZAPD/packages.config b/tools/ZAPD/ZAPD/packages.config new file mode 100644 index 0000000000..a7f2abbd29 --- /dev/null +++ b/tools/ZAPD/ZAPD/packages.config @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/tools/ZAPD/ZAPDUtils/Color3b.h b/tools/ZAPD/ZAPDUtils/Color3b.h new file mode 100644 index 0000000000..7e59f6b7f7 --- /dev/null +++ b/tools/ZAPD/ZAPDUtils/Color3b.h @@ -0,0 +1,21 @@ +#pragma once + +#include + +struct Color3b +{ + uint8_t r, g, b; + + Color3b() + { + r = 0; + g = 0; + b = 0; + }; + Color3b(uint8_t nR, uint8_t nG, uint8_t nB) + { + r = nR; + g = nG; + b = nB; + }; +}; \ No newline at end of file diff --git a/tools/ZAPD/ZAPDUtils/Makefile b/tools/ZAPD/ZAPDUtils/Makefile new file mode 100644 index 0000000000..aef6780313 --- /dev/null +++ b/tools/ZAPD/ZAPDUtils/Makefile @@ -0,0 +1,28 @@ +# Only used for standalone compilation, usually inherits these from the main makefile +CXXFLAGS ?= -Wall -Wextra -O2 -g -std=c++17 + +SRC_DIRS := $(shell find -type d -not -path "*build*") +CPP_FILES := $(foreach dir,$(SRC_DIRS),$(wildcard $(dir)/*.cpp)) +H_FILES := $(foreach dir,$(SRC_DIRS),$(wildcard $(dir)/*.h)) + +O_FILES := $(foreach f,$(CPP_FILES:.cpp=.o),build/$f) +LIB := ZAPDUtils.a + +# create build directories +$(shell mkdir -p $(foreach dir,$(SRC_DIRS),build/$(dir))) + +all: $(LIB) + +clean: + rm -rf build $(LIB) + +format: + clang-format-11 -i $(CPP_FILES) $(H_FILES) + +.PHONY: all clean format + +build/%.o: %.cpp + $(CXX) $(CXXFLAGS) $(OPTFLAGS) -c $(OUTPUT_OPTION) $< + +$(LIB): $(O_FILES) + $(AR) rcs $@ $^ diff --git a/tools/ZAPD/ZAPDUtils/StrHash.h b/tools/ZAPD/ZAPDUtils/StrHash.h new file mode 100644 index 0000000000..68d22b9cd6 --- /dev/null +++ b/tools/ZAPD/ZAPDUtils/StrHash.h @@ -0,0 +1,51 @@ +#pragma once + +#include +#include +#include + +typedef uint32_t strhash; + +[[maybe_unused]] static strhash CRC32B(unsigned char* message, int32_t size) +{ + int32_t byte = 0, crc = 0; + int32_t mask = 0; + + crc = 0xFFFFFFFF; + + for (int32_t i = 0; i < size; i++) + { + byte = message[i]; + crc = crc ^ byte; + + for (int32_t j = 7; j >= 0; j--) + { + mask = -(crc & 1); + crc = (crc >> 1) ^ (0xEDB88320 & mask); + } + } + + return ~(uint32_t)(crc); +} + +[[maybe_unused]] constexpr static strhash CRC32BCT(const char* message, int32_t size) +{ + int32_t byte = 0, crc = 0; + int32_t mask = 0; + + crc = 0xFFFFFFFF; + + for (int32_t i = 0; i < size; i++) + { + byte = message[i]; + crc = crc ^ byte; + + for (int32_t j = 7; j >= 0; j--) + { + mask = -(crc & 1); + crc = (crc >> 1) ^ (0xEDB88320 & mask); + } + } + + return ~(uint32_t)(crc); +} \ No newline at end of file diff --git a/tools/ZAPD/ZAPDUtils/Utils/BinaryReader.cpp b/tools/ZAPD/ZAPDUtils/Utils/BinaryReader.cpp new file mode 100644 index 0000000000..a4cf782294 --- /dev/null +++ b/tools/ZAPD/ZAPDUtils/Utils/BinaryReader.cpp @@ -0,0 +1,148 @@ +#include "BinaryReader.h" +#include +#include +#include "Stream.h" + +BinaryReader::BinaryReader(Stream* nStream) +{ + stream.reset(nStream); +} + +void BinaryReader::Close() +{ + stream->Close(); +} + +void BinaryReader::Seek(uint32_t offset, SeekOffsetType seekType) +{ + stream->Seek(offset, seekType); +} + +uint32_t BinaryReader::GetBaseAddress() +{ + return stream->GetBaseAddress(); +} + +void BinaryReader::Read([[maybe_unused]] char* buffer, int32_t length) +{ + stream->Read(length); +} + +char BinaryReader::ReadChar() +{ + return (char)stream->ReadByte(); +} + +int8_t BinaryReader::ReadByte() +{ + return stream->ReadByte(); +} + +uint8_t BinaryReader::ReadUByte() +{ + return (uint8_t)stream->ReadByte(); +} + +int16_t BinaryReader::ReadInt16() +{ + int16_t result = 0; + + stream->Read((char*)&result, sizeof(int16_t)); + return result; +} + +int32_t BinaryReader::ReadInt32() +{ + int32_t result = 0; + + stream->Read((char*)&result, sizeof(int32_t)); + return result; +} + +uint16_t BinaryReader::ReadUInt16() +{ + uint16_t result = 0; + + stream->Read((char*)&result, sizeof(uint16_t)); + return result; +} + +uint32_t BinaryReader::ReadUInt32() +{ + uint32_t result = 0; + + stream->Read((char*)&result, sizeof(uint32_t)); + return result; +} + +uint64_t BinaryReader::ReadUInt64() +{ + uint64_t result = 0; + + stream->Read((char*)&result, sizeof(uint64_t)); + return result; +} + +float BinaryReader::ReadSingle() +{ + float result = NAN; + + stream->Read((char*)&result, sizeof(float)); + + if (isnan(result)) + throw std::runtime_error("BinaryReader::ReadSingle(): Error reading stream"); + + return result; +} + +double BinaryReader::ReadDouble() +{ + double result = NAN; + + stream->Read((char*)&result, sizeof(double)); + if (isnan(result)) + throw std::runtime_error("BinaryReader::ReadDouble(): Error reading stream"); + + return result; +} + +Vec3f BinaryReader::ReadVec3f() +{ + return Vec3f(); +} + +Vec3s BinaryReader::ReadVec3s() +{ + return Vec3s(0, 0, 0); +} + +Vec3s BinaryReader::ReadVec3b() +{ + return Vec3s(0, 0, 0); +} + +Vec2f BinaryReader::ReadVec2f() +{ + return Vec2f(); +} + +Color3b BinaryReader::ReadColor3b() +{ + return Color3b(); +} + +std::string BinaryReader::ReadString() +{ + std::string res; + char c; + + do + { + c = ReadChar(); + + if (c != 0) + res += c; + } while (c != 0); + + return res; +} \ No newline at end of file diff --git a/tools/ZAPD/ZAPDUtils/Utils/BinaryReader.h b/tools/ZAPD/ZAPDUtils/Utils/BinaryReader.h new file mode 100644 index 0000000000..cf0eeb42c9 --- /dev/null +++ b/tools/ZAPD/ZAPDUtils/Utils/BinaryReader.h @@ -0,0 +1,43 @@ +#pragma once + +#include +#include +#include +#include +#include "../Color3b.h" +#include "../Vec2f.h" +#include "../Vec3f.h" +#include "../Vec3s.h" +#include "Stream.h" + +class BinaryReader +{ +public: + BinaryReader(Stream* nStream); + + void Close(); + + void Seek(uint32_t offset, SeekOffsetType seekType); + uint32_t GetBaseAddress(); + + void Read(char* buffer, int32_t length); + char ReadChar(); + int8_t ReadByte(); + int16_t ReadInt16(); + int32_t ReadInt32(); + uint8_t ReadUByte(); + uint16_t ReadUInt16(); + uint32_t ReadUInt32(); + uint64_t ReadUInt64(); + float ReadSingle(); + double ReadDouble(); + Vec3f ReadVec3f(); + Vec3s ReadVec3s(); + Vec3s ReadVec3b(); + Vec2f ReadVec2f(); + Color3b ReadColor3b(); + std::string ReadString(); + +protected: + std::shared_ptr stream; +}; \ No newline at end of file diff --git a/tools/ZAPD/ZAPDUtils/Utils/BinaryWriter.cpp b/tools/ZAPD/ZAPDUtils/Utils/BinaryWriter.cpp new file mode 100644 index 0000000000..87bc0ac684 --- /dev/null +++ b/tools/ZAPD/ZAPDUtils/Utils/BinaryWriter.cpp @@ -0,0 +1,95 @@ +#include "BinaryWriter.h" + +BinaryWriter::BinaryWriter(Stream* nStream) +{ + stream.reset(nStream); +} + +BinaryWriter::BinaryWriter(std::shared_ptr nStream) +{ + stream = nStream; +} + +void BinaryWriter::Close() +{ + stream->Close(); +} + +std::shared_ptr BinaryWriter::GetStream() +{ + return stream; +} + +uint64_t BinaryWriter::GetBaseAddress() +{ + return stream->GetBaseAddress(); +} + +uint64_t BinaryWriter::GetLength() +{ + return stream->GetLength(); +} + +void BinaryWriter::Seek(int32_t offset, SeekOffsetType seekType) +{ + stream->Seek(offset, seekType); +} + +void BinaryWriter::Write(int8_t value) +{ + stream->Write((char*)&value, sizeof(int8_t)); +} + +void BinaryWriter::Write(uint8_t value) +{ + stream->Write((char*)&value, sizeof(uint8_t)); +} + +void BinaryWriter::Write(int16_t value) +{ + stream->Write((char*)&value, sizeof(int16_t)); +} + +void BinaryWriter::Write(uint16_t value) +{ + stream->Write((char*)&value, sizeof(uint16_t)); +} + +void BinaryWriter::Write(int32_t value) +{ + stream->Write((char*)&value, sizeof(int32_t)); +} + +void BinaryWriter::Write(uint32_t value) +{ + stream->Write((char*)&value, sizeof(uint32_t)); +} + +void BinaryWriter::Write(int64_t value) +{ + stream->Write((char*)&value, sizeof(int64_t)); +} + +void BinaryWriter::Write(uint64_t value) +{ + stream->Write((char*)&value, sizeof(uint64_t)); +} + +void BinaryWriter::Write(float value) +{ + stream->Write((char*)&value, sizeof(float)); +} + +void BinaryWriter::Write(double value) +{ + stream->Write((char*)&value, sizeof(double)); +} + +void BinaryWriter::Write(const std::string& str) +{ + int strLen = str.size(); + stream->Write((char*)&strLen, sizeof(int)); + + for (char c : str) + stream->WriteByte(c); +} diff --git a/tools/ZAPD/ZAPDUtils/Utils/BinaryWriter.h b/tools/ZAPD/ZAPDUtils/Utils/BinaryWriter.h new file mode 100644 index 0000000000..e224d182e3 --- /dev/null +++ b/tools/ZAPD/ZAPDUtils/Utils/BinaryWriter.h @@ -0,0 +1,35 @@ +#pragma once + +#include +#include +#include +#include +#include "Stream.h" + +class BinaryWriter +{ +public: + BinaryWriter(Stream* nStream); + BinaryWriter(std::shared_ptr nStream); + + std::shared_ptr GetStream(); + uint64_t GetBaseAddress(); + uint64_t GetLength(); + void Seek(int32_t offset, SeekOffsetType seekType); + void Close(); + + void Write(int8_t value); + void Write(uint8_t value); + void Write(int16_t value); + void Write(uint16_t value); + void Write(int32_t value); + void Write(uint32_t value); + void Write(int64_t value); + void Write(uint64_t value); + void Write(float value); + void Write(double value); + void Write(const std::string& str); + +protected: + std::shared_ptr stream; +}; \ No newline at end of file diff --git a/tools/ZAPD/ZAPD/BitConverter.h b/tools/ZAPD/ZAPDUtils/Utils/BitConverter.h similarity index 96% rename from tools/ZAPD/ZAPD/BitConverter.h rename to tools/ZAPD/ZAPDUtils/Utils/BitConverter.h index a36cc534f9..5cca35b319 100644 --- a/tools/ZAPD/ZAPD/BitConverter.h +++ b/tools/ZAPD/ZAPDUtils/Utils/BitConverter.h @@ -136,7 +136,8 @@ public: static_assert(sizeof(uint64_t) == sizeof(double), "expected 64-bit double"); // Checks if the float format on the platform the ZAPD binary is running on supports the // same float format as the object file. - static_assert(std::numeric_limits::is_iec559, "expected IEC559 floats on host machine"); + static_assert(std::numeric_limits::is_iec559, + "expected IEC559 floats on host machine"); std::memcpy(&value, &floatData, sizeof(value)); return value; } @@ -152,7 +153,8 @@ public: static_assert(sizeof(uint64_t) == sizeof(double), "expected 64-bit double"); // Checks if the float format on the platform the ZAPD binary is running on supports the // same float format as the object file. - static_assert(std::numeric_limits::is_iec559, "expected IEC559 doubles on host machine"); + static_assert(std::numeric_limits::is_iec559, + "expected IEC559 doubles on host machine"); std::memcpy(&value, &floatData, sizeof(value)); return value; } diff --git a/tools/ZAPD/ZAPD/Directory.h b/tools/ZAPD/ZAPDUtils/Utils/Directory.h similarity index 96% rename from tools/ZAPD/ZAPD/Directory.h rename to tools/ZAPD/ZAPDUtils/Utils/Directory.h index adb2e17d28..eaa6a26abb 100644 --- a/tools/ZAPD/ZAPD/Directory.h +++ b/tools/ZAPD/ZAPDUtils/Utils/Directory.h @@ -23,7 +23,7 @@ public: static void CreateDirectory(const std::string& path) { - std::string curPath = ""; + std::string curPath; std::vector split = StringHelper::Split(path, "/"); for (std::string s : split) diff --git a/tools/ZAPD/ZAPD/File.h b/tools/ZAPD/ZAPDUtils/Utils/File.h similarity index 80% rename from tools/ZAPD/ZAPD/File.h rename to tools/ZAPD/ZAPDUtils/Utils/File.h index 4cb7b56093..e3f8880cb6 100644 --- a/tools/ZAPD/ZAPD/File.h +++ b/tools/ZAPD/ZAPDUtils/Utils/File.h @@ -6,7 +6,7 @@ #include #include #include "Directory.h" -#include "StringHelper.h" +#include "Utils/StringHelper.h" class File { @@ -58,6 +58,18 @@ public: file.write((char*)data.data(), data.size()); }; + static void WriteAllBytes(const std::string& filePath, const std::vector& data) + { + std::ofstream file(filePath, std::ios::binary); + file.write((char*)data.data(), data.size()); + }; + + static void WriteAllBytes(const std::string& filePath, const char* data, int dataSize) + { + std::ofstream file(filePath, std::ios::binary); + file.write((char*)data, dataSize); + }; + static void WriteAllText(const fs::path& filePath, const std::string& text) { std::ofstream file(filePath, std::ios::out); diff --git a/tools/ZAPD/ZAPDUtils/Utils/MemoryStream.cpp b/tools/ZAPD/ZAPDUtils/Utils/MemoryStream.cpp new file mode 100644 index 0000000000..6c27399d6c --- /dev/null +++ b/tools/ZAPD/ZAPDUtils/Utils/MemoryStream.cpp @@ -0,0 +1,96 @@ +#include "MemoryStream.h" +#include + +#ifndef _MSC_VER +#define memcpy_s(dest, destSize, source, sourceSize) memcpy(dest, source, destSize) +#endif + +MemoryStream::MemoryStream() +{ + buffer = std::vector(); + bufferSize = 0; + baseAddress = 0; +} + +MemoryStream::MemoryStream(char* nBuffer, size_t nBufferSize) : MemoryStream() +{ + buffer = std::vector(nBuffer, nBuffer + nBufferSize); + bufferSize = nBufferSize; + baseAddress = 0; +} + +MemoryStream::~MemoryStream() +{ +} + +uint64_t MemoryStream::GetLength() +{ + return buffer.size(); +} + +void MemoryStream::Seek(int32_t offset, SeekOffsetType seekType) +{ + if (seekType == SeekOffsetType::Start) + baseAddress = offset; + else if (seekType == SeekOffsetType::Current) + baseAddress += offset; + else if (seekType == SeekOffsetType::End) + baseAddress = bufferSize - 1 - offset; +} + +std::unique_ptr MemoryStream::Read(size_t length) +{ + std::unique_ptr result = std::make_unique(length); + + memcpy_s(result.get(), length, &buffer[baseAddress], length); + baseAddress += length; + + return result; +} + +void MemoryStream::Read(const char* dest, size_t length) +{ + memcpy_s((void*)dest, length, &buffer[baseAddress], length); + baseAddress += length; +} + +int8_t MemoryStream::ReadByte() +{ + return buffer[baseAddress++]; +} + +void MemoryStream::Write(char* srcBuffer, size_t length) +{ + if (baseAddress + length >= buffer.size()) + { + buffer.resize(baseAddress + length); + bufferSize += length; + } + + memcpy_s(&buffer[baseAddress], length, srcBuffer, length); + baseAddress += length; +} + +void MemoryStream::WriteByte(int8_t value) +{ + if (baseAddress >= buffer.size()) + { + buffer.resize(baseAddress + 1); + bufferSize = baseAddress; + } + + buffer[baseAddress++] = value; +} + +std::vector MemoryStream::ToVector() +{ + return buffer; +} + +void MemoryStream::Flush() +{ +} + +void MemoryStream::Close() +{ +} \ No newline at end of file diff --git a/tools/ZAPD/ZAPDUtils/Utils/MemoryStream.h b/tools/ZAPD/ZAPDUtils/Utils/MemoryStream.h new file mode 100644 index 0000000000..5a17bb0c36 --- /dev/null +++ b/tools/ZAPD/ZAPDUtils/Utils/MemoryStream.h @@ -0,0 +1,33 @@ +#pragma once + +#include +#include +#include "Stream.h" + +class MemoryStream : public Stream +{ +public: + MemoryStream(); + MemoryStream(char* nBuffer, size_t nBufferSize); + ~MemoryStream(); + + uint64_t GetLength() override; + + void Seek(int32_t offset, SeekOffsetType seekType) override; + + std::unique_ptr Read(size_t length) override; + void Read(const char* dest, size_t length) override; + int8_t ReadByte() override; + + void Write(char* srcBuffer, size_t length) override; + void WriteByte(int8_t value) override; + + std::vector ToVector(); + + void Flush() override; + void Close() override; + +protected: + std::vector buffer; + std::size_t bufferSize; +}; \ No newline at end of file diff --git a/tools/ZAPD/ZAPDUtils/Utils/Path.h b/tools/ZAPD/ZAPDUtils/Utils/Path.h new file mode 100644 index 0000000000..496a0ae13c --- /dev/null +++ b/tools/ZAPD/ZAPDUtils/Utils/Path.h @@ -0,0 +1,50 @@ +#pragma once + +#include +#include +#include "Utils/StringHelper.h" + +#if __has_include() +#include +namespace fs = std::filesystem; +#else +#include +namespace fs = std::experimental::filesystem; +#endif + +class Path +{ +public: + static std::string GetFileName(const fs::path& input) + { + // https://en.cppreference.com/w/cpp/filesystem/path/filename + return input.filename(); + }; + + static std::string GetFileNameWithoutExtension(const fs::path& input) + { + // https://en.cppreference.com/w/cpp/filesystem/path/stem + return input.stem(); + }; + + static std::string GetFileNameExtension(const std::string& input) + { + return input.substr(input.find_last_of("."), input.length()); + }; + + static fs::path GetPath(const std::string& input) + { + std::vector split = StringHelper::Split(input, "/"); + fs::path output; + + for (std::string str : split) + { + if (str.find_last_of(".") == std::string::npos) + output /= str; + } + + return output; + }; + + static fs::path GetDirectoryName(const fs::path& path) { return path.parent_path(); }; +}; diff --git a/tools/ZAPD/ZAPDUtils/Utils/Stream.h b/tools/ZAPD/ZAPDUtils/Utils/Stream.h new file mode 100644 index 0000000000..060e23cd27 --- /dev/null +++ b/tools/ZAPD/ZAPDUtils/Utils/Stream.h @@ -0,0 +1,41 @@ +#pragma once + +#include +#include + +enum class SeekOffsetType +{ + Start, + Current, + End +}; + +// TODO: Eventually account for endianess in binaryreader and binarywriter +enum class Endianess +{ + Little = 0, + Big = 1, +}; + +class Stream +{ +public: + virtual ~Stream() = default; + virtual uint64_t GetLength() = 0; + uint64_t GetBaseAddress() { return baseAddress; } + + virtual void Seek(int32_t offset, SeekOffsetType seekType) = 0; + + virtual std::unique_ptr Read(size_t length) = 0; + virtual void Read(const char* dest, size_t length) = 0; + virtual int8_t ReadByte() = 0; + + virtual void Write(char* destBuffer, size_t length) = 0; + virtual void WriteByte(int8_t value) = 0; + + virtual void Flush() = 0; + virtual void Close() = 0; + +protected: + uint64_t baseAddress; +}; \ No newline at end of file diff --git a/tools/ZAPD/ZAPD/StringHelper.h b/tools/ZAPD/ZAPDUtils/Utils/StringHelper.h similarity index 97% rename from tools/ZAPD/ZAPD/StringHelper.h rename to tools/ZAPD/ZAPDUtils/Utils/StringHelper.h index 26516d0fd8..74607ce3a2 100644 --- a/tools/ZAPD/ZAPD/StringHelper.h +++ b/tools/ZAPD/ZAPDUtils/Utils/StringHelper.h @@ -7,13 +7,11 @@ #include #include -#ifndef __PRETTY_FUNCTION__ #ifdef _MSC_VER #define __PRETTY_FUNCTION__ __FUNCSIG__ -#else +#elif not defined(__GNUC__) #define __PRETTY_FUNCTION__ __func__ #endif -#endif class StringHelper { @@ -83,7 +81,7 @@ public: { char buffer[32768]; // char buffer[2048]; - std::string output = ""; + std::string output; va_list va; va_start(va, format); diff --git a/tools/ZAPD/ZAPDUtils/Vec2f.h b/tools/ZAPD/ZAPDUtils/Vec2f.h new file mode 100644 index 0000000000..9d4beeb465 --- /dev/null +++ b/tools/ZAPD/ZAPDUtils/Vec2f.h @@ -0,0 +1,19 @@ +#pragma once + +#include + +struct Vec2f +{ + float x, y; + + Vec2f() + { + x = 0; + y = 0; + }; + Vec2f(float nX, float nY) + { + x = nX; + y = nY; + }; +}; \ No newline at end of file diff --git a/tools/ZAPD/ZAPDUtils/Vec3f.h b/tools/ZAPD/ZAPDUtils/Vec3f.h new file mode 100644 index 0000000000..4bfbb3c254 --- /dev/null +++ b/tools/ZAPD/ZAPDUtils/Vec3f.h @@ -0,0 +1,21 @@ +#pragma once + +#include + +struct Vec3f +{ + float x, y, z; + + Vec3f() + { + x = 0; + y = 0; + z = 0; + }; + Vec3f(float nX, float nY, float nZ) + { + x = nX; + y = nY; + z = nZ; + }; +}; \ No newline at end of file diff --git a/tools/ZAPD/ZAPD/Vec3s.h b/tools/ZAPD/ZAPDUtils/Vec3s.h similarity index 100% rename from tools/ZAPD/ZAPD/Vec3s.h rename to tools/ZAPD/ZAPDUtils/Vec3s.h diff --git a/tools/ZAPD/ZAPDUtils/ZAPDUtils.vcxproj b/tools/ZAPD/ZAPDUtils/ZAPDUtils.vcxproj new file mode 100644 index 0000000000..803cdb5f01 --- /dev/null +++ b/tools/ZAPD/ZAPDUtils/ZAPDUtils.vcxproj @@ -0,0 +1,165 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + Win32Proj + {a2e01c3e-d647-45d1-9788-043debc1a908} + ZAPDUtils + 10.0 + + + + Application + true + v142 + Unicode + + + Application + false + v142 + true + Unicode + + + StaticLibrary + true + v142 + Unicode + + + Application + false + v142 + true + Unicode + + + + + + + + + + + + + + + + + + + + + true + + + false + + + true + + + false + + + + Level3 + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + Level3 + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tools/ZAPD/ZAPDUtils/ZAPDUtils.vcxproj.filters b/tools/ZAPD/ZAPDUtils/ZAPDUtils.vcxproj.filters new file mode 100644 index 0000000000..48117c845f --- /dev/null +++ b/tools/ZAPD/ZAPDUtils/ZAPDUtils.vcxproj.filters @@ -0,0 +1,78 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + {d8c2c1e7-b065-4b0f-86a2-46ab46eedc0b} + + + {e047919d-7186-49ca-b115-e48fbb5c8743} + + + + + Header Files\Utils + + + Header Files\Utils + + + Header Files\Utils + + + Header Files\Utils + + + Header Files\Utils + + + Header Files\Utils + + + Header Files\Utils + + + Header Files\Utils + + + Header Files + + + Header Files\Utils + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + + + Source Files\Utils + + + Source Files\Utils + + + Source Files\Utils + + + \ No newline at end of file diff --git a/tools/ZAPD/copycheck.py b/tools/ZAPD/copycheck.py index d13f9843d4..36288f6853 100755 --- a/tools/ZAPD/copycheck.py +++ b/tools/ZAPD/copycheck.py @@ -1,3 +1,5 @@ +#!/usr/bin/env python3 + import os from shutil import copyfile diff --git a/tools/ZAPD/docs/zapd_extraction_xml_reference.md b/tools/ZAPD/docs/zapd_extraction_xml_reference.md index 9d84525631..818d9f1c70 100644 --- a/tools/ZAPD/docs/zapd_extraction_xml_reference.md +++ b/tools/ZAPD/docs/zapd_extraction_xml_reference.md @@ -13,7 +13,9 @@ This document aims to be a small reference of how to create a compatible xml fil - [Background](#background) - [Blob](#blob) - [DList](#dlist) + - [TextureAnimation](#textureanimation) - [Scene and Room](#scene-and-room) + - [AltHeader](#altheader) - [Animation](#animation) - [PlayerAnimation](#playeranimation) - [CurveAnimation](#curveanimation) @@ -30,6 +32,7 @@ This document aims to be a small reference of how to create a compatible xml fil - [Cutscene](#cutscene) - [Array](#array) - [Path](#path) + - [PlayerAnimationData](#playeranimationdata) ## Basic XML @@ -42,7 +45,7 @@ An example of an object xml: - + @@ -67,6 +70,20 @@ For most resources inside a `` tag **you should also set an `Offset` attri It's worth noting that every tag expects a `Name="gNameOfTheAsset"`. This is will be the name of the extracted variable in the output C code. Every asset must be prefixed with `g` and the suffix should represent the type of the variable. +Every tag can accept a `Static` attribute to specify if the asset should be marked as `static` or not. +There are 3 valid values (defaults to `Global`): + +- `Global`: Mark static if the flag `--static` was used. +- `On`: Override the global config and **always mark** as `static`. +- `Off`: Override the global config and **don't mark** as `static`. + +This table summarizes if the asset will be marked `static` (✅) or not (❌) +| `Static=""` attribute in XML | Without `--static` flag | With `--static` flag | +| ---------------------------- | ----------------------- | -------------------- | +| `On` | ✅ | ✅ | +| `Global` (default) | ❌ | ✅ | +| `Off` | ❌ | ❌ | + ------------------------- ### File @@ -129,7 +146,7 @@ The following is a list of the texture formats the Nintendo 64 supports, with th | 16-bit red, green, blue, alpha (RGBA) (5/5/5/1) | `G_IM_FMT_RGBA, G_IM_SIZ_16b` | `rgba16` | | 16-bit IA (8/8) | `G_IM_FMT_IA, G_IM_SIZ_16b` | `ia16` | | 16-bit YUV (Luminance, Blue-Y, Red-Y) | `G_IM_FMT_YUV, G_IM_SIZ_16b` | (not used) | -| 32-bit RGBA (8/8/8/8) | `G_IM_FMT_RGBA, G_IM_SIZ_32b` | `rgba8` | +| 32-bit RGBA (8/8/8/8) | `G_IM_FMT_RGBA, G_IM_SIZ_32b` | `rgba32` | If you want to know more about this formats, you can check [`gsDPLoadTextureBlock`](http://n64devkit.square7.ch/n64man/gdp/gDPLoadTextureBlock.htm) for most formats, or [`gDPLoadTextureBlock_4b`](http://n64devkit.square7.ch/n64man/gdp/gDPLoadTextureBlock_4b.htm) for the 4-bit formats. @@ -196,9 +213,77 @@ A.k.a. Display list, or Gfx. ------------------------- +### TextureAnimation + +A data type exclusive to Majora's Mask, that has scrolling, color changing, and texture changing capabilities. Declaring the main array will generate everything else; textures for the TextureCycle type must be declared manually in the XML to use symbols. (If it does reference any undeclared textures, ZAPD will warn and give the their offsets.) + +```xml + +``` + +- Attributes: + + - `Name`: Required. Suxffixed by `TexAnim`. + +------------------------- + ### Scene and Room -TODO. I'm hoping somebody else will do this. +`Scene`s and `Room`s are a bit special, because `Room`s usually needs assets declared in their respective `Scene` (which is in a different file), so they need to be extracted together. + +To accomplish this, the scene and each of their rooms must be declared in the same XML. + +- Example: + +```xml + + + + + + + + + + + + + + +``` + +- Attributes: + + - `HackMode`: Optional. This is a simple non-hardcoded way to handle some edge cases. Valid values: `syotes_room`. + +------------------------- + +### AltHeader + +Like `Scene`s and `Room`s, `AltHeader`s is special too. It should always be declared in the same `File` as a `Scene` or a `Room`. + +- Example: + +```xml + + + + + + + + + + + + + + +``` + +- Attributes: + + - `Name`: Required. Suxffixed by `AltHeader`. ------------------------- @@ -331,6 +416,7 @@ extern u8 gJsjutanShadowTex[2048]; - `Type`: The type of the declared variable. If missing, it will default to `void*`. - `TypeSize`: The size in bytes of the type. If missing, it will default to `4` (the size of a word and a pointer). Integer or hex value. - `Count`: Optional. If it is present, the variable will be declared as an array instead of a plain variable. The value of this attribute specifies the length of the array. If `Count` is present but it has no value (`Count=""`), then the length of the array will not be specified either in the declared variable. Integer or hex value. + - `Static`: This attribute can't be enabled on a Symbol node. A warning will be showed in this case. ------------------------- @@ -499,8 +585,6 @@ Currently, only [`Scalar`](#scalar), [`Vector`](#vector) and [`Vtx`](#vtx) suppo ------------------------- -------------------------- - ### Path - Example: @@ -515,3 +599,20 @@ Currently, only [`Scalar`](#scalar), [`Vector`](#vector) and [`Vtx`](#vtx) suppo - `NumPaths`: Optional. The amount of paths contained in the array. It must be a positive integer. ------------------------- + +### PlayerAnimationData + +Allows the extraction of the specific data of the player animations which are found in the `link_animetion` file. + +- Example: + +```xml + +``` + +- Attributes: + + - `Name`: Required. Suxffixed by `AnimData`. + - `FrameCount`: Required. The length of the animation in frames. It must be a positive integer. + +------------------------- diff --git a/tools/ZAPD/docs/zapd_xml_spec.md b/tools/ZAPD/docs/zapd_xml_spec.md new file mode 100644 index 0000000000..9fcc0d4aab --- /dev/null +++ b/tools/ZAPD/docs/zapd_xml_spec.md @@ -0,0 +1,55 @@ +# ZAPD XML specification + +ZAPD XMLs use a restrictive subset of the XML standard: any ZAPD XML must be a valid XML (All elements starting with `` ending appropriately with ``, single "empty-element" tags with `/` at the end, etc.). + +Reminder that in + +```xml + + + + + + + + + +``` + +``, ``, `` are *children* of ``, but `` is not. `` is a *descendent* of `` and a child of ``. + +- Every XML's outermost element start/end tag is a single ``. +- The children of a `` must be ``s. +- A `` has *resources* as children. A resource is almost always single empty-element tag, and has one of the types + - `` + - `` + - `` + - `` + - `` + - `` + - `` + - `` + - `` + - `` + - `` + - `` + - `` + - `` + - `` + - `` + - `` + - `` + - `` + - `` + - `` + - `` + - `` + - `` + - `` + +- A `` cannot descend from a ``. +- All resources must be children of a ``. +- `` is the only paired resource tag enclosing an element; the element must be a single resource tag, one of + - `` + - `` + - `` diff --git a/tools/ZAPD/lib/assimp-built/assimp-vc142-mt.dll b/tools/ZAPD/lib/assimp-built/assimp-vc142-mt.dll deleted file mode 100644 index bf7a2f862f..0000000000 Binary files a/tools/ZAPD/lib/assimp-built/assimp-vc142-mt.dll and /dev/null differ diff --git a/tools/ZAPD/lib/assimp-built/assimp-vc142-mt.lib b/tools/ZAPD/lib/assimp-built/assimp-vc142-mt.lib deleted file mode 100644 index 88e0a99f02..0000000000 Binary files a/tools/ZAPD/lib/assimp-built/assimp-vc142-mt.lib and /dev/null differ diff --git a/tools/ZAPD/lib/assimp/include/assimp/.editorconfig b/tools/ZAPD/lib/assimp/include/assimp/.editorconfig deleted file mode 100644 index 9ea66423ad..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/.editorconfig +++ /dev/null @@ -1,8 +0,0 @@ -# See for details - -[*.{h,hpp,inl}] -end_of_line = lf -insert_final_newline = true -trim_trailing_whitespace = true -indent_size = 4 -indent_style = space diff --git a/tools/ZAPD/lib/assimp/include/assimp/BaseImporter.h b/tools/ZAPD/lib/assimp/include/assimp/BaseImporter.h deleted file mode 100644 index 55f7fe3754..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/BaseImporter.h +++ /dev/null @@ -1,418 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ - -/** @file Definition of the base class for all importer worker classes. */ -#ifndef INCLUDED_AI_BASEIMPORTER_H -#define INCLUDED_AI_BASEIMPORTER_H - -#include "Exceptional.h" - -#include -#include -#include -#include -#include -#include - -struct aiScene; -struct aiImporterDesc; - -namespace Assimp { - -class Importer; -class IOSystem; -class BaseProcess; -class SharedPostProcessInfo; -class IOStream; - -// utility to do char4 to uint32 in a portable manner -#define AI_MAKE_MAGIC(string) ((uint32_t)((string[0] << 24) + \ - (string[1] << 16) + (string[2] << 8) + string[3])) - - -// --------------------------------------------------------------------------- -/** FOR IMPORTER PLUGINS ONLY: The BaseImporter defines a common interface - * for all importer worker classes. - * - * The interface defines two functions: CanRead() is used to check if the - * importer can handle the format of the given file. If an implementation of - * this function returns true, the importer then calls ReadFile() which - * imports the given file. ReadFile is not overridable, it just calls - * InternReadFile() and catches any ImportErrorException that might occur. - */ -class ASSIMP_API BaseImporter { - friend class Importer; - -private: - /* Pushes state into importer for the importer scale */ - virtual void UpdateImporterScale( Importer* pImp ); - -public: - - /** Constructor to be privately used by #Importer */ - BaseImporter() AI_NO_EXCEPT; - - /** Destructor, private as well */ - virtual ~BaseImporter(); - - // ------------------------------------------------------------------- - /** Returns whether the class can handle the format of the given file. - * - * The implementation should be as quick as possible. A check for - * the file extension is enough. If no suitable loader is found with - * this strategy, CanRead() is called again, the 'checkSig' parameter - * set to true this time. Now the implementation is expected to - * perform a full check of the file structure, possibly searching the - * first bytes of the file for magic identifiers or keywords. - * - * @param pFile Path and file name of the file to be examined. - * @param pIOHandler The IO handler to use for accessing any file. - * @param checkSig Set to true if this method is called a second time. - * This time, the implementation may take more time to examine the - * contents of the file to be loaded for magic bytes, keywords, etc - * to be able to load files with unknown/not existent file extensions. - * @return true if the class can read this file, false if not. - */ - virtual bool CanRead( - const std::string& pFile, - IOSystem* pIOHandler, - bool checkSig - ) const = 0; - - // ------------------------------------------------------------------- - /** Imports the given file and returns the imported data. - * If the import succeeds, ownership of the data is transferred to - * the caller. If the import fails, NULL is returned. The function - * takes care that any partially constructed data is destroyed - * beforehand. - * - * @param pImp #Importer object hosting this loader. - * @param pFile Path of the file to be imported. - * @param pIOHandler IO-Handler used to open this and possible other files. - * @return The imported data or NULL if failed. If it failed a - * human-readable error description can be retrieved by calling - * GetErrorText() - * - * @note This function is not intended to be overridden. Implement - * InternReadFile() to do the import. If an exception is thrown somewhere - * in InternReadFile(), this function will catch it and transform it into - * a suitable response to the caller. - */ - aiScene* ReadFile( - Importer* pImp, - const std::string& pFile, - IOSystem* pIOHandler - ); - - // ------------------------------------------------------------------- - /** Returns the error description of the last error that occurred. - * @return A description of the last error that occurred. An empty - * string if there was no error. - */ - const std::string& GetErrorText() const { - return m_ErrorText; - } - - // ------------------------------------------------------------------- - /** Called prior to ReadFile(). - * The function is a request to the importer to update its configuration - * basing on the Importer's configuration property list. - * @param pImp Importer instance - */ - virtual void SetupProperties( - const Importer* pImp - ); - - // ------------------------------------------------------------------- - /** Called by #Importer::GetImporterInfo to get a description of - * some loader features. Importers must provide this information. */ - virtual const aiImporterDesc* GetInfo() const = 0; - - /** - * Will be called only by scale process when scaling is requested. - */ - virtual void SetFileScale(double scale) - { - fileScale = scale; - } - - virtual double GetFileScale() const - { - return fileScale; - } - - enum ImporterUnits { - M, - MM, - CM, - INCHES, - FEET - }; - - /** - * Assimp Importer - * unit conversions available - * if you need another measurment unit add it below. - * it's currently defined in assimp that we prefer meters. - * */ - std::map importerUnits = { - {ImporterUnits::M, 1}, - {ImporterUnits::CM, 0.01}, - {ImporterUnits::MM, 0.001}, - {ImporterUnits::INCHES, 0.0254}, - {ImporterUnits::FEET, 0.3048} - }; - - virtual void SetApplicationUnits( const ImporterUnits& unit ) - { - importerScale = importerUnits[unit]; - applicationUnits = unit; - } - - virtual const ImporterUnits& GetApplicationUnits() - { - return applicationUnits; - } - - // ------------------------------------------------------------------- - /** Called by #Importer::GetExtensionList for each loaded importer. - * Take the extension list contained in the structure returned by - * #GetInfo and insert all file extensions into the given set. - * @param extension set to collect file extensions in*/ - void GetExtensionList(std::set& extensions); - -protected: - ImporterUnits applicationUnits = ImporterUnits::M; - double importerScale = 1.0; - double fileScale = 1.0; - - - - // ------------------------------------------------------------------- - /** Imports the given file into the given scene structure. The - * function is expected to throw an ImportErrorException if there is - * an error. If it terminates normally, the data in aiScene is - * expected to be correct. Override this function to implement the - * actual importing. - *
- * The output scene must meet the following requirements:
- *
    - *
  • At least a root node must be there, even if its only purpose - * is to reference one mesh.
  • - *
  • aiMesh::mPrimitiveTypes may be 0. The types of primitives - * in the mesh are determined automatically in this case.
  • - *
  • the vertex data is stored in a pseudo-indexed "verbose" format. - * In fact this means that every vertex that is referenced by - * a face is unique. Or the other way round: a vertex index may - * not occur twice in a single aiMesh.
  • - *
  • aiAnimation::mDuration may be -1. Assimp determines the length - * of the animation automatically in this case as the length of - * the longest animation channel.
  • - *
  • aiMesh::mBitangents may be NULL if tangents and normals are - * given. In this case bitangents are computed as the cross product - * between normal and tangent.
  • - *
  • There needn't be a material. If none is there a default material - * is generated. However, it is recommended practice for loaders - * to generate a default material for yourself that matches the - * default material setting for the file format better than Assimp's - * generic default material. Note that default materials *should* - * be named AI_DEFAULT_MATERIAL_NAME if they're just color-shaded - * or AI_DEFAULT_TEXTURED_MATERIAL_NAME if they define a (dummy) - * texture.
  • - *
- * If the AI_SCENE_FLAGS_INCOMPLETE-Flag is not set:
    - *
  • at least one mesh must be there
  • - *
  • there may be no meshes with 0 vertices or faces
  • - *
- * This won't be checked (except by the validation step): Assimp will - * crash if one of the conditions is not met! - * - * @param pFile Path of the file to be imported. - * @param pScene The scene object to hold the imported data. - * NULL is not a valid parameter. - * @param pIOHandler The IO handler to use for any file access. - * NULL is not a valid parameter. */ - virtual void InternReadFile( - const std::string& pFile, - aiScene* pScene, - IOSystem* pIOHandler - ) = 0; - -public: // static utilities - - // ------------------------------------------------------------------- - /** A utility for CanRead(). - * - * The function searches the header of a file for a specific token - * and returns true if this token is found. This works for text - * files only. There is a rudimentary handling of UNICODE files. - * The comparison is case independent. - * - * @param pIOSystem IO System to work with - * @param file File name of the file - * @param tokens List of tokens to search for - * @param numTokens Size of the token array - * @param searchBytes Number of bytes to be searched for the tokens. - */ - static bool SearchFileHeaderForToken( - IOSystem* pIOSystem, - const std::string& file, - const char** tokens, - unsigned int numTokens, - unsigned int searchBytes = 200, - bool tokensSol = false, - bool noAlphaBeforeTokens = false); - - // ------------------------------------------------------------------- - /** @brief Check whether a file has a specific file extension - * @param pFile Input file - * @param ext0 Extension to check for. Lowercase characters only, no dot! - * @param ext1 Optional second extension - * @param ext2 Optional third extension - * @note Case-insensitive - */ - static bool SimpleExtensionCheck ( - const std::string& pFile, - const char* ext0, - const char* ext1 = NULL, - const char* ext2 = NULL); - - // ------------------------------------------------------------------- - /** @brief Extract file extension from a string - * @param pFile Input file - * @return Extension without trailing dot, all lowercase - */ - static std::string GetExtension ( - const std::string& pFile); - - // ------------------------------------------------------------------- - /** @brief Check whether a file starts with one or more magic tokens - * @param pFile Input file - * @param pIOHandler IO system to be used - * @param magic n magic tokens - * @params num Size of magic - * @param offset Offset from file start where tokens are located - * @param Size of one token, in bytes. Maximally 16 bytes. - * @return true if one of the given tokens was found - * - * @note For convenience, the check is also performed for the - * byte-swapped variant of all tokens (big endian). Only for - * tokens of size 2,4. - */ - static bool CheckMagicToken( - IOSystem* pIOHandler, - const std::string& pFile, - const void* magic, - unsigned int num, - unsigned int offset = 0, - unsigned int size = 4); - - // ------------------------------------------------------------------- - /** An utility for all text file loaders. It converts a file to our - * UTF8 character set. Errors are reported, but ignored. - * - * @param data File buffer to be converted to UTF8 data. The buffer - * is resized as appropriate. */ - static void ConvertToUTF8( - std::vector& data); - - // ------------------------------------------------------------------- - /** An utility for all text file loaders. It converts a file from our - * UTF8 character set back to ISO-8859-1. Errors are reported, but ignored. - * - * @param data File buffer to be converted from UTF8 to ISO-8859-1. The buffer - * is resized as appropriate. */ - static void ConvertUTF8toISO8859_1( - std::string& data); - - // ------------------------------------------------------------------- - /// @brief Enum to define, if empty files are ok or not. - enum TextFileMode { - ALLOW_EMPTY, - FORBID_EMPTY - }; - - // ------------------------------------------------------------------- - /** Utility for text file loaders which copies the contents of the - * file into a memory buffer and converts it to our UTF8 - * representation. - * @param stream Stream to read from. - * @param data Output buffer to be resized and filled with the - * converted text file data. The buffer is terminated with - * a binary 0. - * @param mode Whether it is OK to load empty text files. */ - static void TextFileToBuffer( - IOStream* stream, - std::vector& data, - TextFileMode mode = FORBID_EMPTY); - - // ------------------------------------------------------------------- - /** Utility function to move a std::vector into a aiScene array - * @param vec The vector to be moved - * @param out The output pointer to the allocated array. - * @param numOut The output count of elements copied. */ - template - AI_FORCE_INLINE - static void CopyVector( - std::vector& vec, - T*& out, - unsigned int& outLength) - { - outLength = unsigned(vec.size()); - if (outLength) { - out = new T[outLength]; - std::swap_ranges(vec.begin(), vec.end(), out); - } - } - -protected: - /// Error description in case there was one. - std::string m_ErrorText; - /// Currently set progress handler. - ProgressHandler* m_progress; -}; - - - -} // end of namespace Assimp - -#endif // AI_BASEIMPORTER_H_INC diff --git a/tools/ZAPD/lib/assimp/include/assimp/Bitmap.h b/tools/ZAPD/lib/assimp/include/assimp/Bitmap.h deleted file mode 100644 index e6b5fb1327..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/Bitmap.h +++ /dev/null @@ -1,125 +0,0 @@ -/* ---------------------------------------------------------------------------- -Open Asset Import Library (assimp) ---------------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the following -conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------- -*/ - -/** @file Bitmap.h - * @brief Defines bitmap format helper for textures - * - * Used for file formats which embed their textures into the model file. - */ - -#ifndef AI_BITMAP_H_INC -#define AI_BITMAP_H_INC - -#include "defs.h" -#include -#include - -struct aiTexture; - -namespace Assimp { - -class IOStream; - -class ASSIMP_API Bitmap { -protected: - - struct Header { - uint16_t type; - uint32_t size; - uint16_t reserved1; - uint16_t reserved2; - uint32_t offset; - - // We define the struct size because sizeof(Header) might return a wrong result because of structure padding. - // Moreover, we must use this ugly and error prone syntax because Visual Studio neither support constexpr or sizeof(name_of_field). - static const std::size_t header_size = - sizeof(uint16_t) + // type - sizeof(uint32_t) + // size - sizeof(uint16_t) + // reserved1 - sizeof(uint16_t) + // reserved2 - sizeof(uint32_t); // offset - }; - - struct DIB { - uint32_t size; - int32_t width; - int32_t height; - uint16_t planes; - uint16_t bits_per_pixel; - uint32_t compression; - uint32_t image_size; - int32_t x_resolution; - int32_t y_resolution; - uint32_t nb_colors; - uint32_t nb_important_colors; - - // We define the struct size because sizeof(DIB) might return a wrong result because of structure padding. - // Moreover, we must use this ugly and error prone syntax because Visual Studio neither support constexpr or sizeof(name_of_field). - static const std::size_t dib_size = - sizeof(uint32_t) + // size - sizeof(int32_t) + // width - sizeof(int32_t) + // height - sizeof(uint16_t) + // planes - sizeof(uint16_t) + // bits_per_pixel - sizeof(uint32_t) + // compression - sizeof(uint32_t) + // image_size - sizeof(int32_t) + // x_resolution - sizeof(int32_t) + // y_resolution - sizeof(uint32_t) + // nb_colors - sizeof(uint32_t); // nb_important_colors - }; - - static const std::size_t mBytesPerPixel = 4; - -public: - static void Save(aiTexture* texture, IOStream* file); - -protected: - static void WriteHeader(Header& header, IOStream* file); - static void WriteDIB(DIB& dib, IOStream* file); - static void WriteData(aiTexture* texture, IOStream* file); -}; - -} - -#endif // AI_BITMAP_H_INC diff --git a/tools/ZAPD/lib/assimp/include/assimp/BlobIOSystem.h b/tools/ZAPD/lib/assimp/include/assimp/BlobIOSystem.h deleted file mode 100644 index d005e5c119..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/BlobIOSystem.h +++ /dev/null @@ -1,338 +0,0 @@ -/* ---------------------------------------------------------------------------- -Open Asset Import Library (assimp) ---------------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the following -conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------- -*/ - -/** @file Provides cheat implementations for IOSystem and IOStream to - * redirect exporter output to a blob chain.*/ - -#ifndef AI_BLOBIOSYSTEM_H_INCLUDED -#define AI_BLOBIOSYSTEM_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include - -namespace Assimp { - class BlobIOSystem; - -// -------------------------------------------------------------------------------------------- -/** Redirect IOStream to a blob */ -// -------------------------------------------------------------------------------------------- -class BlobIOStream : public IOStream -{ -public: - - BlobIOStream(BlobIOSystem* creator, const std::string& file, size_t initial = 4096) - : buffer() - , cur_size() - , file_size() - , cursor() - , initial(initial) - , file(file) - , creator(creator) - { - } - - - virtual ~BlobIOStream(); - -public: - - // ------------------------------------------------------------------- - aiExportDataBlob* GetBlob() - { - aiExportDataBlob* blob = new aiExportDataBlob(); - blob->size = file_size; - blob->data = buffer; - - buffer = NULL; - - return blob; - } - - -public: - - - // ------------------------------------------------------------------- - virtual size_t Read( void *, - size_t, - size_t ) - { - return 0; - } - - // ------------------------------------------------------------------- - virtual size_t Write(const void* pvBuffer, - size_t pSize, - size_t pCount) - { - pSize *= pCount; - if (cursor + pSize > cur_size) { - Grow(cursor + pSize); - } - - memcpy(buffer+cursor, pvBuffer, pSize); - cursor += pSize; - - file_size = std::max(file_size,cursor); - return pCount; - } - - // ------------------------------------------------------------------- - virtual aiReturn Seek(size_t pOffset, - aiOrigin pOrigin) - { - switch(pOrigin) - { - case aiOrigin_CUR: - cursor += pOffset; - break; - - case aiOrigin_END: - cursor = file_size - pOffset; - break; - - case aiOrigin_SET: - cursor = pOffset; - break; - - default: - return AI_FAILURE; - } - - if (cursor > file_size) { - Grow(cursor); - } - - file_size = std::max(cursor,file_size); - return AI_SUCCESS; - } - - // ------------------------------------------------------------------- - virtual size_t Tell() const - { - return cursor; - } - - // ------------------------------------------------------------------- - virtual size_t FileSize() const - { - return file_size; - } - - // ------------------------------------------------------------------- - virtual void Flush() - { - // ignore - } - - - -private: - - // ------------------------------------------------------------------- - void Grow(size_t need = 0) - { - // 1.5 and phi are very heap-friendly growth factors (the first - // allows for frequent re-use of heap blocks, the second - // forms a fibonacci sequence with similar characteristics - - // since this heavily depends on the heap implementation - // and other factors as well, i'll just go with 1.5 since - // it is quicker to compute). - size_t new_size = std::max(initial, std::max( need, cur_size+(cur_size>>1) )); - - const uint8_t* const old = buffer; - buffer = new uint8_t[new_size]; - - if (old) { - memcpy(buffer,old,cur_size); - delete[] old; - } - - cur_size = new_size; - } - -private: - - uint8_t* buffer; - size_t cur_size,file_size, cursor, initial; - - const std::string file; - BlobIOSystem* const creator; -}; - - -#define AI_BLOBIO_MAGIC "$blobfile" - -// -------------------------------------------------------------------------------------------- -/** Redirect IOSystem to a blob */ -// -------------------------------------------------------------------------------------------- -class BlobIOSystem : public IOSystem -{ - - friend class BlobIOStream; - typedef std::pair BlobEntry; - -public: - - BlobIOSystem() - { - } - - virtual ~BlobIOSystem() - { - for(BlobEntry& blobby : blobs) { - delete blobby.second; - } - } - -public: - - // ------------------------------------------------------------------- - const char* GetMagicFileName() const - { - return AI_BLOBIO_MAGIC; - } - - - // ------------------------------------------------------------------- - aiExportDataBlob* GetBlobChain() - { - // one must be the master - aiExportDataBlob* master = NULL, *cur; - for(const BlobEntry& blobby : blobs) { - if (blobby.first == AI_BLOBIO_MAGIC) { - master = blobby.second; - break; - } - } - if (!master) { - ASSIMP_LOG_ERROR("BlobIOSystem: no data written or master file was not closed properly."); - return NULL; - } - - master->name.Set(""); - - cur = master; - for(const BlobEntry& blobby : blobs) { - if (blobby.second == master) { - continue; - } - - cur->next = blobby.second; - cur = cur->next; - - // extract the file extension from the file written - const std::string::size_type s = blobby.first.find_first_of('.'); - cur->name.Set(s == std::string::npos ? blobby.first : blobby.first.substr(s+1)); - } - - // give up blob ownership - blobs.clear(); - return master; - } - -public: - - // ------------------------------------------------------------------- - virtual bool Exists( const char* pFile) const { - return created.find(std::string(pFile)) != created.end(); - } - - - // ------------------------------------------------------------------- - virtual char getOsSeparator() const { - return '/'; - } - - - // ------------------------------------------------------------------- - virtual IOStream* Open(const char* pFile, - const char* pMode) - { - if (pMode[0] != 'w') { - return NULL; - } - - created.insert(std::string(pFile)); - return new BlobIOStream(this,std::string(pFile)); - } - - // ------------------------------------------------------------------- - virtual void Close( IOStream* pFile) - { - delete pFile; - } - -private: - - // ------------------------------------------------------------------- - void OnDestruct(const std::string& filename, BlobIOStream* child) - { - // we don't know in which the files are closed, so we - // can't reliably say that the first must be the master - // file ... - blobs.push_back( BlobEntry(filename,child->GetBlob()) ); - } - -private: - std::set created; - std::vector< BlobEntry > blobs; -}; - - -// -------------------------------------------------------------------------------------------- -BlobIOStream :: ~BlobIOStream() -{ - creator->OnDestruct(file,this); - delete[] buffer; -} - - -} // end Assimp - -#endif diff --git a/tools/ZAPD/lib/assimp/include/assimp/ByteSwapper.h b/tools/ZAPD/lib/assimp/include/assimp/ByteSwapper.h deleted file mode 100644 index 20a2463fb8..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/ByteSwapper.h +++ /dev/null @@ -1,287 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ - -/** @file Helper class tp perform various byte oder swappings - (e.g. little to big endian) */ -#ifndef AI_BYTESWAPPER_H_INC -#define AI_BYTESWAPPER_H_INC - -#include -#include -#include - -#if _MSC_VER >= 1400 -#include -#endif - -namespace Assimp { -// -------------------------------------------------------------------------------------- -/** Defines some useful byte order swap routines. - * - * This is required to read big-endian model formats on little-endian machines, - * and vice versa. Direct use of this class is DEPRECATED. Use #StreamReader instead. */ -// -------------------------------------------------------------------------------------- -class ByteSwap { - ByteSwap() AI_NO_EXCEPT {} - -public: - - // ---------------------------------------------------------------------- - /** Swap two bytes of data - * @param[inout] _szOut A void* to save the reintcasts for the caller. */ - static inline void Swap2(void* _szOut) - { - ai_assert(_szOut); - -#if _MSC_VER >= 1400 - uint16_t* const szOut = reinterpret_cast(_szOut); - *szOut = _byteswap_ushort(*szOut); -#else - uint8_t* const szOut = reinterpret_cast(_szOut); - std::swap(szOut[0],szOut[1]); -#endif - } - - // ---------------------------------------------------------------------- - /** Swap four bytes of data - * @param[inout] _szOut A void* to save the reintcasts for the caller. */ - static inline void Swap4(void* _szOut) - { - ai_assert(_szOut); - -#if _MSC_VER >= 1400 - uint32_t* const szOut = reinterpret_cast(_szOut); - *szOut = _byteswap_ulong(*szOut); -#else - uint8_t* const szOut = reinterpret_cast(_szOut); - std::swap(szOut[0],szOut[3]); - std::swap(szOut[1],szOut[2]); -#endif - } - - // ---------------------------------------------------------------------- - /** Swap eight bytes of data - * @param[inout] _szOut A void* to save the reintcasts for the caller. */ - static inline void Swap8(void* _szOut) - { - ai_assert(_szOut); - -#if _MSC_VER >= 1400 - uint64_t* const szOut = reinterpret_cast(_szOut); - *szOut = _byteswap_uint64(*szOut); -#else - uint8_t* const szOut = reinterpret_cast(_szOut); - std::swap(szOut[0],szOut[7]); - std::swap(szOut[1],szOut[6]); - std::swap(szOut[2],szOut[5]); - std::swap(szOut[3],szOut[4]); -#endif - } - - // ---------------------------------------------------------------------- - /** ByteSwap a float. Not a joke. - * @param[inout] fOut ehm. .. */ - static inline void Swap(float* fOut) { - Swap4(fOut); - } - - // ---------------------------------------------------------------------- - /** ByteSwap a double. Not a joke. - * @param[inout] fOut ehm. .. */ - static inline void Swap(double* fOut) { - Swap8(fOut); - } - - - // ---------------------------------------------------------------------- - /** ByteSwap an int16t. Not a joke. - * @param[inout] fOut ehm. .. */ - static inline void Swap(int16_t* fOut) { - Swap2(fOut); - } - - static inline void Swap(uint16_t* fOut) { - Swap2(fOut); - } - - // ---------------------------------------------------------------------- - /** ByteSwap an int32t. Not a joke. - * @param[inout] fOut ehm. .. */ - static inline void Swap(int32_t* fOut){ - Swap4(fOut); - } - - static inline void Swap(uint32_t* fOut){ - Swap4(fOut); - } - - // ---------------------------------------------------------------------- - /** ByteSwap an int64t. Not a joke. - * @param[inout] fOut ehm. .. */ - static inline void Swap(int64_t* fOut) { - Swap8(fOut); - } - - static inline void Swap(uint64_t* fOut) { - Swap8(fOut); - } - - // ---------------------------------------------------------------------- - //! Templatized ByteSwap - //! \returns param tOut as swapped - template - static inline Type Swapped(Type tOut) - { - return _swapper()(tOut); - } - -private: - - template struct _swapper; -}; - -template struct ByteSwap::_swapper { - T operator() (T tOut) { - Swap2(&tOut); - return tOut; - } -}; - -template struct ByteSwap::_swapper { - T operator() (T tOut) { - Swap4(&tOut); - return tOut; - } -}; - -template struct ByteSwap::_swapper { - T operator() (T tOut) { - Swap8(&tOut); - return tOut; - } -}; - - -// -------------------------------------------------------------------------------------- -// ByteSwap macros for BigEndian/LittleEndian support -// -------------------------------------------------------------------------------------- -#if (defined AI_BUILD_BIG_ENDIAN) -# define AI_LE(t) (t) -# define AI_BE(t) ByteSwap::Swapped(t) -# define AI_LSWAP2(p) -# define AI_LSWAP4(p) -# define AI_LSWAP8(p) -# define AI_LSWAP2P(p) -# define AI_LSWAP4P(p) -# define AI_LSWAP8P(p) -# define LE_NCONST const -# define AI_SWAP2(p) ByteSwap::Swap2(&(p)) -# define AI_SWAP4(p) ByteSwap::Swap4(&(p)) -# define AI_SWAP8(p) ByteSwap::Swap8(&(p)) -# define AI_SWAP2P(p) ByteSwap::Swap2((p)) -# define AI_SWAP4P(p) ByteSwap::Swap4((p)) -# define AI_SWAP8P(p) ByteSwap::Swap8((p)) -# define BE_NCONST -#else -# define AI_BE(t) (t) -# define AI_LE(t) ByteSwap::Swapped(t) -# define AI_SWAP2(p) -# define AI_SWAP4(p) -# define AI_SWAP8(p) -# define AI_SWAP2P(p) -# define AI_SWAP4P(p) -# define AI_SWAP8P(p) -# define BE_NCONST const -# define AI_LSWAP2(p) ByteSwap::Swap2(&(p)) -# define AI_LSWAP4(p) ByteSwap::Swap4(&(p)) -# define AI_LSWAP8(p) ByteSwap::Swap8(&(p)) -# define AI_LSWAP2P(p) ByteSwap::Swap2((p)) -# define AI_LSWAP4P(p) ByteSwap::Swap4((p)) -# define AI_LSWAP8P(p) ByteSwap::Swap8((p)) -# define LE_NCONST -#endif - - -namespace Intern { - -// -------------------------------------------------------------------------------------------- -template -struct ByteSwapper { - void operator() (T* inout) { - ByteSwap::Swap(inout); - } -}; - -template -struct ByteSwapper { - void operator() (T*) { - } -}; - -// -------------------------------------------------------------------------------------------- -template -struct Getter { - void operator() (T* inout, bool le) { -#ifdef AI_BUILD_BIG_ENDIAN - le = le; -#else - le = !le; -#endif - if (le) { - ByteSwapper1?true:false)> () (inout); - } - else ByteSwapper () (inout); - } -}; - -template -struct Getter { - - void operator() (T* inout, bool /*le*/) { - // static branch - ByteSwapper1)> () (inout); - } -}; -} // end Intern -} // end Assimp - -#endif //!! AI_BYTESWAPPER_H_INC diff --git a/tools/ZAPD/lib/assimp/include/assimp/Compiler/poppack1.h b/tools/ZAPD/lib/assimp/include/assimp/Compiler/poppack1.h deleted file mode 100644 index e033bc1472..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/Compiler/poppack1.h +++ /dev/null @@ -1,22 +0,0 @@ - -// =============================================================================== -// May be included multiple times - resets structure packing to the defaults -// for all supported compilers. Reverts the changes made by #include -// -// Currently this works on the following compilers: -// MSVC 7,8,9 -// GCC -// BORLAND (complains about 'pack state changed but not reverted', but works) -// =============================================================================== - -#ifndef AI_PUSHPACK_IS_DEFINED -# error pushpack1.h must be included after poppack1.h -#endif - -// reset packing to the original value -#if defined(_MSC_VER) || defined(__BORLANDC__) || defined (__BCPLUSPLUS__) -# pragma pack( pop ) -#endif -#undef PACK_STRUCT - -#undef AI_PUSHPACK_IS_DEFINED diff --git a/tools/ZAPD/lib/assimp/include/assimp/Compiler/pstdint.h b/tools/ZAPD/lib/assimp/include/assimp/Compiler/pstdint.h deleted file mode 100644 index 4de4ce2a90..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/Compiler/pstdint.h +++ /dev/null @@ -1,912 +0,0 @@ -/* A portable stdint.h - **************************************************************************** - * BSD License: - **************************************************************************** - * - * Copyright (c) 2005-2016 Paul Hsieh - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - **************************************************************************** - * - * Version 0.1.15.4 - * - * The ANSI C standard committee, for the C99 standard, specified the - * inclusion of a new standard include file called stdint.h. This is - * a very useful and long desired include file which contains several - * very precise definitions for integer scalar types that is - * critically important for making portable several classes of - * applications including cryptography, hashing, variable length - * integer libraries and so on. But for most developers its likely - * useful just for programming sanity. - * - * The problem is that some compiler vendors chose to ignore the C99 - * standard and some older compilers have no opportunity to be updated. - * Because of this situation, simply including stdint.h in your code - * makes it unportable. - * - * So that's what this file is all about. Its an attempt to build a - * single universal include file that works on as many platforms as - * possible to deliver what stdint.h is supposed to. Even compilers - * that already come with stdint.h can use this file instead without - * any loss of functionality. A few things that should be noted about - * this file: - * - * 1) It is not guaranteed to be portable and/or present an identical - * interface on all platforms. The extreme variability of the - * ANSI C standard makes this an impossibility right from the - * very get go. Its really only meant to be useful for the vast - * majority of platforms that possess the capability of - * implementing usefully and precisely defined, standard sized - * integer scalars. Systems which are not intrinsically 2s - * complement may produce invalid constants. - * - * 2) There is an unavoidable use of non-reserved symbols. - * - * 3) Other standard include files are invoked. - * - * 4) This file may come in conflict with future platforms that do - * include stdint.h. The hope is that one or the other can be - * used with no real difference. - * - * 5) In the current version, if your platform can't represent - * int32_t, int16_t and int8_t, it just dumps out with a compiler - * error. - * - * 6) 64 bit integers may or may not be defined. Test for their - * presence with the test: #ifdef INT64_MAX or #ifdef UINT64_MAX. - * Note that this is different from the C99 specification which - * requires the existence of 64 bit support in the compiler. If - * this is not defined for your platform, yet it is capable of - * dealing with 64 bits then it is because this file has not yet - * been extended to cover all of your system's capabilities. - * - * 7) (u)intptr_t may or may not be defined. Test for its presence - * with the test: #ifdef PTRDIFF_MAX. If this is not defined - * for your platform, then it is because this file has not yet - * been extended to cover all of your system's capabilities, not - * because its optional. - * - * 8) The following might not been defined even if your platform is - * capable of defining it: - * - * WCHAR_MIN - * WCHAR_MAX - * (u)int64_t - * PTRDIFF_MIN - * PTRDIFF_MAX - * (u)intptr_t - * - * 9) The following have not been defined: - * - * WINT_MIN - * WINT_MAX - * - * 10) The criteria for defining (u)int_least(*)_t isn't clear, - * except for systems which don't have a type that precisely - * defined 8, 16, or 32 bit types (which this include file does - * not support anyways). Default definitions have been given. - * - * 11) The criteria for defining (u)int_fast(*)_t isn't something I - * would trust to any particular compiler vendor or the ANSI C - * committee. It is well known that "compatible systems" are - * commonly created that have very different performance - * characteristics from the systems they are compatible with, - * especially those whose vendors make both the compiler and the - * system. Default definitions have been given, but its strongly - * recommended that users never use these definitions for any - * reason (they do *NOT* deliver any serious guarantee of - * improved performance -- not in this file, nor any vendor's - * stdint.h). - * - * 12) The following macros: - * - * PRINTF_INTMAX_MODIFIER - * PRINTF_INT64_MODIFIER - * PRINTF_INT32_MODIFIER - * PRINTF_INT16_MODIFIER - * PRINTF_LEAST64_MODIFIER - * PRINTF_LEAST32_MODIFIER - * PRINTF_LEAST16_MODIFIER - * PRINTF_INTPTR_MODIFIER - * - * are strings which have been defined as the modifiers required - * for the "d", "u" and "x" printf formats to correctly output - * (u)intmax_t, (u)int64_t, (u)int32_t, (u)int16_t, (u)least64_t, - * (u)least32_t, (u)least16_t and (u)intptr_t types respectively. - * PRINTF_INTPTR_MODIFIER is not defined for some systems which - * provide their own stdint.h. PRINTF_INT64_MODIFIER is not - * defined if INT64_MAX is not defined. These are an extension - * beyond what C99 specifies must be in stdint.h. - * - * In addition, the following macros are defined: - * - * PRINTF_INTMAX_HEX_WIDTH - * PRINTF_INT64_HEX_WIDTH - * PRINTF_INT32_HEX_WIDTH - * PRINTF_INT16_HEX_WIDTH - * PRINTF_INT8_HEX_WIDTH - * PRINTF_INTMAX_DEC_WIDTH - * PRINTF_INT64_DEC_WIDTH - * PRINTF_INT32_DEC_WIDTH - * PRINTF_INT16_DEC_WIDTH - * PRINTF_UINT8_DEC_WIDTH - * PRINTF_UINTMAX_DEC_WIDTH - * PRINTF_UINT64_DEC_WIDTH - * PRINTF_UINT32_DEC_WIDTH - * PRINTF_UINT16_DEC_WIDTH - * PRINTF_UINT8_DEC_WIDTH - * - * Which specifies the maximum number of characters required to - * print the number of that type in either hexadecimal or decimal. - * These are an extension beyond what C99 specifies must be in - * stdint.h. - * - * Compilers tested (all with 0 warnings at their highest respective - * settings): Borland Turbo C 2.0, WATCOM C/C++ 11.0 (16 bits and 32 - * bits), Microsoft Visual C++ 6.0 (32 bit), Microsoft Visual Studio - * .net (VC7), Intel C++ 4.0, GNU gcc v3.3.3 - * - * This file should be considered a work in progress. Suggestions for - * improvements, especially those which increase coverage are strongly - * encouraged. - * - * Acknowledgements - * - * The following people have made significant contributions to the - * development and testing of this file: - * - * Chris Howie - * John Steele Scott - * Dave Thorup - * John Dill - * Florian Wobbe - * Christopher Sean Morrison - * Mikkel Fahnoe Jorgensen - * - */ - -#include -#include -#include - -/* - * For gcc with _STDINT_H, fill in the PRINTF_INT*_MODIFIER macros, and - * do nothing else. On the Mac OS X version of gcc this is _STDINT_H_. - */ - -#if ((defined(__SUNPRO_C) && __SUNPRO_C >= 0x570) || (defined(_MSC_VER) && _MSC_VER >= 1600) || (defined(__STDC__) && __STDC__ && defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || (defined (__WATCOMC__) && (defined (_STDINT_H_INCLUDED) || __WATCOMC__ >= 1250)) || (defined(__GNUC__) && (__GNUC__ > 3 || defined(_STDINT_H) || defined(_STDINT_H_) || defined (__UINT_FAST64_TYPE__)) )) && !defined (_PSTDINT_H_INCLUDED) -#include -#define _PSTDINT_H_INCLUDED -# if defined(__GNUC__) && (defined(__x86_64__) || defined(__ppc64__)) && !(defined(__APPLE__) && defined(__MACH__)) -# ifndef PRINTF_INT64_MODIFIER -# define PRINTF_INT64_MODIFIER "l" -# endif -# ifndef PRINTF_INT32_MODIFIER -# define PRINTF_INT32_MODIFIER "" -# endif -# else -# ifndef PRINTF_INT64_MODIFIER -# define PRINTF_INT64_MODIFIER "ll" -# endif -# ifndef PRINTF_INT32_MODIFIER -# if (UINT_MAX == UINT32_MAX) -# define PRINTF_INT32_MODIFIER "" -# else -# define PRINTF_INT32_MODIFIER "l" -# endif -# endif -# endif -# ifndef PRINTF_INT16_MODIFIER -# define PRINTF_INT16_MODIFIER "h" -# endif -# ifndef PRINTF_INTMAX_MODIFIER -# define PRINTF_INTMAX_MODIFIER PRINTF_INT64_MODIFIER -# endif -# ifndef PRINTF_INT64_HEX_WIDTH -# define PRINTF_INT64_HEX_WIDTH "16" -# endif -# ifndef PRINTF_UINT64_HEX_WIDTH -# define PRINTF_UINT64_HEX_WIDTH "16" -# endif -# ifndef PRINTF_INT32_HEX_WIDTH -# define PRINTF_INT32_HEX_WIDTH "8" -# endif -# ifndef PRINTF_UINT32_HEX_WIDTH -# define PRINTF_UINT32_HEX_WIDTH "8" -# endif -# ifndef PRINTF_INT16_HEX_WIDTH -# define PRINTF_INT16_HEX_WIDTH "4" -# endif -# ifndef PRINTF_UINT16_HEX_WIDTH -# define PRINTF_UINT16_HEX_WIDTH "4" -# endif -# ifndef PRINTF_INT8_HEX_WIDTH -# define PRINTF_INT8_HEX_WIDTH "2" -# endif -# ifndef PRINTF_UINT8_HEX_WIDTH -# define PRINTF_UINT8_HEX_WIDTH "2" -# endif -# ifndef PRINTF_INT64_DEC_WIDTH -# define PRINTF_INT64_DEC_WIDTH "19" -# endif -# ifndef PRINTF_UINT64_DEC_WIDTH -# define PRINTF_UINT64_DEC_WIDTH "20" -# endif -# ifndef PRINTF_INT32_DEC_WIDTH -# define PRINTF_INT32_DEC_WIDTH "10" -# endif -# ifndef PRINTF_UINT32_DEC_WIDTH -# define PRINTF_UINT32_DEC_WIDTH "10" -# endif -# ifndef PRINTF_INT16_DEC_WIDTH -# define PRINTF_INT16_DEC_WIDTH "5" -# endif -# ifndef PRINTF_UINT16_DEC_WIDTH -# define PRINTF_UINT16_DEC_WIDTH "5" -# endif -# ifndef PRINTF_INT8_DEC_WIDTH -# define PRINTF_INT8_DEC_WIDTH "3" -# endif -# ifndef PRINTF_UINT8_DEC_WIDTH -# define PRINTF_UINT8_DEC_WIDTH "3" -# endif -# ifndef PRINTF_INTMAX_HEX_WIDTH -# define PRINTF_INTMAX_HEX_WIDTH PRINTF_UINT64_HEX_WIDTH -# endif -# ifndef PRINTF_UINTMAX_HEX_WIDTH -# define PRINTF_UINTMAX_HEX_WIDTH PRINTF_UINT64_HEX_WIDTH -# endif -# ifndef PRINTF_INTMAX_DEC_WIDTH -# define PRINTF_INTMAX_DEC_WIDTH PRINTF_UINT64_DEC_WIDTH -# endif -# ifndef PRINTF_UINTMAX_DEC_WIDTH -# define PRINTF_UINTMAX_DEC_WIDTH PRINTF_UINT64_DEC_WIDTH -# endif - -/* - * Something really weird is going on with Open Watcom. Just pull some of - * these duplicated definitions from Open Watcom's stdint.h file for now. - */ - -# if defined (__WATCOMC__) && __WATCOMC__ >= 1250 -# if !defined (INT64_C) -# define INT64_C(x) (x + (INT64_MAX - INT64_MAX)) -# endif -# if !defined (UINT64_C) -# define UINT64_C(x) (x + (UINT64_MAX - UINT64_MAX)) -# endif -# if !defined (INT32_C) -# define INT32_C(x) (x + (INT32_MAX - INT32_MAX)) -# endif -# if !defined (UINT32_C) -# define UINT32_C(x) (x + (UINT32_MAX - UINT32_MAX)) -# endif -# if !defined (INT16_C) -# define INT16_C(x) (x) -# endif -# if !defined (UINT16_C) -# define UINT16_C(x) (x) -# endif -# if !defined (INT8_C) -# define INT8_C(x) (x) -# endif -# if !defined (UINT8_C) -# define UINT8_C(x) (x) -# endif -# if !defined (UINT64_MAX) -# define UINT64_MAX 18446744073709551615ULL -# endif -# if !defined (INT64_MAX) -# define INT64_MAX 9223372036854775807LL -# endif -# if !defined (UINT32_MAX) -# define UINT32_MAX 4294967295UL -# endif -# if !defined (INT32_MAX) -# define INT32_MAX 2147483647L -# endif -# if !defined (INTMAX_MAX) -# define INTMAX_MAX INT64_MAX -# endif -# if !defined (INTMAX_MIN) -# define INTMAX_MIN INT64_MIN -# endif -# endif -#endif - -/* - * I have no idea what is the truly correct thing to do on older Solaris. - * From some online discussions, this seems to be what is being - * recommended. For people who actually are developing on older Solaris, - * what I would like to know is, does this define all of the relevant - * macros of a complete stdint.h? Remember, in pstdint.h 64 bit is - * considered optional. - */ - -#if (defined(__SUNPRO_C) && __SUNPRO_C >= 0x420) && !defined(_PSTDINT_H_INCLUDED) -#include -#define _PSTDINT_H_INCLUDED -#endif - -#ifndef _PSTDINT_H_INCLUDED -#define _PSTDINT_H_INCLUDED - -#ifndef SIZE_MAX -# define SIZE_MAX (~(size_t)0) -#endif - -/* - * Deduce the type assignments from limits.h under the assumption that - * integer sizes in bits are powers of 2, and follow the ANSI - * definitions. - */ - -#ifndef UINT8_MAX -# define UINT8_MAX 0xff -#endif -#if !defined(uint8_t) && !defined(_UINT8_T) && !defined(vxWorks) -# if (UCHAR_MAX == UINT8_MAX) || defined (S_SPLINT_S) - typedef unsigned char uint8_t; -# define UINT8_C(v) ((uint8_t) v) -# else -# error "Platform not supported" -# endif -#endif - -#ifndef INT8_MAX -# define INT8_MAX 0x7f -#endif -#ifndef INT8_MIN -# define INT8_MIN INT8_C(0x80) -#endif -#if !defined(int8_t) && !defined(_INT8_T) && !defined(vxWorks) -# if (SCHAR_MAX == INT8_MAX) || defined (S_SPLINT_S) - typedef signed char int8_t; -# define INT8_C(v) ((int8_t) v) -# else -# error "Platform not supported" -# endif -#endif - -#ifndef UINT16_MAX -# define UINT16_MAX 0xffff -#endif -#if !defined(uint16_t) && !defined(_UINT16_T) && !defined(vxWorks) -#if (UINT_MAX == UINT16_MAX) || defined (S_SPLINT_S) - typedef unsigned int uint16_t; -# ifndef PRINTF_INT16_MODIFIER -# define PRINTF_INT16_MODIFIER "" -# endif -# define UINT16_C(v) ((uint16_t) (v)) -#elif (USHRT_MAX == UINT16_MAX) - typedef unsigned short uint16_t; -# define UINT16_C(v) ((uint16_t) (v)) -# ifndef PRINTF_INT16_MODIFIER -# define PRINTF_INT16_MODIFIER "h" -# endif -#else -#error "Platform not supported" -#endif -#endif - -#ifndef INT16_MAX -# define INT16_MAX 0x7fff -#endif -#ifndef INT16_MIN -# define INT16_MIN INT16_C(0x8000) -#endif -#if !defined(int16_t) && !defined(_INT16_T) && !defined(vxWorks) -#if (INT_MAX == INT16_MAX) || defined (S_SPLINT_S) - typedef signed int int16_t; -# define INT16_C(v) ((int16_t) (v)) -# ifndef PRINTF_INT16_MODIFIER -# define PRINTF_INT16_MODIFIER "" -# endif -#elif (SHRT_MAX == INT16_MAX) - typedef signed short int16_t; -# define INT16_C(v) ((int16_t) (v)) -# ifndef PRINTF_INT16_MODIFIER -# define PRINTF_INT16_MODIFIER "h" -# endif -#else -#error "Platform not supported" -#endif -#endif - -#ifndef UINT32_MAX -# define UINT32_MAX (0xffffffffUL) -#endif -#if !defined(uint32_t) && !defined(_UINT32_T) && !defined(vxWorks) -#if (ULONG_MAX == UINT32_MAX) || defined (S_SPLINT_S) - typedef unsigned long uint32_t; -# define UINT32_C(v) v ## UL -# ifndef PRINTF_INT32_MODIFIER -# define PRINTF_INT32_MODIFIER "l" -# endif -#elif (UINT_MAX == UINT32_MAX) - typedef unsigned int uint32_t; -# ifndef PRINTF_INT32_MODIFIER -# define PRINTF_INT32_MODIFIER "" -# endif -# define UINT32_C(v) v ## U -#elif (USHRT_MAX == UINT32_MAX) - typedef unsigned short uint32_t; -# define UINT32_C(v) ((unsigned short) (v)) -# ifndef PRINTF_INT32_MODIFIER -# define PRINTF_INT32_MODIFIER "" -# endif -#else -#error "Platform not supported" -#endif -#endif - -#ifndef INT32_MAX -# define INT32_MAX (0x7fffffffL) -#endif -#ifndef INT32_MIN -# define INT32_MIN INT32_C(0x80000000) -#endif -#if !defined(int32_t) && !defined(_INT32_T) && !defined(vxWorks) -#if (LONG_MAX == INT32_MAX) || defined (S_SPLINT_S) - typedef signed long int32_t; -# define INT32_C(v) v ## L -# ifndef PRINTF_INT32_MODIFIER -# define PRINTF_INT32_MODIFIER "l" -# endif -#elif (INT_MAX == INT32_MAX) - typedef signed int int32_t; -# define INT32_C(v) v -# ifndef PRINTF_INT32_MODIFIER -# define PRINTF_INT32_MODIFIER "" -# endif -#elif (SHRT_MAX == INT32_MAX) - typedef signed short int32_t; -# define INT32_C(v) ((short) (v)) -# ifndef PRINTF_INT32_MODIFIER -# define PRINTF_INT32_MODIFIER "" -# endif -#else -#error "Platform not supported" -#endif -#endif - -/* - * The macro stdint_int64_defined is temporarily used to record - * whether or not 64 integer support is available. It must be - * defined for any 64 integer extensions for new platforms that are - * added. - */ - -#undef stdint_int64_defined -#if (defined(__STDC__) && defined(__STDC_VERSION__)) || defined (S_SPLINT_S) -# if (__STDC__ && __STDC_VERSION__ >= 199901L) || defined (S_SPLINT_S) -# define stdint_int64_defined - typedef long long int64_t; - typedef unsigned long long uint64_t; -# define UINT64_C(v) v ## ULL -# define INT64_C(v) v ## LL -# ifndef PRINTF_INT64_MODIFIER -# define PRINTF_INT64_MODIFIER "ll" -# endif -# endif -#endif - -#if !defined (stdint_int64_defined) -# if defined(__GNUC__) && !defined(vxWorks) -# define stdint_int64_defined - __extension__ typedef long long int64_t; - __extension__ typedef unsigned long long uint64_t; -# define UINT64_C(v) v ## ULL -# define INT64_C(v) v ## LL -# ifndef PRINTF_INT64_MODIFIER -# define PRINTF_INT64_MODIFIER "ll" -# endif -# elif defined(__MWERKS__) || defined (__SUNPRO_C) || defined (__SUNPRO_CC) || defined (__APPLE_CC__) || defined (_LONG_LONG) || defined (_CRAYC) || defined (S_SPLINT_S) -# define stdint_int64_defined - typedef long long int64_t; - typedef unsigned long long uint64_t; -# define UINT64_C(v) v ## ULL -# define INT64_C(v) v ## LL -# ifndef PRINTF_INT64_MODIFIER -# define PRINTF_INT64_MODIFIER "ll" -# endif -# elif (defined(__WATCOMC__) && defined(__WATCOM_INT64__)) || (defined(_MSC_VER) && _INTEGRAL_MAX_BITS >= 64) || (defined (__BORLANDC__) && __BORLANDC__ > 0x460) || defined (__alpha) || defined (__DECC) -# define stdint_int64_defined - typedef __int64 int64_t; - typedef unsigned __int64 uint64_t; -# define UINT64_C(v) v ## UI64 -# define INT64_C(v) v ## I64 -# ifndef PRINTF_INT64_MODIFIER -# define PRINTF_INT64_MODIFIER "I64" -# endif -# endif -#endif - -#if !defined (LONG_LONG_MAX) && defined (INT64_C) -# define LONG_LONG_MAX INT64_C (9223372036854775807) -#endif -#ifndef ULONG_LONG_MAX -# define ULONG_LONG_MAX UINT64_C (18446744073709551615) -#endif - -#if !defined (INT64_MAX) && defined (INT64_C) -# define INT64_MAX INT64_C (9223372036854775807) -#endif -#if !defined (INT64_MIN) && defined (INT64_C) -# define INT64_MIN INT64_C (-9223372036854775808) -#endif -#if !defined (UINT64_MAX) && defined (INT64_C) -# define UINT64_MAX UINT64_C (18446744073709551615) -#endif - -/* - * Width of hexadecimal for number field. - */ - -#ifndef PRINTF_INT64_HEX_WIDTH -# define PRINTF_INT64_HEX_WIDTH "16" -#endif -#ifndef PRINTF_INT32_HEX_WIDTH -# define PRINTF_INT32_HEX_WIDTH "8" -#endif -#ifndef PRINTF_INT16_HEX_WIDTH -# define PRINTF_INT16_HEX_WIDTH "4" -#endif -#ifndef PRINTF_INT8_HEX_WIDTH -# define PRINTF_INT8_HEX_WIDTH "2" -#endif -#ifndef PRINTF_INT64_DEC_WIDTH -# define PRINTF_INT64_DEC_WIDTH "19" -#endif -#ifndef PRINTF_INT32_DEC_WIDTH -# define PRINTF_INT32_DEC_WIDTH "10" -#endif -#ifndef PRINTF_INT16_DEC_WIDTH -# define PRINTF_INT16_DEC_WIDTH "5" -#endif -#ifndef PRINTF_INT8_DEC_WIDTH -# define PRINTF_INT8_DEC_WIDTH "3" -#endif -#ifndef PRINTF_UINT64_DEC_WIDTH -# define PRINTF_UINT64_DEC_WIDTH "20" -#endif -#ifndef PRINTF_UINT32_DEC_WIDTH -# define PRINTF_UINT32_DEC_WIDTH "10" -#endif -#ifndef PRINTF_UINT16_DEC_WIDTH -# define PRINTF_UINT16_DEC_WIDTH "5" -#endif -#ifndef PRINTF_UINT8_DEC_WIDTH -# define PRINTF_UINT8_DEC_WIDTH "3" -#endif - -/* - * Ok, lets not worry about 128 bit integers for now. Moore's law says - * we don't need to worry about that until about 2040 at which point - * we'll have bigger things to worry about. - */ - -#ifdef stdint_int64_defined - typedef int64_t intmax_t; - typedef uint64_t uintmax_t; -# define INTMAX_MAX INT64_MAX -# define INTMAX_MIN INT64_MIN -# define UINTMAX_MAX UINT64_MAX -# define UINTMAX_C(v) UINT64_C(v) -# define INTMAX_C(v) INT64_C(v) -# ifndef PRINTF_INTMAX_MODIFIER -# define PRINTF_INTMAX_MODIFIER PRINTF_INT64_MODIFIER -# endif -# ifndef PRINTF_INTMAX_HEX_WIDTH -# define PRINTF_INTMAX_HEX_WIDTH PRINTF_INT64_HEX_WIDTH -# endif -# ifndef PRINTF_INTMAX_DEC_WIDTH -# define PRINTF_INTMAX_DEC_WIDTH PRINTF_INT64_DEC_WIDTH -# endif -#else - typedef int32_t intmax_t; - typedef uint32_t uintmax_t; -# define INTMAX_MAX INT32_MAX -# define UINTMAX_MAX UINT32_MAX -# define UINTMAX_C(v) UINT32_C(v) -# define INTMAX_C(v) INT32_C(v) -# ifndef PRINTF_INTMAX_MODIFIER -# define PRINTF_INTMAX_MODIFIER PRINTF_INT32_MODIFIER -# endif -# ifndef PRINTF_INTMAX_HEX_WIDTH -# define PRINTF_INTMAX_HEX_WIDTH PRINTF_INT32_HEX_WIDTH -# endif -# ifndef PRINTF_INTMAX_DEC_WIDTH -# define PRINTF_INTMAX_DEC_WIDTH PRINTF_INT32_DEC_WIDTH -# endif -#endif - -/* - * Because this file currently only supports platforms which have - * precise powers of 2 as bit sizes for the default integers, the - * least definitions are all trivial. Its possible that a future - * version of this file could have different definitions. - */ - -#ifndef stdint_least_defined - typedef int8_t int_least8_t; - typedef uint8_t uint_least8_t; - typedef int16_t int_least16_t; - typedef uint16_t uint_least16_t; - typedef int32_t int_least32_t; - typedef uint32_t uint_least32_t; -# define PRINTF_LEAST32_MODIFIER PRINTF_INT32_MODIFIER -# define PRINTF_LEAST16_MODIFIER PRINTF_INT16_MODIFIER -# define UINT_LEAST8_MAX UINT8_MAX -# define INT_LEAST8_MAX INT8_MAX -# define UINT_LEAST16_MAX UINT16_MAX -# define INT_LEAST16_MAX INT16_MAX -# define UINT_LEAST32_MAX UINT32_MAX -# define INT_LEAST32_MAX INT32_MAX -# define INT_LEAST8_MIN INT8_MIN -# define INT_LEAST16_MIN INT16_MIN -# define INT_LEAST32_MIN INT32_MIN -# ifdef stdint_int64_defined - typedef int64_t int_least64_t; - typedef uint64_t uint_least64_t; -# define PRINTF_LEAST64_MODIFIER PRINTF_INT64_MODIFIER -# define UINT_LEAST64_MAX UINT64_MAX -# define INT_LEAST64_MAX INT64_MAX -# define INT_LEAST64_MIN INT64_MIN -# endif -#endif -#undef stdint_least_defined - -/* - * The ANSI C committee pretending to know or specify anything about - * performance is the epitome of misguided arrogance. The mandate of - * this file is to *ONLY* ever support that absolute minimum - * definition of the fast integer types, for compatibility purposes. - * No extensions, and no attempt to suggest what may or may not be a - * faster integer type will ever be made in this file. Developers are - * warned to stay away from these types when using this or any other - * stdint.h. - */ - -typedef int_least8_t int_fast8_t; -typedef uint_least8_t uint_fast8_t; -typedef int_least16_t int_fast16_t; -typedef uint_least16_t uint_fast16_t; -typedef int_least32_t int_fast32_t; -typedef uint_least32_t uint_fast32_t; -#define UINT_FAST8_MAX UINT_LEAST8_MAX -#define INT_FAST8_MAX INT_LEAST8_MAX -#define UINT_FAST16_MAX UINT_LEAST16_MAX -#define INT_FAST16_MAX INT_LEAST16_MAX -#define UINT_FAST32_MAX UINT_LEAST32_MAX -#define INT_FAST32_MAX INT_LEAST32_MAX -#define INT_FAST8_MIN INT_LEAST8_MIN -#define INT_FAST16_MIN INT_LEAST16_MIN -#define INT_FAST32_MIN INT_LEAST32_MIN -#ifdef stdint_int64_defined - typedef int_least64_t int_fast64_t; - typedef uint_least64_t uint_fast64_t; -# define UINT_FAST64_MAX UINT_LEAST64_MAX -# define INT_FAST64_MAX INT_LEAST64_MAX -# define INT_FAST64_MIN INT_LEAST64_MIN -#endif - -#undef stdint_int64_defined - -/* - * Whatever piecemeal, per compiler thing we can do about the wchar_t - * type limits. - */ - -#if defined(__WATCOMC__) || defined(_MSC_VER) || defined (__GNUC__) && !defined(vxWorks) -# include -# ifndef WCHAR_MIN -# define WCHAR_MIN 0 -# endif -# ifndef WCHAR_MAX -# define WCHAR_MAX ((wchar_t)-1) -# endif -#endif - -/* - * Whatever piecemeal, per compiler/platform thing we can do about the - * (u)intptr_t types and limits. - */ - -#if (defined (_MSC_VER) && defined (_UINTPTR_T_DEFINED)) || defined (_UINTPTR_T) -# define STDINT_H_UINTPTR_T_DEFINED -#endif - -#ifndef STDINT_H_UINTPTR_T_DEFINED -# if defined (__alpha__) || defined (__ia64__) || defined (__x86_64__) || defined (_WIN64) || defined (__ppc64__) -# define stdint_intptr_bits 64 -# elif defined (__WATCOMC__) || defined (__TURBOC__) -# if defined(__TINY__) || defined(__SMALL__) || defined(__MEDIUM__) -# define stdint_intptr_bits 16 -# else -# define stdint_intptr_bits 32 -# endif -# elif defined (__i386__) || defined (_WIN32) || defined (WIN32) || defined (__ppc64__) -# define stdint_intptr_bits 32 -# elif defined (__INTEL_COMPILER) -/* TODO -- what did Intel do about x86-64? */ -# else -/* #error "This platform might not be supported yet" */ -# endif - -# ifdef stdint_intptr_bits -# define stdint_intptr_glue3_i(a,b,c) a##b##c -# define stdint_intptr_glue3(a,b,c) stdint_intptr_glue3_i(a,b,c) -# ifndef PRINTF_INTPTR_MODIFIER -# define PRINTF_INTPTR_MODIFIER stdint_intptr_glue3(PRINTF_INT,stdint_intptr_bits,_MODIFIER) -# endif -# ifndef PTRDIFF_MAX -# define PTRDIFF_MAX stdint_intptr_glue3(INT,stdint_intptr_bits,_MAX) -# endif -# ifndef PTRDIFF_MIN -# define PTRDIFF_MIN stdint_intptr_glue3(INT,stdint_intptr_bits,_MIN) -# endif -# ifndef UINTPTR_MAX -# define UINTPTR_MAX stdint_intptr_glue3(UINT,stdint_intptr_bits,_MAX) -# endif -# ifndef INTPTR_MAX -# define INTPTR_MAX stdint_intptr_glue3(INT,stdint_intptr_bits,_MAX) -# endif -# ifndef INTPTR_MIN -# define INTPTR_MIN stdint_intptr_glue3(INT,stdint_intptr_bits,_MIN) -# endif -# ifndef INTPTR_C -# define INTPTR_C(x) stdint_intptr_glue3(INT,stdint_intptr_bits,_C)(x) -# endif -# ifndef UINTPTR_C -# define UINTPTR_C(x) stdint_intptr_glue3(UINT,stdint_intptr_bits,_C)(x) -# endif - typedef stdint_intptr_glue3(uint,stdint_intptr_bits,_t) uintptr_t; - typedef stdint_intptr_glue3( int,stdint_intptr_bits,_t) intptr_t; -# else -/* TODO -- This following is likely wrong for some platforms, and does - nothing for the definition of uintptr_t. */ - typedef ptrdiff_t intptr_t; -# endif -# define STDINT_H_UINTPTR_T_DEFINED -#endif - -/* - * Assumes sig_atomic_t is signed and we have a 2s complement machine. - */ - -#ifndef SIG_ATOMIC_MAX -# define SIG_ATOMIC_MAX ((((sig_atomic_t) 1) << (sizeof (sig_atomic_t)*CHAR_BIT-1)) - 1) -#endif - -#endif - -#if defined (__TEST_PSTDINT_FOR_CORRECTNESS) - -/* - * Please compile with the maximum warning settings to make sure macros are - * not defined more than once. - */ - -#include -#include -#include - -#define glue3_aux(x,y,z) x ## y ## z -#define glue3(x,y,z) glue3_aux(x,y,z) - -#define DECLU(bits) glue3(uint,bits,_t) glue3(u,bits,) = glue3(UINT,bits,_C) (0); -#define DECLI(bits) glue3(int,bits,_t) glue3(i,bits,) = glue3(INT,bits,_C) (0); - -#define DECL(us,bits) glue3(DECL,us,) (bits) - -#define TESTUMAX(bits) glue3(u,bits,) = ~glue3(u,bits,); if (glue3(UINT,bits,_MAX) != glue3(u,bits,)) printf ("Something wrong with UINT%d_MAX\n", bits) - -#define REPORTERROR(msg) { err_n++; if (err_first <= 0) err_first = __LINE__; printf msg; } - -int main () { - int err_n = 0; - int err_first = 0; - DECL(I,8) - DECL(U,8) - DECL(I,16) - DECL(U,16) - DECL(I,32) - DECL(U,32) -#ifdef INT64_MAX - DECL(I,64) - DECL(U,64) -#endif - intmax_t imax = INTMAX_C(0); - uintmax_t umax = UINTMAX_C(0); - char str0[256], str1[256]; - - sprintf (str0, "%" PRINTF_INT32_MODIFIER "d", INT32_C(2147483647)); - if (0 != strcmp (str0, "2147483647")) REPORTERROR (("Something wrong with PRINTF_INT32_MODIFIER : %s\n", str0)); - if (atoi(PRINTF_INT32_DEC_WIDTH) != (int) strlen(str0)) REPORTERROR (("Something wrong with PRINTF_INT32_DEC_WIDTH : %s\n", PRINTF_INT32_DEC_WIDTH)); - sprintf (str0, "%" PRINTF_INT32_MODIFIER "u", UINT32_C(4294967295)); - if (0 != strcmp (str0, "4294967295")) REPORTERROR (("Something wrong with PRINTF_INT32_MODIFIER : %s\n", str0)); - if (atoi(PRINTF_UINT32_DEC_WIDTH) != (int) strlen(str0)) REPORTERROR (("Something wrong with PRINTF_UINT32_DEC_WIDTH : %s\n", PRINTF_UINT32_DEC_WIDTH)); -#ifdef INT64_MAX - sprintf (str1, "%" PRINTF_INT64_MODIFIER "d", INT64_C(9223372036854775807)); - if (0 != strcmp (str1, "9223372036854775807")) REPORTERROR (("Something wrong with PRINTF_INT32_MODIFIER : %s\n", str1)); - if (atoi(PRINTF_INT64_DEC_WIDTH) != (int) strlen(str1)) REPORTERROR (("Something wrong with PRINTF_INT64_DEC_WIDTH : %s, %d\n", PRINTF_INT64_DEC_WIDTH, (int) strlen(str1))); - sprintf (str1, "%" PRINTF_INT64_MODIFIER "u", UINT64_C(18446744073709550591)); - if (0 != strcmp (str1, "18446744073709550591")) REPORTERROR (("Something wrong with PRINTF_INT32_MODIFIER : %s\n", str1)); - if (atoi(PRINTF_UINT64_DEC_WIDTH) != (int) strlen(str1)) REPORTERROR (("Something wrong with PRINTF_UINT64_DEC_WIDTH : %s, %d\n", PRINTF_UINT64_DEC_WIDTH, (int) strlen(str1))); -#endif - - sprintf (str0, "%d %x\n", 0, ~0); - - sprintf (str1, "%d %x\n", i8, ~0); - if (0 != strcmp (str0, str1)) REPORTERROR (("Something wrong with i8 : %s\n", str1)); - sprintf (str1, "%u %x\n", u8, ~0); - if (0 != strcmp (str0, str1)) REPORTERROR (("Something wrong with u8 : %s\n", str1)); - sprintf (str1, "%d %x\n", i16, ~0); - if (0 != strcmp (str0, str1)) REPORTERROR (("Something wrong with i16 : %s\n", str1)); - sprintf (str1, "%u %x\n", u16, ~0); - if (0 != strcmp (str0, str1)) REPORTERROR (("Something wrong with u16 : %s\n", str1)); - sprintf (str1, "%" PRINTF_INT32_MODIFIER "d %x\n", i32, ~0); - if (0 != strcmp (str0, str1)) REPORTERROR (("Something wrong with i32 : %s\n", str1)); - sprintf (str1, "%" PRINTF_INT32_MODIFIER "u %x\n", u32, ~0); - if (0 != strcmp (str0, str1)) REPORTERROR (("Something wrong with u32 : %s\n", str1)); -#ifdef INT64_MAX - sprintf (str1, "%" PRINTF_INT64_MODIFIER "d %x\n", i64, ~0); - if (0 != strcmp (str0, str1)) REPORTERROR (("Something wrong with i64 : %s\n", str1)); -#endif - sprintf (str1, "%" PRINTF_INTMAX_MODIFIER "d %x\n", imax, ~0); - if (0 != strcmp (str0, str1)) REPORTERROR (("Something wrong with imax : %s\n", str1)); - sprintf (str1, "%" PRINTF_INTMAX_MODIFIER "u %x\n", umax, ~0); - if (0 != strcmp (str0, str1)) REPORTERROR (("Something wrong with umax : %s\n", str1)); - - TESTUMAX(8); - TESTUMAX(16); - TESTUMAX(32); -#ifdef INT64_MAX - TESTUMAX(64); -#endif - -#define STR(v) #v -#define Q(v) printf ("sizeof " STR(v) " = %u\n", (unsigned) sizeof (v)); - if (err_n) { - printf ("pstdint.h is not correct. Please use sizes below to correct it:\n"); - } - - Q(int) - Q(unsigned) - Q(long int) - Q(short int) - Q(int8_t) - Q(int16_t) - Q(int32_t) -#ifdef INT64_MAX - Q(int64_t) -#endif - - return EXIT_SUCCESS; -} - -#endif diff --git a/tools/ZAPD/lib/assimp/include/assimp/Compiler/pushpack1.h b/tools/ZAPD/lib/assimp/include/assimp/Compiler/pushpack1.h deleted file mode 100644 index 4c9fbb857f..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/Compiler/pushpack1.h +++ /dev/null @@ -1,43 +0,0 @@ - - -// =============================================================================== -// May be included multiple times - sets structure packing to 1 -// for all supported compilers. #include reverts the changes. -// -// Currently this works on the following compilers: -// MSVC 7,8,9 -// GCC -// BORLAND (complains about 'pack state changed but not reverted', but works) -// Clang -// -// -// USAGE: -// -// struct StructToBePacked { -// } PACK_STRUCT; -// -// =============================================================================== - -#ifdef AI_PUSHPACK_IS_DEFINED -# error poppack1.h must be included after pushpack1.h -#endif - -#if defined(_MSC_VER) || defined(__BORLANDC__) || defined (__BCPLUSPLUS__) -# pragma pack(push,1) -# define PACK_STRUCT -#elif defined( __GNUC__ ) || defined(__clang__) -# if !defined(HOST_MINGW) -# define PACK_STRUCT __attribute__((__packed__)) -# else -# define PACK_STRUCT __attribute__((gcc_struct, __packed__)) -# endif -#else -# error Compiler not supported -#endif - -#if defined(_MSC_VER) -// C4103: Packing was changed after the inclusion of the header, probably missing #pragma pop -# pragma warning (disable : 4103) -#endif - -#define AI_PUSHPACK_IS_DEFINED diff --git a/tools/ZAPD/lib/assimp/include/assimp/CreateAnimMesh.h b/tools/ZAPD/lib/assimp/include/assimp/CreateAnimMesh.h deleted file mode 100644 index a60173588f..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/CreateAnimMesh.h +++ /dev/null @@ -1,58 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ - -/** @file CreateAnimMesh.h - * Create AnimMesh from Mesh - */ -#ifndef INCLUDED_AI_CREATE_ANIM_MESH_H -#define INCLUDED_AI_CREATE_ANIM_MESH_H - -#include - -namespace Assimp { - -/** Create aiAnimMesh from aiMesh. */ -ASSIMP_API aiAnimMesh *aiCreateAnimMesh(const aiMesh *mesh); - -} // end of namespace Assimp -#endif // INCLUDED_AI_CREATE_ANIM_MESH_H - diff --git a/tools/ZAPD/lib/assimp/include/assimp/DefaultIOStream.h b/tools/ZAPD/lib/assimp/include/assimp/DefaultIOStream.h deleted file mode 100644 index 994d728ff5..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/DefaultIOStream.h +++ /dev/null @@ -1,140 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ - -/** @file Default file I/O using fXXX()-family of functions */ -#ifndef AI_DEFAULTIOSTREAM_H_INC -#define AI_DEFAULTIOSTREAM_H_INC - -#include -#include -#include -#include - -namespace Assimp { - -// ---------------------------------------------------------------------------------- -//! @class DefaultIOStream -//! @brief Default IO implementation, use standard IO operations -//! @note An instance of this class can exist without a valid file handle -//! attached to it. All calls fail, but the instance can nevertheless be -//! used with no restrictions. -class ASSIMP_API DefaultIOStream : public IOStream -{ - friend class DefaultIOSystem; -#if __ANDROID__ -# if __ANDROID_API__ > 9 -# if defined(AI_CONFIG_ANDROID_JNI_ASSIMP_MANAGER_SUPPORT) - friend class AndroidJNIIOSystem; -# endif // defined(AI_CONFIG_ANDROID_JNI_ASSIMP_MANAGER_SUPPORT) -# endif // __ANDROID_API__ > 9 -#endif // __ANDROID__ - -protected: - DefaultIOStream() AI_NO_EXCEPT; - DefaultIOStream(FILE* pFile, const std::string &strFilename); - -public: - /** Destructor public to allow simple deletion to close the file. */ - ~DefaultIOStream (); - - // ------------------------------------------------------------------- - /// Read from stream - size_t Read(void* pvBuffer, - size_t pSize, - size_t pCount); - - - // ------------------------------------------------------------------- - /// Write to stream - size_t Write(const void* pvBuffer, - size_t pSize, - size_t pCount); - - // ------------------------------------------------------------------- - /// Seek specific position - aiReturn Seek(size_t pOffset, - aiOrigin pOrigin); - - // ------------------------------------------------------------------- - /// Get current seek position - size_t Tell() const; - - // ------------------------------------------------------------------- - /// Get size of file - size_t FileSize() const; - - // ------------------------------------------------------------------- - /// Flush file contents - void Flush(); - -private: - // File data-structure, using clib - FILE* mFile; - // Filename - std::string mFilename; - // Cached file size - mutable size_t mCachedSize; -}; - -// ---------------------------------------------------------------------------------- -inline -DefaultIOStream::DefaultIOStream() AI_NO_EXCEPT -: mFile(nullptr) -, mFilename("") -, mCachedSize(SIZE_MAX) { - // empty -} - -// ---------------------------------------------------------------------------------- -inline -DefaultIOStream::DefaultIOStream (FILE* pFile, const std::string &strFilename) -: mFile(pFile) -, mFilename(strFilename) -, mCachedSize(SIZE_MAX) { - // empty -} -// ---------------------------------------------------------------------------------- - -} // ns assimp - -#endif //!!AI_DEFAULTIOSTREAM_H_INC - diff --git a/tools/ZAPD/lib/assimp/include/assimp/DefaultIOSystem.h b/tools/ZAPD/lib/assimp/include/assimp/DefaultIOSystem.h deleted file mode 100644 index 2dd5c801b5..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/DefaultIOSystem.h +++ /dev/null @@ -1,93 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ - -/** @file Default implementation of IOSystem using the standard C file functions */ -#ifndef AI_DEFAULTIOSYSTEM_H_INC -#define AI_DEFAULTIOSYSTEM_H_INC - -#include - -namespace Assimp { - -// --------------------------------------------------------------------------- -/** Default implementation of IOSystem using the standard C file functions */ -class ASSIMP_API DefaultIOSystem : public IOSystem { -public: - // ------------------------------------------------------------------- - /** Tests for the existence of a file at the given path. */ - bool Exists( const char* pFile) const; - - // ------------------------------------------------------------------- - /** Returns the directory separator. */ - char getOsSeparator() const; - - // ------------------------------------------------------------------- - /** Open a new file with a given path. */ - IOStream* Open( const char* pFile, const char* pMode = "rb"); - - // ------------------------------------------------------------------- - /** Closes the given file and releases all resources associated with it. */ - void Close( IOStream* pFile); - - // ------------------------------------------------------------------- - /** Compare two paths */ - bool ComparePaths (const char* one, const char* second) const; - - /** @brief get the file name of a full filepath - * example: /tmp/archive.tar.gz -> archive.tar.gz - */ - static std::string fileName( const std::string &path ); - - /** @brief get the complete base name of a full filepath - * example: /tmp/archive.tar.gz -> archive.tar - */ - static std::string completeBaseName( const std::string &path); - - /** @brief get the path of a full filepath - * example: /tmp/archive.tar.gz -> /tmp/ - */ - static std::string absolutePath( const std::string &path); -}; - -} //!ns Assimp - -#endif //AI_DEFAULTIOSYSTEM_H_INC diff --git a/tools/ZAPD/lib/assimp/include/assimp/DefaultLogger.hpp b/tools/ZAPD/lib/assimp/include/assimp/DefaultLogger.hpp deleted file mode 100644 index 1946e250a6..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/DefaultLogger.hpp +++ /dev/null @@ -1,188 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ -/** @file DefaultLogger.hpp -*/ - -#ifndef INCLUDED_AI_DEFAULTLOGGER -#define INCLUDED_AI_DEFAULTLOGGER - -#include "Logger.hpp" -#include "LogStream.hpp" -#include "NullLogger.hpp" -#include - -namespace Assimp { -// ------------------------------------------------------------------------------------ -class IOStream; -struct LogStreamInfo; - -/** default name of logfile */ -#define ASSIMP_DEFAULT_LOG_NAME "AssimpLog.txt" - -// ------------------------------------------------------------------------------------ -/** @brief CPP-API: Primary logging facility of Assimp. - * - * The library stores its primary #Logger as a static member of this class. - * #get() returns this primary logger. By default the underlying implementation is - * just a #NullLogger which rejects all log messages. By calling #create(), logging - * is turned on. To capture the log output multiple log streams (#LogStream) can be - * attach to the logger. Some default streams for common streaming locations (such as - * a file, std::cout, OutputDebugString()) are also provided. - * - * If you wish to customize the logging at an even deeper level supply your own - * implementation of #Logger to #set(). - * @note The whole logging stuff causes a small extra overhead for all imports. */ -class ASSIMP_API DefaultLogger : - public Logger { - -public: - - // ---------------------------------------------------------------------- - /** @brief Creates a logging instance. - * @param name Name for log file. Only valid in combination - * with the aiDefaultLogStream_FILE flag. - * @param severity Log severity, VERBOSE turns on debug messages - * @param defStreams Default log streams to be attached. Any bitwise - * combination of the aiDefaultLogStream enumerated values. - * If #aiDefaultLogStream_FILE is specified but an empty string is - * passed for 'name', no log file is created at all. - * @param io IOSystem to be used to open external files (such as the - * log file). Pass NULL to rely on the default implementation. - * This replaces the default #NullLogger with a #DefaultLogger instance. */ - static Logger *create(const char* name = ASSIMP_DEFAULT_LOG_NAME, - LogSeverity severity = NORMAL, - unsigned int defStreams = aiDefaultLogStream_DEBUGGER | aiDefaultLogStream_FILE, - IOSystem* io = NULL); - - // ---------------------------------------------------------------------- - /** @brief Setup a custom #Logger implementation. - * - * Use this if the provided #DefaultLogger class doesn't fit into - * your needs. If the provided message formatting is OK for you, - * it's much easier to use #create() and to attach your own custom - * output streams to it. - * @param logger Pass NULL to setup a default NullLogger*/ - static void set (Logger *logger); - - // ---------------------------------------------------------------------- - /** @brief Getter for singleton instance - * @return Only instance. This is never null, but it could be a - * NullLogger. Use isNullLogger to check this.*/ - static Logger *get(); - - // ---------------------------------------------------------------------- - /** @brief Return whether a #NullLogger is currently active - * @return true if the current logger is a #NullLogger. - * Use create() or set() to setup a logger that does actually do - * something else than just rejecting all log messages. */ - static bool isNullLogger(); - - // ---------------------------------------------------------------------- - /** @brief Kills the current singleton logger and replaces it with a - * #NullLogger instance. */ - static void kill(); - - // ---------------------------------------------------------------------- - /** @copydoc Logger::attachStream */ - bool attachStream(LogStream *pStream, - unsigned int severity); - - // ---------------------------------------------------------------------- - /** @copydoc Logger::detatchStream */ - bool detatchStream(LogStream *pStream, - unsigned int severity); - -private: - // ---------------------------------------------------------------------- - /** @briefPrivate construction for internal use by create(). - * @param severity Logging granularity */ - explicit DefaultLogger(LogSeverity severity); - - // ---------------------------------------------------------------------- - /** @briefDestructor */ - ~DefaultLogger(); - - /** @brief Logs debug infos, only been written when severity level VERBOSE is set */ - void OnDebug(const char* message); - - /** @brief Logs an info message */ - void OnInfo(const char* message); - - /** @brief Logs a warning message */ - void OnWarn(const char* message); - - /** @brief Logs an error message */ - void OnError(const char* message); - - // ---------------------------------------------------------------------- - /** @brief Writes a message to all streams */ - void WriteToStreams(const char* message, ErrorSeverity ErrorSev ); - - // ---------------------------------------------------------------------- - /** @brief Returns the thread id. - * @note This is an OS specific feature, if not supported, a - * zero will be returned. - */ - unsigned int GetThreadID(); - -private: - // Aliases for stream container - typedef std::vector StreamArray; - typedef std::vector::iterator StreamIt; - typedef std::vector::const_iterator ConstStreamIt; - - //! only logging instance - static Logger *m_pLogger; - static NullLogger s_pNullLogger; - - //! Attached streams - StreamArray m_StreamArray; - - bool noRepeatMsg; - char lastMsg[MAX_LOG_MESSAGE_LENGTH*2]; - size_t lastLen; -}; -// ------------------------------------------------------------------------------------ - -} // Namespace Assimp - -#endif // !! INCLUDED_AI_DEFAULTLOGGER diff --git a/tools/ZAPD/lib/assimp/include/assimp/Defines.h b/tools/ZAPD/lib/assimp/include/assimp/Defines.h deleted file mode 100644 index 15e1d83c26..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/Defines.h +++ /dev/null @@ -1,49 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2012, assimp team -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ - -// We need those constants, workaround for any platforms where nobody defined them yet -#if (!defined SIZE_MAX) -# define SIZE_MAX (~((size_t)0)) -#endif - -#if (!defined UINT_MAX) -# define UINT_MAX (~((unsigned int)0)) -#endif - diff --git a/tools/ZAPD/lib/assimp/include/assimp/Exceptional.h b/tools/ZAPD/lib/assimp/include/assimp/Exceptional.h deleted file mode 100644 index 5109b8f077..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/Exceptional.h +++ /dev/null @@ -1,125 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2008, assimp team -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ - -#ifndef INCLUDED_EXCEPTIONAL_H -#define INCLUDED_EXCEPTIONAL_H - -#include -#include -using std::runtime_error; - -#ifdef _MSC_VER -# pragma warning(disable : 4275) -#endif - -// --------------------------------------------------------------------------- -/** FOR IMPORTER PLUGINS ONLY: Simple exception class to be thrown if an - * unrecoverable error occurs while importing. Loading APIs return - * NULL instead of a valid aiScene then. */ -class DeadlyImportError - : public runtime_error -{ -public: - /** Constructor with arguments */ - explicit DeadlyImportError( const std::string& errorText) - : runtime_error(errorText) - { - } - -private: -}; - -typedef DeadlyImportError DeadlyExportError; - -#ifdef _MSC_VER -# pragma warning(default : 4275) -#endif - -// --------------------------------------------------------------------------- -template -struct ExceptionSwallower { - T operator ()() const { - return T(); - } -}; - -// --------------------------------------------------------------------------- -template -struct ExceptionSwallower { - T* operator ()() const { - return NULL; - } -}; - -// --------------------------------------------------------------------------- -template <> -struct ExceptionSwallower { - aiReturn operator ()() const { - try { - throw; - } - catch (std::bad_alloc&) { - return aiReturn_OUTOFMEMORY; - } - catch (...) { - return aiReturn_FAILURE; - } - } -}; - -// --------------------------------------------------------------------------- -template <> -struct ExceptionSwallower { - void operator ()() const { - return; - } -}; - -#define ASSIMP_BEGIN_EXCEPTION_REGION()\ -{\ - try { - -#define ASSIMP_END_EXCEPTION_REGION(type)\ - } catch(...) {\ - return ExceptionSwallower()();\ - }\ -} - -#endif // INCLUDED_EXCEPTIONAL_H diff --git a/tools/ZAPD/lib/assimp/include/assimp/Exporter.hpp b/tools/ZAPD/lib/assimp/include/assimp/Exporter.hpp deleted file mode 100644 index ea0303e804..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/Exporter.hpp +++ /dev/null @@ -1,505 +0,0 @@ -/* ---------------------------------------------------------------------------- -Open Asset Import Library (assimp) ---------------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the following -conditions are met: - -* Redistributions of source code must retain the above -copyright notice, this list of conditions and the -following disclaimer. - -* Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the -following disclaimer in the documentation and/or other -materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its -contributors may be used to endorse or promote products -derived from this software without specific prior -written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------- -*/ - -/** @file Exporter.hpp -* @brief Defines the CPP-API for the Assimp export interface -*/ -#pragma once -#ifndef AI_EXPORT_HPP_INC -#define AI_EXPORT_HPP_INC - -#ifndef ASSIMP_BUILD_NO_EXPORT - -#include "cexport.h" -#include - -namespace Assimp { - -class ExporterPimpl; -class IOSystem; -class ProgressHandler; - -// ---------------------------------------------------------------------------------- -/** CPP-API: The Exporter class forms an C++ interface to the export functionality - * of the Open Asset Import Library. Note that the export interface is available - * only if Assimp has been built with ASSIMP_BUILD_NO_EXPORT not defined. - * - * The interface is modeled after the importer interface and mostly - * symmetric. The same rules for threading etc. apply. - * - * In a nutshell, there are two export interfaces: #Export, which writes the - * output file(s) either to the regular file system or to a user-supplied - * #IOSystem, and #ExportToBlob which returns a linked list of memory - * buffers (blob), each referring to one output file (in most cases - * there will be only one output file of course, but this extra complexity is - * needed since Assimp aims at supporting a wide range of file formats). - * - * #ExportToBlob is especially useful if you intend to work - * with the data in-memory. -*/ -class ASSIMP_API ExportProperties; - -class ASSIMP_API Exporter { -public: - /** Function pointer type of a Export worker function */ - typedef void (*fpExportFunc)(const char*, IOSystem*, const aiScene*, const ExportProperties*); - - /** Internal description of an Assimp export format option */ - struct ExportFormatEntry { - /// Public description structure to be returned by aiGetExportFormatDescription() - aiExportFormatDesc mDescription; - - // Worker function to do the actual exporting - fpExportFunc mExportFunction; - - // Post-processing steps to be executed PRIOR to invoking mExportFunction - unsigned int mEnforcePP; - - // Constructor to fill all entries - ExportFormatEntry( const char* pId, const char* pDesc, const char* pExtension, fpExportFunc pFunction, unsigned int pEnforcePP = 0u) - { - mDescription.id = pId; - mDescription.description = pDesc; - mDescription.fileExtension = pExtension; - mExportFunction = pFunction; - mEnforcePP = pEnforcePP; - } - - ExportFormatEntry() : - mExportFunction() - , mEnforcePP() - { - mDescription.id = NULL; - mDescription.description = NULL; - mDescription.fileExtension = NULL; - } - }; - - /** - * @brief The class constructor. - */ - Exporter(); - - /** - * @brief The class destructor. - */ - ~Exporter(); - - // ------------------------------------------------------------------- - /** Supplies a custom IO handler to the exporter to use to open and - * access files. - * - * If you need #Export to use custom IO logic to access the files, - * you need to supply a custom implementation of IOSystem and - * IOFile to the exporter. - * - * #Exporter takes ownership of the object and will destroy it - * afterwards. The previously assigned handler will be deleted. - * Pass NULL to take again ownership of your IOSystem and reset Assimp - * to use its default implementation, which uses plain file IO. - * - * @param pIOHandler The IO handler to be used in all file accesses - * of the Importer. */ - void SetIOHandler( IOSystem* pIOHandler); - - // ------------------------------------------------------------------- - /** Retrieves the IO handler that is currently set. - * You can use #IsDefaultIOHandler() to check whether the returned - * interface is the default IO handler provided by ASSIMP. The default - * handler is active as long the application doesn't supply its own - * custom IO handler via #SetIOHandler(). - * @return A valid IOSystem interface, never NULL. */ - IOSystem* GetIOHandler() const; - - // ------------------------------------------------------------------- - /** Checks whether a default IO handler is active - * A default handler is active as long the application doesn't - * supply its own custom IO handler via #SetIOHandler(). - * @return true by default */ - bool IsDefaultIOHandler() const; - - // ------------------------------------------------------------------- - /** Supplies a custom progress handler to the exporter. This - * interface exposes an #Update() callback, which is called - * more or less periodically (please don't sue us if it - * isn't as periodically as you'd like it to have ...). - * This can be used to implement progress bars and loading - * timeouts. - * @param pHandler Progress callback interface. Pass nullptr to - * disable progress reporting. - * @note Progress handlers can be used to abort the loading - * at almost any time.*/ - void SetProgressHandler(ProgressHandler* pHandler); - - // ------------------------------------------------------------------- - /** Exports the given scene to a chosen file format. Returns the exported - * data as a binary blob which you can write into a file or something. - * When you're done with the data, simply let the #Exporter instance go - * out of scope to have it released automatically. - * @param pScene The scene to export. Stays in possession of the caller, - * is not changed by the function. - * @param pFormatId ID string to specify to which format you want to - * export to. Use - * #GetExportFormatCount / #GetExportFormatDescription to learn which - * export formats are available. - * @param pPreprocessing See the documentation for #Export - * @return the exported data or NULL in case of error. - * @note If the Exporter instance did already hold a blob from - * a previous call to #ExportToBlob, it will be disposed. - * Any IO handlers set via #SetIOHandler are ignored here. - * @note Use aiCopyScene() to get a modifiable copy of a previously - * imported scene. */ - const aiExportDataBlob* ExportToBlob(const aiScene* pScene, const char* pFormatId, - unsigned int pPreprocessing = 0u, const ExportProperties* pProperties = nullptr); - const aiExportDataBlob* ExportToBlob( const aiScene* pScene, const std::string& pFormatId, - unsigned int pPreprocessing = 0u, const ExportProperties* pProperties = nullptr); - - // ------------------------------------------------------------------- - /** Convenience function to export directly to a file. Use - * #SetIOSystem to supply a custom IOSystem to gain fine-grained control - * about the output data flow of the export process. - * @param pBlob A data blob obtained from a previous call to #aiExportScene. Must not be NULL. - * @param pPath Full target file name. Target must be accessible. - * @param pPreprocessing Accepts any choice of the #aiPostProcessSteps enumerated - * flags, but in reality only a subset of them makes sense here. Specifying - * 'preprocessing' flags is useful if the input scene does not conform to - * Assimp's default conventions as specified in the @link data Data Structures Page @endlink. - * In short, this means the geometry data should use a right-handed coordinate systems, face - * winding should be counter-clockwise and the UV coordinate origin is assumed to be in - * the upper left. The #aiProcess_MakeLeftHanded, #aiProcess_FlipUVs and - * #aiProcess_FlipWindingOrder flags are used in the import side to allow users - * to have those defaults automatically adapted to their conventions. Specifying those flags - * for exporting has the opposite effect, respectively. Some other of the - * #aiPostProcessSteps enumerated values may be useful as well, but you'll need - * to try out what their effect on the exported file is. Many formats impose - * their own restrictions on the structure of the geometry stored therein, - * so some preprocessing may have little or no effect at all, or may be - * redundant as exporters would apply them anyhow. A good example - * is triangulation - whilst you can enforce it by specifying - * the #aiProcess_Triangulate flag, most export formats support only - * triangulate data so they would run the step even if it wasn't requested. - * - * If assimp detects that the input scene was directly taken from the importer side of - * the library (i.e. not copied using aiCopyScene and potentially modified afterwards), - * any post-processing steps already applied to the scene will not be applied again, unless - * they show non-idempotent behavior (#aiProcess_MakeLeftHanded, #aiProcess_FlipUVs and - * #aiProcess_FlipWindingOrder). - * @return AI_SUCCESS if everything was fine. - * @note Use aiCopyScene() to get a modifiable copy of a previously - * imported scene.*/ - aiReturn Export( const aiScene* pScene, const char* pFormatId, const char* pPath, - unsigned int pPreprocessing = 0u, const ExportProperties* pProperties = nullptr); - aiReturn Export( const aiScene* pScene, const std::string& pFormatId, const std::string& pPath, - unsigned int pPreprocessing = 0u, const ExportProperties* pProperties = nullptr); - - // ------------------------------------------------------------------- - /** Returns an error description of an error that occurred in #Export - * or #ExportToBlob - * - * Returns an empty string if no error occurred. - * @return A description of the last error, an empty string if no - * error occurred. The string is never NULL. - * - * @note The returned function remains valid until one of the - * following methods is called: #Export, #ExportToBlob, #FreeBlob */ - const char* GetErrorString() const; - - // ------------------------------------------------------------------- - /** Return the blob obtained from the last call to #ExportToBlob */ - const aiExportDataBlob* GetBlob() const; - - // ------------------------------------------------------------------- - /** Orphan the blob from the last call to #ExportToBlob. This means - * the caller takes ownership and is thus responsible for calling - * the C API function #aiReleaseExportBlob to release it. */ - const aiExportDataBlob* GetOrphanedBlob() const; - - // ------------------------------------------------------------------- - /** Frees the current blob. - * - * The function does nothing if no blob has previously been - * previously produced via #ExportToBlob. #FreeBlob is called - * automatically by the destructor. The only reason to call - * it manually would be to reclaim as much storage as possible - * without giving up the #Exporter instance yet. */ - void FreeBlob( ); - - // ------------------------------------------------------------------- - /** Returns the number of export file formats available in the current - * Assimp build. Use #Exporter::GetExportFormatDescription to - * retrieve infos of a specific export format. - * - * This includes built-in exporters as well as exporters registered - * using #RegisterExporter. - **/ - size_t GetExportFormatCount() const; - - // ------------------------------------------------------------------- - /** Returns a description of the nth export file format. Use # - * #Exporter::GetExportFormatCount to learn how many export - * formats are supported. - * - * The returned pointer is of static storage duration if the - * pIndex pertains to a built-in exporter (i.e. one not registered - * via #RegistrerExporter). It is restricted to the life-time of the - * #Exporter instance otherwise. - * - * @param pIndex Index of the export format to retrieve information - * for. Valid range is 0 to #Exporter::GetExportFormatCount - * @return A description of that specific export format. - * NULL if pIndex is out of range. */ - const aiExportFormatDesc* GetExportFormatDescription( size_t pIndex ) const; - - // ------------------------------------------------------------------- - /** Register a custom exporter. Custom export formats are limited to - * to the current #Exporter instance and do not affect the - * library globally. The indexes under which the format's - * export format description can be queried are assigned - * monotonously. - * @param desc Exporter description. - * @return aiReturn_SUCCESS if the export format was successfully - * registered. A common cause that would prevent an exporter - * from being registered is that its format id is already - * occupied by another format. */ - aiReturn RegisterExporter(const ExportFormatEntry& desc); - - // ------------------------------------------------------------------- - /** Remove an export format previously registered with #RegisterExporter - * from the #Exporter instance (this can also be used to drop - * built-in exporters because those are implicitly registered - * using #RegisterExporter). - * @param id Format id to be unregistered, this refers to the - * 'id' field of #aiExportFormatDesc. - * @note Calling this method on a format description not yet registered - * has no effect.*/ - void UnregisterExporter(const char* id); - -protected: - // Just because we don't want you to know how we're hacking around. - ExporterPimpl* pimpl; -}; - -class ASSIMP_API ExportProperties { -public: - // Data type to store the key hash - typedef unsigned int KeyType; - - // typedefs for our four configuration maps. - // We don't need more, so there is no need for a generic solution - typedef std::map IntPropertyMap; - typedef std::map FloatPropertyMap; - typedef std::map StringPropertyMap; - typedef std::map MatrixPropertyMap; - -public: - /** Standard constructor - * @see ExportProperties() - */ - ExportProperties(); - - // ------------------------------------------------------------------- - /** Copy constructor. - * - * This copies the configuration properties of another ExportProperties. - * @see ExportProperties(const ExportProperties& other) - */ - ExportProperties(const ExportProperties& other); - - // ------------------------------------------------------------------- - /** Set an integer configuration property. - * @param szName Name of the property. All supported properties - * are defined in the aiConfig.g header (all constants share the - * prefix AI_CONFIG_XXX and are simple strings). - * @param iValue New value of the property - * @return true if the property was set before. The new value replaces - * the previous value in this case. - * @note Property of different types (float, int, string ..) are kept - * on different stacks, so calling SetPropertyInteger() for a - * floating-point property has no effect - the loader will call - * GetPropertyFloat() to read the property, but it won't be there. - */ - bool SetPropertyInteger(const char* szName, int iValue); - - // ------------------------------------------------------------------- - /** Set a boolean configuration property. Boolean properties - * are stored on the integer stack internally so it's possible - * to set them via #SetPropertyBool and query them with - * #GetPropertyBool and vice versa. - * @see SetPropertyInteger() - */ - bool SetPropertyBool(const char* szName, bool value) { - return SetPropertyInteger(szName,value); - } - - // ------------------------------------------------------------------- - /** Set a floating-point configuration property. - * @see SetPropertyInteger() - */ - bool SetPropertyFloat(const char* szName, ai_real fValue); - - // ------------------------------------------------------------------- - /** Set a string configuration property. - * @see SetPropertyInteger() - */ - bool SetPropertyString(const char* szName, const std::string& sValue); - - // ------------------------------------------------------------------- - /** Set a matrix configuration property. - * @see SetPropertyInteger() - */ - bool SetPropertyMatrix(const char* szName, const aiMatrix4x4& sValue); - - // ------------------------------------------------------------------- - /** Get a configuration property. - * @param szName Name of the property. All supported properties - * are defined in the aiConfig.g header (all constants share the - * prefix AI_CONFIG_XXX). - * @param iErrorReturn Value that is returned if the property - * is not found. - * @return Current value of the property - * @note Property of different types (float, int, string ..) are kept - * on different lists, so calling SetPropertyInteger() for a - * floating-point property has no effect - the loader will call - * GetPropertyFloat() to read the property, but it won't be there. - */ - int GetPropertyInteger(const char* szName, - int iErrorReturn = 0xffffffff) const; - - // ------------------------------------------------------------------- - /** Get a boolean configuration property. Boolean properties - * are stored on the integer stack internally so it's possible - * to set them via #SetPropertyBool and query them with - * #GetPropertyBool and vice versa. - * @see GetPropertyInteger() - */ - bool GetPropertyBool(const char* szName, bool bErrorReturn = false) const { - return GetPropertyInteger(szName,bErrorReturn)!=0; - } - - // ------------------------------------------------------------------- - /** Get a floating-point configuration property - * @see GetPropertyInteger() - */ - ai_real GetPropertyFloat(const char* szName, - ai_real fErrorReturn = 10e10f) const; - - // ------------------------------------------------------------------- - /** Get a string configuration property - * - * The return value remains valid until the property is modified. - * @see GetPropertyInteger() - */ - const std::string GetPropertyString(const char* szName, - const std::string& sErrorReturn = "") const; - - // ------------------------------------------------------------------- - /** Get a matrix configuration property - * - * The return value remains valid until the property is modified. - * @see GetPropertyInteger() - */ - const aiMatrix4x4 GetPropertyMatrix(const char* szName, - const aiMatrix4x4& sErrorReturn = aiMatrix4x4()) const; - - // ------------------------------------------------------------------- - /** Determine a integer configuration property has been set. - * @see HasPropertyInteger() - */ - bool HasPropertyInteger(const char* szName) const; - - /** Determine a boolean configuration property has been set. - * @see HasPropertyBool() - */ - bool HasPropertyBool(const char* szName) const; - - /** Determine a boolean configuration property has been set. - * @see HasPropertyFloat() - */ - bool HasPropertyFloat(const char* szName) const; - - /** Determine a String configuration property has been set. - * @see HasPropertyString() - */ - bool HasPropertyString(const char* szName) const; - - /** Determine a Matrix configuration property has been set. - * @see HasPropertyMatrix() - */ - bool HasPropertyMatrix(const char* szName) const; - -protected: - - /** List of integer properties */ - IntPropertyMap mIntProperties; - - /** List of floating-point properties */ - FloatPropertyMap mFloatProperties; - - /** List of string properties */ - StringPropertyMap mStringProperties; - - /** List of Matrix properties */ - MatrixPropertyMap mMatrixProperties; -}; - -// ---------------------------------------------------------------------------------- -inline -const aiExportDataBlob* Exporter::ExportToBlob( const aiScene* pScene, const std::string& pFormatId, - unsigned int pPreprocessing, const ExportProperties* pProperties) -{ - return ExportToBlob(pScene,pFormatId.c_str(),pPreprocessing, pProperties); -} - -// ---------------------------------------------------------------------------------- -inline -aiReturn Exporter :: Export( const aiScene* pScene, const std::string& pFormatId, - const std::string& pPath, unsigned int pPreprocessing, - const ExportProperties* pProperties) -{ - return Export(pScene,pFormatId.c_str(),pPath.c_str(),pPreprocessing, pProperties); -} - -} // namespace Assimp - -#endif // ASSIMP_BUILD_NO_EXPORT -#endif // AI_EXPORT_HPP_INC diff --git a/tools/ZAPD/lib/assimp/include/assimp/GenericProperty.h b/tools/ZAPD/lib/assimp/include/assimp/GenericProperty.h deleted file mode 100644 index 183ecd5197..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/GenericProperty.h +++ /dev/null @@ -1,133 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ - -#ifndef AI_GENERIC_PROPERTY_H_INCLUDED -#define AI_GENERIC_PROPERTY_H_INCLUDED - -#include -#include -#include "Hash.h" - -#include - -// ------------------------------------------------------------------------------------------------ -template -inline -bool SetGenericProperty(std::map< unsigned int, T >& list, - const char* szName, const T& value) { - ai_assert(nullptr != szName); - const uint32_t hash = SuperFastHash(szName); - - typename std::map::iterator it = list.find(hash); - if (it == list.end()) { - list.insert(std::pair( hash, value )); - return false; - } - (*it).second = value; - - return true; -} - -// ------------------------------------------------------------------------------------------------ -template -inline -const T& GetGenericProperty(const std::map< unsigned int, T >& list, - const char* szName, const T& errorReturn) { - ai_assert(nullptr != szName); - const uint32_t hash = SuperFastHash(szName); - - typename std::map::const_iterator it = list.find(hash); - if (it == list.end()) { - return errorReturn; - } - - return (*it).second; -} - -// ------------------------------------------------------------------------------------------------ -// Special version for pointer types - they will be deleted when replaced with another value -// passing NULL removes the whole property -template -inline -void SetGenericPropertyPtr(std::map< unsigned int, T* >& list, - const char* szName, T* value, bool* bWasExisting = nullptr ) { - ai_assert(nullptr != szName); - const uint32_t hash = SuperFastHash(szName); - - typename std::map::iterator it = list.find(hash); - if (it == list.end()) { - if (bWasExisting) { - *bWasExisting = false; - } - - list.insert(std::pair( hash, value )); - return; - } - if ((*it).second != value) { - delete (*it).second; - (*it).second = value; - } - if (!value) { - list.erase(it); - } - if (bWasExisting) { - *bWasExisting = true; - } -} - -// ------------------------------------------------------------------------------------------------ -template -inline -bool HasGenericProperty(const std::map< unsigned int, T >& list, - const char* szName) { - ai_assert(nullptr != szName); - const uint32_t hash = SuperFastHash(szName); - - typename std::map::const_iterator it = list.find(hash); - if (it == list.end()) { - return false; - } - - return true; -} - -#endif // !! AI_GENERIC_PROPERTY_H_INCLUDED diff --git a/tools/ZAPD/lib/assimp/include/assimp/Hash.h b/tools/ZAPD/lib/assimp/include/assimp/Hash.h deleted file mode 100644 index 30657be198..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/Hash.h +++ /dev/null @@ -1,118 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ - -#ifndef AI_HASH_H_INCLUDED -#define AI_HASH_H_INCLUDED - -#include -#include - -// ------------------------------------------------------------------------------------------------ -// Hashing function taken from -// http://www.azillionmonkeys.com/qed/hash.html -// (incremental version) -// -// This code is Copyright 2004-2008 by Paul Hsieh. It is used here in the belief that -// Assimp's license is considered compatible with Pauls's derivative license as specified -// on his web page. -// -// (stdint.h should have been been included here) -// ------------------------------------------------------------------------------------------------ -#undef get16bits -#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \ - || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__) -#define get16bits(d) (*((const uint16_t *) (d))) -#endif - -#if !defined (get16bits) -#define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)\ - +(uint32_t)(((const uint8_t *)(d))[0]) ) -#endif - -// ------------------------------------------------------------------------------------------------ -inline uint32_t SuperFastHash (const char * data, uint32_t len = 0, uint32_t hash = 0) { -uint32_t tmp; -int rem; - - if (!data) return 0; - if (!len)len = (uint32_t)::strlen(data); - - rem = len & 3; - len >>= 2; - - /* Main loop */ - for (;len > 0; len--) { - hash += get16bits (data); - tmp = (get16bits (data+2) << 11) ^ hash; - hash = (hash << 16) ^ tmp; - data += 2*sizeof (uint16_t); - hash += hash >> 11; - } - - /* Handle end cases */ - switch (rem) { - case 3: hash += get16bits (data); - hash ^= hash << 16; - hash ^= data[sizeof (uint16_t)] << 18; - hash += hash >> 11; - break; - case 2: hash += get16bits (data); - hash ^= hash << 11; - hash += hash >> 17; - break; - case 1: hash += *data; - hash ^= hash << 10; - hash += hash >> 1; - } - - /* Force "avalanching" of final 127 bits */ - hash ^= hash << 3; - hash += hash >> 5; - hash ^= hash << 4; - hash += hash >> 17; - hash ^= hash << 25; - hash += hash >> 6; - - return hash; -} - -#endif // !! AI_HASH_H_INCLUDED diff --git a/tools/ZAPD/lib/assimp/include/assimp/IOStream.hpp b/tools/ZAPD/lib/assimp/include/assimp/IOStream.hpp deleted file mode 100644 index 0623d0f70b..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/IOStream.hpp +++ /dev/null @@ -1,142 +0,0 @@ -/* ---------------------------------------------------------------------------- -Open Asset Import Library (assimp) ---------------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the following -conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------- -*/ -/** @file IOStream.hpp - * @brief File I/O wrappers for C++. - */ - -#pragma once -#ifndef AI_IOSTREAM_H_INC -#define AI_IOSTREAM_H_INC - -#include "types.h" - -#ifndef __cplusplus -# error This header requires C++ to be used. aiFileIO.h is the \ - corresponding C interface. -#endif - -namespace Assimp { - -// ---------------------------------------------------------------------------------- -/** @brief CPP-API: Class to handle file I/O for C++ - * - * Derive an own implementation from this interface to provide custom IO handling - * to the Importer. If you implement this interface, be sure to also provide an - * implementation for IOSystem that creates instances of your custom IO class. -*/ -class ASSIMP_API IOStream -#ifndef SWIG - : public Intern::AllocateFromAssimpHeap -#endif -{ -protected: - /** Constructor protected, use IOSystem::Open() to create an instance. */ - IOStream() AI_NO_EXCEPT; - -public: - // ------------------------------------------------------------------- - /** @brief Destructor. Deleting the object closes the underlying file, - * alternatively you may use IOSystem::Close() to release the file. - */ - virtual ~IOStream(); - - // ------------------------------------------------------------------- - /** @brief Read from the file - * - * See fread() for more details - * This fails for write-only files */ - virtual size_t Read(void* pvBuffer, - size_t pSize, - size_t pCount) = 0; - - // ------------------------------------------------------------------- - /** @brief Write to the file - * - * See fwrite() for more details - * This fails for read-only files */ - virtual size_t Write(const void* pvBuffer, - size_t pSize, - size_t pCount) = 0; - - // ------------------------------------------------------------------- - /** @brief Set the read/write cursor of the file - * - * Note that the offset is _negative_ for aiOrigin_END. - * See fseek() for more details */ - virtual aiReturn Seek(size_t pOffset, - aiOrigin pOrigin) = 0; - - // ------------------------------------------------------------------- - /** @brief Get the current position of the read/write cursor - * - * See ftell() for more details */ - virtual size_t Tell() const = 0; - - // ------------------------------------------------------------------- - /** @brief Returns filesize - * Returns the filesize. */ - virtual size_t FileSize() const = 0; - - // ------------------------------------------------------------------- - /** @brief Flush the contents of the file buffer (for writers) - * See fflush() for more details. - */ - virtual void Flush() = 0; -}; //! class IOStream - -// ---------------------------------------------------------------------------------- -inline -IOStream::IOStream() AI_NO_EXCEPT { - // empty -} - -// ---------------------------------------------------------------------------------- -inline -IOStream::~IOStream() { - // empty -} -// ---------------------------------------------------------------------------------- - -} //!namespace Assimp - -#endif //!!AI_IOSTREAM_H_INC diff --git a/tools/ZAPD/lib/assimp/include/assimp/IOStreamBuffer.h b/tools/ZAPD/lib/assimp/include/assimp/IOStreamBuffer.h deleted file mode 100644 index 58abd97a02..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/IOStreamBuffer.h +++ /dev/null @@ -1,355 +0,0 @@ -#pragma once - -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above -copyright notice, this list of conditions and the -following disclaimer. - -* Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the -following disclaimer in the documentation and/or other -materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its -contributors may be used to endorse or promote products -derived from this software without specific prior -written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ - -#include -#include - -#include "ParsingUtils.h" - -#include - -namespace Assimp { - -// --------------------------------------------------------------------------- -/** - * Implementation of a cached stream buffer. - */ -template -class IOStreamBuffer { -public: - /// @brief The class constructor. - IOStreamBuffer( size_t cache = 4096 * 4096 ); - - /// @brief The class destructor. - ~IOStreamBuffer(); - - /// @brief Will open the cached access for a given stream. - /// @param stream The stream to cache. - /// @return true if successful. - bool open( IOStream *stream ); - - /// @brief Will close the cached access. - /// @return true if successful. - bool close(); - - /// @brief Returns the file-size. - /// @return The file-size. - size_t size() const; - - /// @brief Returns the cache size. - /// @return The cache size. - size_t cacheSize() const; - - /// @brief Will read the next block. - /// @return true if successful. - bool readNextBlock(); - - /// @brief Returns the number of blocks to read. - /// @return The number of blocks. - size_t getNumBlocks() const; - - /// @brief Returns the current block index. - /// @return The current block index. - size_t getCurrentBlockIndex() const; - - /// @brief Returns the current file pos. - /// @return The current file pos. - size_t getFilePos() const; - - /// @brief Will read the next line. - /// @param buffer The buffer for the next line. - /// @return true if successful. - bool getNextDataLine( std::vector &buffer, T continuationToken ); - - /// @brief Will read the next line ascii or binary end line char. - /// @param buffer The buffer for the next line. - /// @return true if successful. - bool getNextLine(std::vector &buffer); - - /// @brief Will read the next block. - /// @param buffer The buffer for the next block. - /// @return true if successful. - bool getNextBlock( std::vector &buffer ); - -private: - IOStream *m_stream; - size_t m_filesize; - size_t m_cacheSize; - size_t m_numBlocks; - size_t m_blockIdx; - std::vector m_cache; - size_t m_cachePos; - size_t m_filePos; -}; - -template -inline -IOStreamBuffer::IOStreamBuffer( size_t cache ) -: m_stream( nullptr ) -, m_filesize( 0 ) -, m_cacheSize( cache ) -, m_numBlocks( 0 ) -, m_blockIdx( 0 ) -, m_cachePos( 0 ) -, m_filePos( 0 ) { - m_cache.resize( cache ); - std::fill( m_cache.begin(), m_cache.end(), '\n' ); -} - -template -inline -IOStreamBuffer::~IOStreamBuffer() { - // empty -} - -template -inline -bool IOStreamBuffer::open( IOStream *stream ) { - // file still opened! - if ( nullptr != m_stream ) { - return false; - } - - // Invalid stream pointer - if ( nullptr == stream ) { - return false; - } - - m_stream = stream; - m_filesize = m_stream->FileSize(); - if ( m_filesize == 0 ) { - return false; - } - if ( m_filesize < m_cacheSize ) { - m_cacheSize = m_filesize; - } - - m_numBlocks = m_filesize / m_cacheSize; - if ( ( m_filesize % m_cacheSize ) > 0 ) { - m_numBlocks++; - } - - return true; -} - -template -inline -bool IOStreamBuffer::close() { - if ( nullptr == m_stream ) { - return false; - } - - // init counters and state vars - m_stream = nullptr; - m_filesize = 0; - m_numBlocks = 0; - m_blockIdx = 0; - m_cachePos = 0; - m_filePos = 0; - - return true; -} - -template -inline -size_t IOStreamBuffer::size() const { - return m_filesize; -} - -template -inline -size_t IOStreamBuffer::cacheSize() const { - return m_cacheSize; -} - -template -inline -bool IOStreamBuffer::readNextBlock() { - m_stream->Seek( m_filePos, aiOrigin_SET ); - size_t readLen = m_stream->Read( &m_cache[ 0 ], sizeof( T ), m_cacheSize ); - if ( readLen == 0 ) { - return false; - } - if ( readLen < m_cacheSize ) { - m_cacheSize = readLen; - } - m_filePos += m_cacheSize; - m_cachePos = 0; - m_blockIdx++; - - return true; -} - -template -inline -size_t IOStreamBuffer::getNumBlocks() const { - return m_numBlocks; -} - -template -inline -size_t IOStreamBuffer::getCurrentBlockIndex() const { - return m_blockIdx; -} - -template -inline -size_t IOStreamBuffer::getFilePos() const { - return m_filePos; -} - -template -inline -bool IOStreamBuffer::getNextDataLine( std::vector &buffer, T continuationToken ) { - buffer.resize( m_cacheSize ); - if ( m_cachePos >= m_cacheSize || 0 == m_filePos ) { - if ( !readNextBlock() ) { - return false; - } - } - - bool continuationFound( false ); - size_t i = 0; - for( ;; ) { - if ( continuationToken == m_cache[ m_cachePos ] ) { - continuationFound = true; - ++m_cachePos; - } - if ( IsLineEnd( m_cache[ m_cachePos ] ) ) { - if ( !continuationFound ) { - // the end of the data line - break; - } else { - // skip line end - while ( m_cache[m_cachePos] != '\n') { - ++m_cachePos; - } - ++m_cachePos; - continuationFound = false; - } - } - - buffer[ i ] = m_cache[ m_cachePos ]; - ++m_cachePos; - ++i; - if (m_cachePos >= size()) { - break; - } - if ( m_cachePos >= m_cacheSize ) { - if ( !readNextBlock() ) { - return false; - } - } - } - - buffer[ i ] = '\n'; - ++m_cachePos; - - return true; -} - -static inline -bool isEndOfCache( size_t pos, size_t cacheSize ) { - return ( pos == cacheSize ); -} - -template -inline -bool IOStreamBuffer::getNextLine(std::vector &buffer) { - buffer.resize(m_cacheSize); - if ( isEndOfCache( m_cachePos, m_cacheSize ) || 0 == m_filePos) { - if (!readNextBlock()) { - return false; - } - } - - if (IsLineEnd(m_cache[m_cachePos])) { - // skip line end - while (m_cache[m_cachePos] != '\n') { - ++m_cachePos; - } - ++m_cachePos; - if ( isEndOfCache( m_cachePos, m_cacheSize ) ) { - if ( !readNextBlock() ) { - return false; - } - } - } - - size_t i( 0 ); - while (!IsLineEnd(m_cache[ m_cachePos ])) { - buffer[i] = m_cache[ m_cachePos ]; - ++m_cachePos; - ++i; - if (m_cachePos >= m_cacheSize) { - if (!readNextBlock()) { - return false; - } - } - } - buffer[i] = '\n'; - ++m_cachePos; - - return true; -} - -template -inline -bool IOStreamBuffer::getNextBlock( std::vector &buffer) { - // Return the last block-value if getNextLine was used before - if ( 0 != m_cachePos ) { - buffer = std::vector( m_cache.begin() + m_cachePos, m_cache.end() ); - m_cachePos = 0; - } else { - if ( !readNextBlock() ) { - return false; - } - - buffer = std::vector(m_cache.begin(), m_cache.end()); - } - - return true; -} - -} // !ns Assimp diff --git a/tools/ZAPD/lib/assimp/include/assimp/IOSystem.hpp b/tools/ZAPD/lib/assimp/include/assimp/IOSystem.hpp deleted file mode 100644 index 78139c2839..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/IOSystem.hpp +++ /dev/null @@ -1,357 +0,0 @@ -/* ---------------------------------------------------------------------------- -Open Asset Import Library (assimp) ---------------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the following -conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------- -*/ - -/** @file IOSystem.hpp - * @brief File system wrapper for C++. Inherit this class to supply - * custom file handling logic to the Import library. -*/ - -#pragma once -#ifndef AI_IOSYSTEM_H_INC -#define AI_IOSYSTEM_H_INC - -#ifndef __cplusplus -# error This header requires C++ to be used. aiFileIO.h is the \ - corresponding C interface. -#endif - -#include "types.h" - -#ifdef _WIN32 -# include -# include -# include -#else -# include -# include -# include -#endif // _WIN32 - -#include - -namespace Assimp { - - class IOStream; - -// --------------------------------------------------------------------------- -/** @brief CPP-API: Interface to the file system. - * - * Derive an own implementation from this interface to supply custom file handling - * to the importer library. If you implement this interface, you also want to - * supply a custom implementation for IOStream. - * - * @see Importer::SetIOHandler() - */ -class ASSIMP_API IOSystem -#ifndef SWIG - : public Intern::AllocateFromAssimpHeap -#endif -{ -public: - - // ------------------------------------------------------------------- - /** @brief Default constructor. - * - * Create an instance of your derived class and assign it to an - * #Assimp::Importer instance by calling Importer::SetIOHandler(). - */ - IOSystem() AI_NO_EXCEPT; - - // ------------------------------------------------------------------- - /** @brief Virtual destructor. - * - * It is safe to be called from within DLL Assimp, we're constructed - * on Assimp's heap. - */ - virtual ~IOSystem(); - - // ------------------------------------------------------------------- - /** @brief For backward compatibility - * @see Exists(const char*) - */ - AI_FORCE_INLINE bool Exists( const std::string& pFile) const; - - // ------------------------------------------------------------------- - /** @brief Tests for the existence of a file at the given path. - * - * @param pFile Path to the file - * @return true if there is a file with this path, else false. - */ - virtual bool Exists( const char* pFile) const = 0; - - // ------------------------------------------------------------------- - /** @brief Returns the system specific directory separator - * @return System specific directory separator - */ - virtual char getOsSeparator() const = 0; - - // ------------------------------------------------------------------- - /** @brief Open a new file with a given path. - * - * When the access to the file is finished, call Close() to release - * all associated resources (or the virtual dtor of the IOStream). - * - * @param pFile Path to the file - * @param pMode Desired file I/O mode. Required are: "wb", "w", "wt", - * "rb", "r", "rt". - * - * @return New IOStream interface allowing the lib to access - * the underlying file. - * @note When implementing this class to provide custom IO handling, - * you probably have to supply an own implementation of IOStream as well. - */ - virtual IOStream* Open(const char* pFile, - const char* pMode = "rb") = 0; - - // ------------------------------------------------------------------- - /** @brief For backward compatibility - * @see Open(const char*, const char*) - */ - inline IOStream* Open(const std::string& pFile, - const std::string& pMode = std::string("rb")); - - // ------------------------------------------------------------------- - /** @brief Closes the given file and releases all resources - * associated with it. - * @param pFile The file instance previously created by Open(). - */ - virtual void Close( IOStream* pFile) = 0; - - // ------------------------------------------------------------------- - /** @brief Compares two paths and check whether the point to - * identical files. - * - * The dummy implementation of this virtual member performs a - * case-insensitive comparison of the given strings. The default IO - * system implementation uses OS mechanisms to convert relative into - * absolute paths, so the result can be trusted. - * @param one First file - * @param second Second file - * @return true if the paths point to the same file. The file needn't - * be existing, however. - */ - virtual bool ComparePaths (const char* one, - const char* second) const; - - // ------------------------------------------------------------------- - /** @brief For backward compatibility - * @see ComparePaths(const char*, const char*) - */ - inline bool ComparePaths (const std::string& one, - const std::string& second) const; - - // ------------------------------------------------------------------- - /** @brief Pushes a new directory onto the directory stack. - * @param path Path to push onto the stack. - * @return True, when push was successful, false if path is empty. - */ - virtual bool PushDirectory( const std::string &path ); - - // ------------------------------------------------------------------- - /** @brief Returns the top directory from the stack. - * @return The directory on the top of the stack. - * Returns empty when no directory was pushed to the stack. - */ - virtual const std::string &CurrentDirectory() const; - - // ------------------------------------------------------------------- - /** @brief Returns the number of directories stored on the stack. - * @return The number of directories of the stack. - */ - virtual size_t StackSize() const; - - // ------------------------------------------------------------------- - /** @brief Pops the top directory from the stack. - * @return True, when a directory was on the stack. False if no - * directory was on the stack. - */ - virtual bool PopDirectory(); - - // ------------------------------------------------------------------- - /** @brief CReates an new directory at the given path. - * @param path [in] The path to create. - * @return True, when a directory was created. False if the directory - * cannot be created. - */ - virtual bool CreateDirectory( const std::string &path ); - - // ------------------------------------------------------------------- - /** @brief Will change the current directory to the given path. - * @param path [in] The path to change to. - * @return True, when the directory has changed successfully. - */ - virtual bool ChangeDirectory( const std::string &path ); - - virtual bool DeleteFile( const std::string &file ); - -private: - std::vector m_pathStack; -}; - -// ---------------------------------------------------------------------------- -AI_FORCE_INLINE -IOSystem::IOSystem() AI_NO_EXCEPT -: m_pathStack() { - // empty -} - -// ---------------------------------------------------------------------------- -AI_FORCE_INLINE -IOSystem::~IOSystem() { - // empty -} - -// ---------------------------------------------------------------------------- -// For compatibility, the interface of some functions taking a std::string was -// changed to const char* to avoid crashes between binary incompatible STL -// versions. This code her is inlined, so it shouldn't cause any problems. -// ---------------------------------------------------------------------------- - -// ---------------------------------------------------------------------------- -AI_FORCE_INLINE -IOStream* IOSystem::Open(const std::string& pFile, const std::string& pMode) { - // NOTE: - // For compatibility, interface was changed to const char* to - // avoid crashes between binary incompatible STL versions - return Open(pFile.c_str(),pMode.c_str()); -} - -// ---------------------------------------------------------------------------- -AI_FORCE_INLINE -bool IOSystem::Exists( const std::string& pFile) const { - // NOTE: - // For compatibility, interface was changed to const char* to - // avoid crashes between binary incompatible STL versions - return Exists(pFile.c_str()); -} - -// ---------------------------------------------------------------------------- -AI_FORCE_INLINE -bool IOSystem::ComparePaths (const std::string& one, const std::string& second) const { - // NOTE: - // For compatibility, interface was changed to const char* to - // avoid crashes between binary incompatible STL versions - return ComparePaths(one.c_str(),second.c_str()); -} - -// ---------------------------------------------------------------------------- -AI_FORCE_INLINE -bool IOSystem::PushDirectory( const std::string &path ) { - if ( path.empty() ) { - return false; - } - - m_pathStack.push_back( path ); - - return true; -} - -// ---------------------------------------------------------------------------- -AI_FORCE_INLINE -const std::string &IOSystem::CurrentDirectory() const { - if ( m_pathStack.empty() ) { - static const std::string Dummy(""); - return Dummy; - } - return m_pathStack[ m_pathStack.size()-1 ]; -} - -// ---------------------------------------------------------------------------- -AI_FORCE_INLINE -size_t IOSystem::StackSize() const { - return m_pathStack.size(); -} - -// ---------------------------------------------------------------------------- -AI_FORCE_INLINE -bool IOSystem::PopDirectory() { - if ( m_pathStack.empty() ) { - return false; - } - - m_pathStack.pop_back(); - - return true; -} - -// ---------------------------------------------------------------------------- -AI_FORCE_INLINE -bool IOSystem::CreateDirectory( const std::string &path ) { - if ( path.empty() ) { - return false; - } - -#ifdef _WIN32 - return 0 != ::_mkdir( path.c_str() ); -#else - return 0 != ::mkdir( path.c_str(), 0777 ); -#endif // _WIN32 -} - -// ---------------------------------------------------------------------------- -AI_FORCE_INLINE -bool IOSystem::ChangeDirectory( const std::string &path ) { - if ( path.empty() ) { - return false; - } - -#ifdef _WIN32 - return 0 != ::_chdir( path.c_str() ); -#else - return 0 != ::chdir( path.c_str() ); -#endif // _WIN32 -} - - -// ---------------------------------------------------------------------------- -AI_FORCE_INLINE -bool IOSystem::DeleteFile( const std::string &file ) { - if ( file.empty() ) { - return false; - } - const int retCode( ::remove( file.c_str() ) ); - return ( 0 == retCode ); -} -} //!ns Assimp - -#endif //AI_IOSYSTEM_H_INC diff --git a/tools/ZAPD/lib/assimp/include/assimp/Importer.hpp b/tools/ZAPD/lib/assimp/include/assimp/Importer.hpp deleted file mode 100644 index 4941df4122..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/Importer.hpp +++ /dev/null @@ -1,659 +0,0 @@ -/* ---------------------------------------------------------------------------- -Open Asset Import Library (assimp) ---------------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the following -conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------- -*/ - -/** @file Importer.hpp - * @brief Defines the C++-API to the Open Asset Import Library. - */ -#pragma once -#ifndef AI_ASSIMP_HPP_INC -#define AI_ASSIMP_HPP_INC - -#ifndef __cplusplus -# error This header requires C++ to be used. Use assimp.h for plain C. -#endif // __cplusplus - -// Public ASSIMP data structures -#include - -namespace Assimp { - // ======================================================================= - // Public interface to Assimp - class Importer; - class IOStream; - class IOSystem; - class ProgressHandler; - - // ======================================================================= - // Plugin development - // - // Include the following headers for the declarations: - // BaseImporter.h - // BaseProcess.h - class BaseImporter; - class BaseProcess; - class SharedPostProcessInfo; - class BatchLoader; - - // ======================================================================= - // Holy stuff, only for members of the high council of the Jedi. - class ImporterPimpl; -} //! namespace Assimp - -#define AI_PROPERTY_WAS_NOT_EXISTING 0xffffffff - -struct aiScene; - -// importerdesc.h -struct aiImporterDesc; - -/** @namespace Assimp Assimp's CPP-API and all internal APIs */ -namespace Assimp { - -// ---------------------------------------------------------------------------------- -/** CPP-API: The Importer class forms an C++ interface to the functionality of the -* Open Asset Import Library. -* -* Create an object of this class and call ReadFile() to import a file. -* If the import succeeds, the function returns a pointer to the imported data. -* The data remains property of the object, it is intended to be accessed -* read-only. The imported data will be destroyed along with the Importer -* object. If the import fails, ReadFile() returns a NULL pointer. In this -* case you can retrieve a human-readable error description be calling -* GetErrorString(). You can call ReadFile() multiple times with a single Importer -* instance. Actually, constructing Importer objects involves quite many -* allocations and may take some time, so it's better to reuse them as often as -* possible. -* -* If you need the Importer to do custom file handling to access the files, -* implement IOSystem and IOStream and supply an instance of your custom -* IOSystem implementation by calling SetIOHandler() before calling ReadFile(). -* If you do not assign a custion IO handler, a default handler using the -* standard C++ IO logic will be used. -* -* @note One Importer instance is not thread-safe. If you use multiple -* threads for loading, each thread should maintain its own Importer instance. -*/ -class ASSIMP_API Importer { -public: - /** - * @brief The upper limit for hints. - */ - static const unsigned int MaxLenHint = 200; - -public: - - // ------------------------------------------------------------------- - /** Constructor. Creates an empty importer object. - * - * Call ReadFile() to start the import process. The configuration - * property table is initially empty. - */ - Importer(); - - // ------------------------------------------------------------------- - /** Copy constructor. - * - * This copies the configuration properties of another Importer. - * If this Importer owns a scene it won't be copied. - * Call ReadFile() to start the import process. - */ - Importer(const Importer& other)=delete; - - // ------------------------------------------------------------------- - /** Assignment operator has been deleted - */ - Importer &operator=(const Importer &) = delete; - - // ------------------------------------------------------------------- - /** Destructor. The object kept ownership of the imported data, - * which now will be destroyed along with the object. - */ - ~Importer(); - - - // ------------------------------------------------------------------- - /** Registers a new loader. - * - * @param pImp Importer to be added. The Importer instance takes - * ownership of the pointer, so it will be automatically deleted - * with the Importer instance. - * @return AI_SUCCESS if the loader has been added. The registration - * fails if there is already a loader for a specific file extension. - */ - aiReturn RegisterLoader(BaseImporter* pImp); - - // ------------------------------------------------------------------- - /** Unregisters a loader. - * - * @param pImp Importer to be unregistered. - * @return AI_SUCCESS if the loader has been removed. The function - * fails if the loader is currently in use (this could happen - * if the #Importer instance is used by more than one thread) or - * if it has not yet been registered. - */ - aiReturn UnregisterLoader(BaseImporter* pImp); - - // ------------------------------------------------------------------- - /** Registers a new post-process step. - * - * At the moment, there's a small limitation: new post processing - * steps are added to end of the list, or in other words, executed - * last, after all built-in steps. - * @param pImp Post-process step to be added. The Importer instance - * takes ownership of the pointer, so it will be automatically - * deleted with the Importer instance. - * @return AI_SUCCESS if the step has been added correctly. - */ - aiReturn RegisterPPStep(BaseProcess* pImp); - - // ------------------------------------------------------------------- - /** Unregisters a post-process step. - * - * @param pImp Step to be unregistered. - * @return AI_SUCCESS if the step has been removed. The function - * fails if the step is currently in use (this could happen - * if the #Importer instance is used by more than one thread) or - * if it has not yet been registered. - */ - aiReturn UnregisterPPStep(BaseProcess* pImp); - - // ------------------------------------------------------------------- - /** Set an integer configuration property. - * @param szName Name of the property. All supported properties - * are defined in the aiConfig.g header (all constants share the - * prefix AI_CONFIG_XXX and are simple strings). - * @param iValue New value of the property - * @return true if the property was set before. The new value replaces - * the previous value in this case. - * @note Property of different types (float, int, string ..) are kept - * on different stacks, so calling SetPropertyInteger() for a - * floating-point property has no effect - the loader will call - * GetPropertyFloat() to read the property, but it won't be there. - */ - bool SetPropertyInteger(const char* szName, int iValue); - - // ------------------------------------------------------------------- - /** Set a boolean configuration property. Boolean properties - * are stored on the integer stack internally so it's possible - * to set them via #SetPropertyBool and query them with - * #GetPropertyBool and vice versa. - * @see SetPropertyInteger() - */ - bool SetPropertyBool(const char* szName, bool value) { - return SetPropertyInteger(szName,value); - } - - // ------------------------------------------------------------------- - /** Set a floating-point configuration property. - * @see SetPropertyInteger() - */ - bool SetPropertyFloat(const char* szName, ai_real fValue); - - // ------------------------------------------------------------------- - /** Set a string configuration property. - * @see SetPropertyInteger() - */ - bool SetPropertyString(const char* szName, const std::string& sValue); - - // ------------------------------------------------------------------- - /** Set a matrix configuration property. - * @see SetPropertyInteger() - */ - bool SetPropertyMatrix(const char* szName, const aiMatrix4x4& sValue); - - // ------------------------------------------------------------------- - /** Get a configuration property. - * @param szName Name of the property. All supported properties - * are defined in the aiConfig.g header (all constants share the - * prefix AI_CONFIG_XXX). - * @param iErrorReturn Value that is returned if the property - * is not found. - * @return Current value of the property - * @note Property of different types (float, int, string ..) are kept - * on different lists, so calling SetPropertyInteger() for a - * floating-point property has no effect - the loader will call - * GetPropertyFloat() to read the property, but it won't be there. - */ - int GetPropertyInteger(const char* szName, - int iErrorReturn = 0xffffffff) const; - - // ------------------------------------------------------------------- - /** Get a boolean configuration property. Boolean properties - * are stored on the integer stack internally so it's possible - * to set them via #SetPropertyBool and query them with - * #GetPropertyBool and vice versa. - * @see GetPropertyInteger() - */ - bool GetPropertyBool(const char* szName, bool bErrorReturn = false) const { - return GetPropertyInteger(szName,bErrorReturn)!=0; - } - - // ------------------------------------------------------------------- - /** Get a floating-point configuration property - * @see GetPropertyInteger() - */ - ai_real GetPropertyFloat(const char* szName, - ai_real fErrorReturn = 10e10) const; - - // ------------------------------------------------------------------- - /** Get a string configuration property - * - * The return value remains valid until the property is modified. - * @see GetPropertyInteger() - */ - const std::string GetPropertyString(const char* szName, - const std::string& sErrorReturn = "") const; - - // ------------------------------------------------------------------- - /** Get a matrix configuration property - * - * The return value remains valid until the property is modified. - * @see GetPropertyInteger() - */ - const aiMatrix4x4 GetPropertyMatrix(const char* szName, - const aiMatrix4x4& sErrorReturn = aiMatrix4x4()) const; - - // ------------------------------------------------------------------- - /** Supplies a custom IO handler to the importer to use to open and - * access files. If you need the importer to use custom IO logic to - * access the files, you need to provide a custom implementation of - * IOSystem and IOFile to the importer. Then create an instance of - * your custom IOSystem implementation and supply it by this function. - * - * The Importer takes ownership of the object and will destroy it - * afterwards. The previously assigned handler will be deleted. - * Pass NULL to take again ownership of your IOSystem and reset Assimp - * to use its default implementation. - * - * @param pIOHandler The IO handler to be used in all file accesses - * of the Importer. - */ - void SetIOHandler( IOSystem* pIOHandler); - - // ------------------------------------------------------------------- - /** Retrieves the IO handler that is currently set. - * You can use #IsDefaultIOHandler() to check whether the returned - * interface is the default IO handler provided by ASSIMP. The default - * handler is active as long the application doesn't supply its own - * custom IO handler via #SetIOHandler(). - * @return A valid IOSystem interface, never NULL. - */ - IOSystem* GetIOHandler() const; - - // ------------------------------------------------------------------- - /** Checks whether a default IO handler is active - * A default handler is active as long the application doesn't - * supply its own custom IO handler via #SetIOHandler(). - * @return true by default - */ - bool IsDefaultIOHandler() const; - - // ------------------------------------------------------------------- - /** Supplies a custom progress handler to the importer. This - * interface exposes an #Update() callback, which is called - * more or less periodically (please don't sue us if it - * isn't as periodically as you'd like it to have ...). - * This can be used to implement progress bars and loading - * timeouts. - * @param pHandler Progress callback interface. Pass NULL to - * disable progress reporting. - * @note Progress handlers can be used to abort the loading - * at almost any time.*/ - void SetProgressHandler ( ProgressHandler* pHandler ); - - // ------------------------------------------------------------------- - /** Retrieves the progress handler that is currently set. - * You can use #IsDefaultProgressHandler() to check whether the returned - * interface is the default handler provided by ASSIMP. The default - * handler is active as long the application doesn't supply its own - * custom handler via #SetProgressHandler(). - * @return A valid ProgressHandler interface, never NULL. - */ - ProgressHandler* GetProgressHandler() const; - - // ------------------------------------------------------------------- - /** Checks whether a default progress handler is active - * A default handler is active as long the application doesn't - * supply its own custom progress handler via #SetProgressHandler(). - * @return true by default - */ - bool IsDefaultProgressHandler() const; - - // ------------------------------------------------------------------- - /** @brief Check whether a given set of post-processing flags - * is supported. - * - * Some flags are mutually exclusive, others are probably - * not available because your excluded them from your - * Assimp builds. Calling this function is recommended if - * you're unsure. - * - * @param pFlags Bitwise combination of the aiPostProcess flags. - * @return true if this flag combination is fine. - */ - bool ValidateFlags(unsigned int pFlags) const; - - // ------------------------------------------------------------------- - /** Reads the given file and returns its contents if successful. - * - * If the call succeeds, the contents of the file are returned as a - * pointer to an aiScene object. The returned data is intended to be - * read-only, the importer object keeps ownership of the data and will - * destroy it upon destruction. If the import fails, NULL is returned. - * A human-readable error description can be retrieved by calling - * GetErrorString(). The previous scene will be deleted during this call. - * @param pFile Path and filename to the file to be imported. - * @param pFlags Optional post processing steps to be executed after - * a successful import. Provide a bitwise combination of the - * #aiPostProcessSteps flags. If you wish to inspect the imported - * scene first in order to fine-tune your post-processing setup, - * consider to use #ApplyPostProcessing(). - * @return A pointer to the imported data, NULL if the import failed. - * The pointer to the scene remains in possession of the Importer - * instance. Use GetOrphanedScene() to take ownership of it. - * - * @note Assimp is able to determine the file format of a file - * automatically. - */ - const aiScene* ReadFile( - const char* pFile, - unsigned int pFlags); - - // ------------------------------------------------------------------- - /** Reads the given file from a memory buffer and returns its - * contents if successful. - * - * If the call succeeds, the contents of the file are returned as a - * pointer to an aiScene object. The returned data is intended to be - * read-only, the importer object keeps ownership of the data and will - * destroy it upon destruction. If the import fails, NULL is returned. - * A human-readable error description can be retrieved by calling - * GetErrorString(). The previous scene will be deleted during this call. - * Calling this method doesn't affect the active IOSystem. - * @param pBuffer Pointer to the file data - * @param pLength Length of pBuffer, in bytes - * @param pFlags Optional post processing steps to be executed after - * a successful import. Provide a bitwise combination of the - * #aiPostProcessSteps flags. If you wish to inspect the imported - * scene first in order to fine-tune your post-processing setup, - * consider to use #ApplyPostProcessing(). - * @param pHint An additional hint to the library. If this is a non - * empty string, the library looks for a loader to support - * the file extension specified by pHint and passes the file to - * the first matching loader. If this loader is unable to completely - * the request, the library continues and tries to determine the - * file format on its own, a task that may or may not be successful. - * Check the return value, and you'll know ... - * @return A pointer to the imported data, NULL if the import failed. - * The pointer to the scene remains in possession of the Importer - * instance. Use GetOrphanedScene() to take ownership of it. - * - * @note This is a straightforward way to decode models from memory - * buffers, but it doesn't handle model formats that spread their - * data across multiple files or even directories. Examples include - * OBJ or MD3, which outsource parts of their material info into - * external scripts. If you need full functionality, provide - * a custom IOSystem to make Assimp find these files and use - * the regular ReadFile() API. - */ - const aiScene* ReadFileFromMemory( - const void* pBuffer, - size_t pLength, - unsigned int pFlags, - const char* pHint = ""); - - // ------------------------------------------------------------------- - /** Apply post-processing to an already-imported scene. - * - * This is strictly equivalent to calling #ReadFile() with the same - * flags. However, you can use this separate function to inspect - * the imported scene first to fine-tune your post-processing setup. - * @param pFlags Provide a bitwise combination of the - * #aiPostProcessSteps flags. - * @return A pointer to the post-processed data. This is still the - * same as the pointer returned by #ReadFile(). However, if - * post-processing fails, the scene could now be NULL. - * That's quite a rare case, post processing steps are not really - * designed to 'fail'. To be exact, the #aiProcess_ValidateDS - * flag is currently the only post processing step which can actually - * cause the scene to be reset to NULL. - * - * @note The method does nothing if no scene is currently bound - * to the #Importer instance. */ - const aiScene* ApplyPostProcessing(unsigned int pFlags); - - const aiScene* ApplyCustomizedPostProcessing( BaseProcess *rootProcess, bool requestValidation ); - - // ------------------------------------------------------------------- - /** @brief Reads the given file and returns its contents if successful. - * - * This function is provided for backward compatibility. - * See the const char* version for detailed docs. - * @see ReadFile(const char*, pFlags) */ - const aiScene* ReadFile( - const std::string& pFile, - unsigned int pFlags); - - // ------------------------------------------------------------------- - /** Frees the current scene. - * - * The function does nothing if no scene has previously been - * read via ReadFile(). FreeScene() is called automatically by the - * destructor and ReadFile() itself. */ - void FreeScene( ); - - // ------------------------------------------------------------------- - /** Returns an error description of an error that occurred in ReadFile(). - * - * Returns an empty string if no error occurred. - * @return A description of the last error, an empty string if no - * error occurred. The string is never NULL. - * - * @note The returned function remains valid until one of the - * following methods is called: #ReadFile(), #FreeScene(). */ - const char* GetErrorString() const; - - // ------------------------------------------------------------------- - /** Returns the scene loaded by the last successful call to ReadFile() - * - * @return Current scene or NULL if there is currently no scene loaded */ - const aiScene* GetScene() const; - - // ------------------------------------------------------------------- - /** Returns the scene loaded by the last successful call to ReadFile() - * and releases the scene from the ownership of the Importer - * instance. The application is now responsible for deleting the - * scene. Any further calls to GetScene() or GetOrphanedScene() - * will return NULL - until a new scene has been loaded via ReadFile(). - * - * @return Current scene or NULL if there is currently no scene loaded - * @note Use this method with maximal caution, and only if you have to. - * By design, aiScene's are exclusively maintained, allocated and - * deallocated by Assimp and no one else. The reasoning behind this - * is the golden rule that deallocations should always be done - * by the module that did the original allocation because heaps - * are not necessarily shared. GetOrphanedScene() enforces you - * to delete the returned scene by yourself, but this will only - * be fine if and only if you're using the same heap as assimp. - * On Windows, it's typically fine provided everything is linked - * against the multithreaded-dll version of the runtime library. - * It will work as well for static linkage with Assimp.*/ - aiScene* GetOrphanedScene(); - - // ------------------------------------------------------------------- - /** Returns whether a given file extension is supported by ASSIMP. - * - * @param szExtension Extension to be checked. - * Must include a trailing dot '.'. Example: ".3ds", ".md3". - * Cases-insensitive. - * @return true if the extension is supported, false otherwise */ - bool IsExtensionSupported(const char* szExtension) const; - - // ------------------------------------------------------------------- - /** @brief Returns whether a given file extension is supported by ASSIMP. - * - * This function is provided for backward compatibility. - * See the const char* version for detailed and up-to-date docs. - * @see IsExtensionSupported(const char*) */ - inline bool IsExtensionSupported(const std::string& szExtension) const; - - // ------------------------------------------------------------------- - /** Get a full list of all file extensions supported by ASSIMP. - * - * If a file extension is contained in the list this does of course not - * mean that ASSIMP is able to load all files with this extension --- - * it simply means there is an importer loaded which claims to handle - * files with this file extension. - * @param szOut String to receive the extension list. - * Format of the list: "*.3ds;*.obj;*.dae". This is useful for - * use with the WinAPI call GetOpenFileName(Ex). */ - void GetExtensionList(aiString& szOut) const; - - // ------------------------------------------------------------------- - /** @brief Get a full list of all file extensions supported by ASSIMP. - * - * This function is provided for backward compatibility. - * See the aiString version for detailed and up-to-date docs. - * @see GetExtensionList(aiString&)*/ - inline void GetExtensionList(std::string& szOut) const; - - // ------------------------------------------------------------------- - /** Get the number of importers currently registered with Assimp. */ - size_t GetImporterCount() const; - - // ------------------------------------------------------------------- - /** Get meta data for the importer corresponding to a specific index.. - * - * For the declaration of #aiImporterDesc, include . - * @param index Index to query, must be within [0,GetImporterCount()) - * @return Importer meta data structure, NULL if the index does not - * exist or if the importer doesn't offer meta information ( - * importers may do this at the cost of being hated by their peers).*/ - const aiImporterDesc* GetImporterInfo(size_t index) const; - - // ------------------------------------------------------------------- - /** Find the importer corresponding to a specific index. - * - * @param index Index to query, must be within [0,GetImporterCount()) - * @return Importer instance. NULL if the index does not - * exist. */ - BaseImporter* GetImporter(size_t index) const; - - // ------------------------------------------------------------------- - /** Find the importer corresponding to a specific file extension. - * - * This is quite similar to #IsExtensionSupported except a - * BaseImporter instance is returned. - * @param szExtension Extension to check for. The following formats - * are recognized (BAH being the file extension): "BAH" (comparison - * is case-insensitive), ".bah", "*.bah" (wild card and dot - * characters at the beginning of the extension are skipped). - * @return NULL if no importer is found*/ - BaseImporter* GetImporter (const char* szExtension) const; - - // ------------------------------------------------------------------- - /** Find the importer index corresponding to a specific file extension. - * - * @param szExtension Extension to check for. The following formats - * are recognized (BAH being the file extension): "BAH" (comparison - * is case-insensitive), ".bah", "*.bah" (wild card and dot - * characters at the beginning of the extension are skipped). - * @return (size_t)-1 if no importer is found */ - size_t GetImporterIndex (const char* szExtension) const; - - // ------------------------------------------------------------------- - /** Returns the storage allocated by ASSIMP to hold the scene data - * in memory. - * - * This refers to the currently loaded file, see #ReadFile(). - * @param in Data structure to be filled. - * @note The returned memory statistics refer to the actual - * size of the use data of the aiScene. Heap-related overhead - * is (naturally) not included.*/ - void GetMemoryRequirements(aiMemoryInfo& in) const; - - // ------------------------------------------------------------------- - /** Enables "extra verbose" mode. - * - * 'Extra verbose' means the data structure is validated after *every* - * single post processing step to make sure everyone modifies the data - * structure in a well-defined manner. This is a debug feature and not - * intended for use in production environments. */ - void SetExtraVerbose(bool bDo); - - // ------------------------------------------------------------------- - /** Private, do not use. */ - ImporterPimpl* Pimpl() { return pimpl; } - const ImporterPimpl* Pimpl() const { return pimpl; } - -protected: - - // Just because we don't want you to know how we're hacking around. - ImporterPimpl* pimpl; -}; //! class Importer - - -// ---------------------------------------------------------------------------- -// For compatibility, the interface of some functions taking a std::string was -// changed to const char* to avoid crashes between binary incompatible STL -// versions. This code her is inlined, so it shouldn't cause any problems. -// ---------------------------------------------------------------------------- - -// ---------------------------------------------------------------------------- -AI_FORCE_INLINE const aiScene* Importer::ReadFile( const std::string& pFile,unsigned int pFlags){ - return ReadFile(pFile.c_str(),pFlags); -} -// ---------------------------------------------------------------------------- -AI_FORCE_INLINE void Importer::GetExtensionList(std::string& szOut) const { - aiString s; - GetExtensionList(s); - szOut = s.data; -} -// ---------------------------------------------------------------------------- -AI_FORCE_INLINE bool Importer::IsExtensionSupported(const std::string& szExtension) const { - return IsExtensionSupported(szExtension.c_str()); -} - -} // !namespace Assimp - -#endif // AI_ASSIMP_HPP_INC diff --git a/tools/ZAPD/lib/assimp/include/assimp/LineSplitter.h b/tools/ZAPD/lib/assimp/include/assimp/LineSplitter.h deleted file mode 100644 index 4afe45b92a..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/LineSplitter.h +++ /dev/null @@ -1,285 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ - -/** @file LineSplitter.h - * @brief LineSplitter, a helper class to iterate through all lines - * of a file easily. Works with StreamReader. - */ -#pragma once -#ifndef INCLUDED_LINE_SPLITTER_H -#define INCLUDED_LINE_SPLITTER_H - -#include -#include "StreamReader.h" -#include "ParsingUtils.h" - -namespace Assimp { - -// ------------------------------------------------------------------------------------------------ -/** Usage: -@code -for(LineSplitter splitter(stream);splitter;++splitter) { - - if (*splitter == "hi!") { - ... - } - else if (splitter->substr(0,5) == "hello") { - ... - // access the third token in the line (tokens are space-separated) - if (strtol(splitter[2]) > 5) { .. } - } - - std::cout << "Current line is: " << splitter.get_index() << std::endl; -} -@endcode -*/ -// ------------------------------------------------------------------------------------------------ -class LineSplitter { -public: - typedef size_t line_idx; - - // ----------------------------------------- - /** construct from existing stream reader - note: trim is *always* assumed true if skyp_empty_lines==true - */ - LineSplitter(StreamReaderLE& stream, bool skip_empty_lines = true, bool trim = true); - - ~LineSplitter(); - - // ----------------------------------------- - /** pseudo-iterator increment */ - LineSplitter& operator++(); - - // ----------------------------------------- - LineSplitter& operator++(int); - - // ----------------------------------------- - /** get a pointer to the beginning of a particular token */ - const char* operator[] (size_t idx) const; - - // ----------------------------------------- - /** extract the start positions of N tokens from the current line*/ - template - void get_tokens(const char* (&tokens)[N]) const; - - // ----------------------------------------- - /** member access */ - const std::string* operator -> () const; - - std::string operator* () const; - - // ----------------------------------------- - /** boolean context */ - operator bool() const; - - // ----------------------------------------- - /** line indices are zero-based, empty lines are included */ - operator line_idx() const; - - line_idx get_index() const; - - // ----------------------------------------- - /** access the underlying stream object */ - StreamReaderLE& get_stream(); - - // ----------------------------------------- - /** !strcmp((*this)->substr(0,strlen(check)),check) */ - bool match_start(const char* check); - - // ----------------------------------------- - /** swallow the next call to ++, return the previous value. */ - void swallow_next_increment(); - - LineSplitter( const LineSplitter & ) = delete; - LineSplitter(LineSplitter &&) = delete; - LineSplitter &operator = ( const LineSplitter & ) = delete; - -private: - line_idx mIdx; - std::string mCur; - StreamReaderLE& mStream; - bool mSwallow, mSkip_empty_lines, mTrim; -}; - -inline -LineSplitter::LineSplitter(StreamReaderLE& stream, bool skip_empty_lines, bool trim ) -: mIdx(0) -, mCur() -, mStream(stream) -, mSwallow() -, mSkip_empty_lines(skip_empty_lines) -, mTrim(trim) { - mCur.reserve(1024); - operator++(); - mIdx = 0; -} - -inline -LineSplitter::~LineSplitter() { - // empty -} - -inline -LineSplitter& LineSplitter::operator++() { - if (mSwallow) { - mSwallow = false; - return *this; - } - - if (!*this) { - throw std::logic_error("End of file, no more lines to be retrieved."); - } - - char s; - mCur.clear(); - while (mStream.GetRemainingSize() && (s = mStream.GetI1(), 1)) { - if (s == '\n' || s == '\r') { - if (mSkip_empty_lines) { - while (mStream.GetRemainingSize() && ((s = mStream.GetI1()) == ' ' || s == '\r' || s == '\n')); - if (mStream.GetRemainingSize()) { - mStream.IncPtr(-1); - } - } else { - // skip both potential line terminators but don't read past this line. - if (mStream.GetRemainingSize() && (s == '\r' && mStream.GetI1() != '\n')) { - mStream.IncPtr(-1); - } - if (mTrim) { - while (mStream.GetRemainingSize() && ((s = mStream.GetI1()) == ' ' || s == '\t')); - if (mStream.GetRemainingSize()) { - mStream.IncPtr(-1); - } - } - } - break; - } - mCur += s; - } - ++mIdx; - - return *this; -} - -inline -LineSplitter &LineSplitter::operator++(int) { - return ++(*this); -} - -inline -const char *LineSplitter::operator[] (size_t idx) const { - const char* s = operator->()->c_str(); - - SkipSpaces(&s); - for (size_t i = 0; i < idx; ++i) { - - for (; !IsSpace(*s); ++s) { - if (IsLineEnd(*s)) { - throw std::range_error("Token index out of range, EOL reached"); - } - } - SkipSpaces(&s); - } - return s; -} - -template -inline -void LineSplitter::get_tokens(const char* (&tokens)[N]) const { - const char* s = operator->()->c_str(); - - SkipSpaces(&s); - for (size_t i = 0; i < N; ++i) { - if (IsLineEnd(*s)) { - throw std::range_error("Token count out of range, EOL reached"); - } - tokens[i] = s; - - for (; *s && !IsSpace(*s); ++s); - SkipSpaces(&s); - } -} - -inline -const std::string* LineSplitter::operator -> () const { - return &mCur; -} - -inline -std::string LineSplitter::operator* () const { - return mCur; -} - -inline -LineSplitter::operator bool() const { - return mStream.GetRemainingSize() > 0; -} - -inline -LineSplitter::operator line_idx() const { - return mIdx; -} - -inline -LineSplitter::line_idx LineSplitter::get_index() const { - return mIdx; -} - -inline -StreamReaderLE &LineSplitter::get_stream() { - return mStream; -} - -inline -bool LineSplitter::match_start(const char* check) { - const size_t len = ::strlen(check); - - return len <= mCur.length() && std::equal(check, check + len, mCur.begin()); -} - -inline -void LineSplitter::swallow_next_increment() { - mSwallow = true; -} - -} // Namespace Assimp - -#endif // INCLUDED_LINE_SPLITTER_H diff --git a/tools/ZAPD/lib/assimp/include/assimp/LogAux.h b/tools/ZAPD/lib/assimp/include/assimp/LogAux.h deleted file mode 100644 index 558485272e..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/LogAux.h +++ /dev/null @@ -1,131 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ - -/** @file LogAux.h - * @brief Common logging usage patterns for importer implementations - */ -#ifndef INCLUDED_AI_LOGAUX_H -#define INCLUDED_AI_LOGAUX_H - -#include -#include -#include - -namespace Assimp { - -template -class LogFunctions { -public: - // ------------------------------------------------------------------------------------------------ - static void ThrowException(const std::string& msg) - { - throw DeadlyImportError(Prefix()+msg); - } - - // ------------------------------------------------------------------------------------------------ - static void LogWarn(const Formatter::format& message) { - if (!DefaultLogger::isNullLogger()) { - ASSIMP_LOG_WARN(Prefix()+(std::string)message); - } - } - - // ------------------------------------------------------------------------------------------------ - static void LogError(const Formatter::format& message) { - if (!DefaultLogger::isNullLogger()) { - ASSIMP_LOG_ERROR(Prefix()+(std::string)message); - } - } - - // ------------------------------------------------------------------------------------------------ - static void LogInfo(const Formatter::format& message) { - if (!DefaultLogger::isNullLogger()) { - ASSIMP_LOG_INFO(Prefix()+(std::string)message); - } - } - - // ------------------------------------------------------------------------------------------------ - static void LogDebug(const Formatter::format& message) { - if (!DefaultLogger::isNullLogger()) { - ASSIMP_LOG_DEBUG(Prefix()+(std::string)message); - } - } - - // https://sourceforge.net/tracker/?func=detail&atid=1067632&aid=3358562&group_id=226462 -#if !defined(__GNUC__) || !defined(__APPLE__) || __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6) - - // ------------------------------------------------------------------------------------------------ - static void LogWarn (const char* message) { - if (!DefaultLogger::isNullLogger()) { - LogWarn(Formatter::format(message)); - } - } - - // ------------------------------------------------------------------------------------------------ - static void LogError (const char* message) { - if (!DefaultLogger::isNullLogger()) { - LogError(Formatter::format(message)); - } - } - - // ------------------------------------------------------------------------------------------------ - static void LogInfo (const char* message) { - if (!DefaultLogger::isNullLogger()) { - LogInfo(Formatter::format(message)); - } - } - - // ------------------------------------------------------------------------------------------------ - static void LogDebug (const char* message) { - if (!DefaultLogger::isNullLogger()) { - LogDebug(Formatter::format(message)); - } - } - -#endif - -private: - static const char* Prefix(); - -}; -} // ! Assimp - -#endif diff --git a/tools/ZAPD/lib/assimp/include/assimp/LogStream.hpp b/tools/ZAPD/lib/assimp/include/assimp/LogStream.hpp deleted file mode 100644 index d0281e2d02..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/LogStream.hpp +++ /dev/null @@ -1,111 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ - -/** @file LogStream.hpp - * @brief Abstract base class 'LogStream', representing an output log stream. - */ -#ifndef INCLUDED_AI_LOGSTREAM_H -#define INCLUDED_AI_LOGSTREAM_H - -#include "types.h" - -namespace Assimp { - -class IOSystem; - -// ------------------------------------------------------------------------------------ -/** @brief CPP-API: Abstract interface for log stream implementations. - * - * Several default implementations are provided, see #aiDefaultLogStream for more - * details. Writing your own implementation of LogStream is just necessary if these - * are not enough for your purpose. */ -class ASSIMP_API LogStream -#ifndef SWIG - : public Intern::AllocateFromAssimpHeap -#endif -{ -protected: - /** @brief Default constructor */ - LogStream() AI_NO_EXCEPT; - -public: - /** @brief Virtual destructor */ - virtual ~LogStream(); - - // ------------------------------------------------------------------- - /** @brief Overwrite this for your own output methods - * - * Log messages *may* consist of multiple lines and you shouldn't - * expect a consistent formatting. If you want custom formatting - * (e.g. generate HTML), supply a custom instance of Logger to - * #DefaultLogger:set(). Usually you can *expect* that a log message - * is exactly one line and terminated with a single \n character. - * @param message Message to be written */ - virtual void write(const char* message) = 0; - - // ------------------------------------------------------------------- - /** @brief Creates a default log stream - * @param streams Type of the default stream - * @param name For aiDefaultLogStream_FILE: name of the output file - * @param io For aiDefaultLogStream_FILE: IOSystem to be used to open the output - * file. Pass NULL for the default implementation. - * @return New LogStream instance. */ - static LogStream* createDefaultStream(aiDefaultLogStream stream, - const char* name = "AssimpLog.txt", - IOSystem* io = nullptr ); - -}; // !class LogStream - -inline -LogStream::LogStream() AI_NO_EXCEPT { - // empty -} - -inline -LogStream::~LogStream() { - // empty -} - -// ------------------------------------------------------------------------------------ -} // Namespace Assimp - -#endif diff --git a/tools/ZAPD/lib/assimp/include/assimp/Logger.hpp b/tools/ZAPD/lib/assimp/include/assimp/Logger.hpp deleted file mode 100644 index 89cade6c33..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/Logger.hpp +++ /dev/null @@ -1,305 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ - -/** @file Logger.hpp - * @brief Abstract base class 'Logger', base of the logging system. - */ -#ifndef INCLUDED_AI_LOGGER_H -#define INCLUDED_AI_LOGGER_H - -#include -#include - -namespace Assimp { - -class LogStream; - -// Maximum length of a log message. Longer messages are rejected. -#define MAX_LOG_MESSAGE_LENGTH 1024u - -// ---------------------------------------------------------------------------------- -/** @brief CPP-API: Abstract interface for logger implementations. - * Assimp provides a default implementation and uses it for almost all - * logging stuff ('DefaultLogger'). This class defines just basic logging - * behavior and is not of interest for you. Instead, take a look at #DefaultLogger. */ -class ASSIMP_API Logger -#ifndef SWIG - : public Intern::AllocateFromAssimpHeap -#endif -{ -public: - - // ---------------------------------------------------------------------- - /** @enum LogSeverity - * @brief Log severity to describe the granularity of logging. - */ - enum LogSeverity { - NORMAL, //!< Normal granularity of logging - VERBOSE //!< Debug infos will be logged, too - }; - - // ---------------------------------------------------------------------- - /** @enum ErrorSeverity - * @brief Description for severity of a log message. - * - * Every LogStream has a bitwise combination of these flags. - * A LogStream doesn't receive any messages of a specific type - * if it doesn't specify the corresponding ErrorSeverity flag. - */ - enum ErrorSeverity { - Debugging = 1, //!< Debug log message - Info = 2, //!< Info log message - Warn = 4, //!< Warn log message - Err = 8 //!< Error log message - }; - -public: - - /** @brief Virtual destructor */ - virtual ~Logger(); - - // ---------------------------------------------------------------------- - /** @brief Writes a debug message - * @param message Debug message*/ - void debug(const char* message); - void debug(const std::string &message); - - // ---------------------------------------------------------------------- - /** @brief Writes a info message - * @param message Info message*/ - void info(const char* message); - void info(const std::string &message); - - // ---------------------------------------------------------------------- - /** @brief Writes a warning message - * @param message Warn message*/ - void warn(const char* message); - void warn(const std::string &message); - - // ---------------------------------------------------------------------- - /** @brief Writes an error message - * @param message Error message*/ - void error(const char* message); - void error(const std::string &message); - - // ---------------------------------------------------------------------- - /** @brief Set a new log severity. - * @param log_severity New severity for logging*/ - void setLogSeverity(LogSeverity log_severity); - - // ---------------------------------------------------------------------- - /** @brief Get the current log severity*/ - LogSeverity getLogSeverity() const; - - // ---------------------------------------------------------------------- - /** @brief Attach a new log-stream - * - * The logger takes ownership of the stream and is responsible - * for its destruction (which is done using ::delete when the logger - * itself is destroyed). Call detachStream to detach a stream and to - * gain ownership of it again. - * @param pStream Log-stream to attach - * @param severity Message filter, specified which types of log - * messages are dispatched to the stream. Provide a bitwise - * combination of the ErrorSeverity flags. - * @return true if the stream has been attached, false otherwise.*/ - virtual bool attachStream(LogStream *pStream, - unsigned int severity = Debugging | Err | Warn | Info) = 0; - - // ---------------------------------------------------------------------- - /** @brief Detach a still attached stream from the logger (or - * modify the filter flags bits) - * @param pStream Log-stream instance for detaching - * @param severity Provide a bitwise combination of the ErrorSeverity - * flags. This value is &~ed with the current flags of the stream, - * if the result is 0 the stream is detached from the Logger and - * the caller retakes the possession of the stream. - * @return true if the stream has been detached, false otherwise.*/ - virtual bool detatchStream(LogStream *pStream, - unsigned int severity = Debugging | Err | Warn | Info) = 0; - -protected: - /** - * Default constructor - */ - Logger() AI_NO_EXCEPT; - - /** - * Construction with a given log severity - */ - explicit Logger(LogSeverity severity); - - // ---------------------------------------------------------------------- - /** - * @brief Called as a request to write a specific debug message - * @param message Debug message. Never longer than - * MAX_LOG_MESSAGE_LENGTH characters (excluding the '0'). - * @note The message string is only valid until the scope of - * the function is left. - */ - virtual void OnDebug(const char* message)= 0; - - // ---------------------------------------------------------------------- - /** - * @brief Called as a request to write a specific info message - * @param message Info message. Never longer than - * MAX_LOG_MESSAGE_LENGTH characters (ecxluding the '0'). - * @note The message string is only valid until the scope of - * the function is left. - */ - virtual void OnInfo(const char* message) = 0; - - // ---------------------------------------------------------------------- - /** - * @brief Called as a request to write a specific warn message - * @param message Warn message. Never longer than - * MAX_LOG_MESSAGE_LENGTH characters (exluding the '0'). - * @note The message string is only valid until the scope of - * the function is left. - */ - virtual void OnWarn(const char* essage) = 0; - - // ---------------------------------------------------------------------- - /** - * @brief Called as a request to write a specific error message - * @param message Error message. Never longer than - * MAX_LOG_MESSAGE_LENGTH characters (exluding the '0'). - * @note The message string is only valid until the scope of - * the function is left. - */ - virtual void OnError(const char* message) = 0; - -protected: - LogSeverity m_Severity; -}; - -// ---------------------------------------------------------------------------------- -// Default constructor -inline -Logger::Logger() AI_NO_EXCEPT -: m_Severity(NORMAL) { - // empty -} - -// ---------------------------------------------------------------------------------- -// Virtual destructor -inline -Logger::~Logger() { - // empty -} - -// ---------------------------------------------------------------------------------- -// Construction with given logging severity -inline -Logger::Logger(LogSeverity severity) -: m_Severity(severity) { - // empty -} - -// ---------------------------------------------------------------------------------- -// Log severity setter -inline -void Logger::setLogSeverity(LogSeverity log_severity){ - m_Severity = log_severity; -} - -// ---------------------------------------------------------------------------------- -// Log severity getter -inline -Logger::LogSeverity Logger::getLogSeverity() const { - return m_Severity; -} - -// ---------------------------------------------------------------------------------- -inline -void Logger::debug(const std::string &message) { - return debug(message.c_str()); -} - -// ---------------------------------------------------------------------------------- -inline -void Logger::error(const std::string &message) { - return error(message.c_str()); -} - -// ---------------------------------------------------------------------------------- -inline -void Logger::warn(const std::string &message) { - return warn(message.c_str()); -} - -// ---------------------------------------------------------------------------------- -inline -void Logger::info(const std::string &message) { - return info(message.c_str()); -} - -// ------------------------------------------------------------------------------------------------ -#define ASSIMP_LOG_WARN_F(string,...)\ - DefaultLogger::get()->warn((Formatter::format(string),__VA_ARGS__)) - -#define ASSIMP_LOG_ERROR_F(string,...)\ - DefaultLogger::get()->error((Formatter::format(string),__VA_ARGS__)) - -#define ASSIMP_LOG_DEBUG_F(string,...)\ - DefaultLogger::get()->debug((Formatter::format(string),__VA_ARGS__)) - -#define ASSIMP_LOG_INFO_F(string,...)\ - DefaultLogger::get()->info((Formatter::format(string),__VA_ARGS__)) - - -#define ASSIMP_LOG_WARN(string)\ - DefaultLogger::get()->warn(string) - -#define ASSIMP_LOG_ERROR(string)\ - DefaultLogger::get()->error(string) - -#define ASSIMP_LOG_DEBUG(string)\ - DefaultLogger::get()->debug(string) - -#define ASSIMP_LOG_INFO(string)\ - DefaultLogger::get()->info(string) - - -} // Namespace Assimp - -#endif // !! INCLUDED_AI_LOGGER_H diff --git a/tools/ZAPD/lib/assimp/include/assimp/Macros.h b/tools/ZAPD/lib/assimp/include/assimp/Macros.h deleted file mode 100644 index 6515303372..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/Macros.h +++ /dev/null @@ -1,49 +0,0 @@ -/* ---------------------------------------------------------------------------- -Open Asset Import Library (assimp) ---------------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the following -conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------- -*/ - -/* Helper macro to set a pointer to NULL in debug builds - */ -#if (defined ASSIMP_BUILD_DEBUG) -# define AI_DEBUG_INVALIDATE_PTR(x) x = NULL; -#else -# define AI_DEBUG_INVALIDATE_PTR(x) -#endif - diff --git a/tools/ZAPD/lib/assimp/include/assimp/MathFunctions.h b/tools/ZAPD/lib/assimp/include/assimp/MathFunctions.h deleted file mode 100644 index f49273bb34..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/MathFunctions.h +++ /dev/null @@ -1,86 +0,0 @@ -/* ---------------------------------------------------------------------------- -Open Asset Import Library (assimp) ---------------------------------------------------------------------------- - -Copyright (c) 2006-2016, assimp team - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the following -conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------- -*/ - -#pragma once - -/** @file MathFunctions.h -* @brief Implementation of math utility functions. - * -*/ - -#include - -namespace Assimp { -namespace Math { - -// TODO: use binary GCD for unsigned integers .... -template < typename IntegerType > -inline -IntegerType gcd( IntegerType a, IntegerType b ) { - const IntegerType zero = (IntegerType)0; - while ( true ) { - if ( a == zero ) - return b; - b %= a; - - if ( b == zero ) - return a; - a %= b; - } -} - -template < typename IntegerType > -inline -IntegerType lcm( IntegerType a, IntegerType b ) { - const IntegerType t = gcd (a,b); - if (!t) - return t; - return a / t * b; -} - -template -inline -T getEpsilon() { - return std::numeric_limits::epsilon(); -} - -} -} diff --git a/tools/ZAPD/lib/assimp/include/assimp/MemoryIOWrapper.h b/tools/ZAPD/lib/assimp/include/assimp/MemoryIOWrapper.h deleted file mode 100644 index c522787184..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/MemoryIOWrapper.h +++ /dev/null @@ -1,244 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ - -/** @file MemoryIOWrapper.h - * Handy IOStream/IOSystem implemetation to read directly from a memory buffer */ -#ifndef AI_MEMORYIOSTREAM_H_INC -#define AI_MEMORYIOSTREAM_H_INC - -#include -#include -#include -#include - -namespace Assimp { - -#define AI_MEMORYIO_MAGIC_FILENAME "$$$___magic___$$$" -#define AI_MEMORYIO_MAGIC_FILENAME_LENGTH 17 - -// ---------------------------------------------------------------------------------- -/** Implementation of IOStream to read directly from a memory buffer */ -// ---------------------------------------------------------------------------------- -class MemoryIOStream : public IOStream { -public: - MemoryIOStream (const uint8_t* buff, size_t len, bool own = false) - : buffer (buff) - , length(len) - , pos((size_t)0) - , own(own) { - // empty - } - - ~MemoryIOStream () { - if(own) { - delete[] buffer; - } - } - - // ------------------------------------------------------------------- - // Read from stream - size_t Read(void* pvBuffer, size_t pSize, size_t pCount) { - ai_assert(nullptr != pvBuffer); - ai_assert(0 != pSize); - - const size_t cnt = std::min( pCount, (length-pos) / pSize); - const size_t ofs = pSize * cnt; - - ::memcpy(pvBuffer,buffer+pos,ofs); - pos += ofs; - - return cnt; - } - - // ------------------------------------------------------------------- - // Write to stream - size_t Write(const void* /*pvBuffer*/, size_t /*pSize*/,size_t /*pCount*/) { - ai_assert(false); // won't be needed - return 0; - } - - // ------------------------------------------------------------------- - // Seek specific position - aiReturn Seek(size_t pOffset, aiOrigin pOrigin) { - if (aiOrigin_SET == pOrigin) { - if (pOffset > length) { - return AI_FAILURE; - } - pos = pOffset; - } else if (aiOrigin_END == pOrigin) { - if (pOffset > length) { - return AI_FAILURE; - } - pos = length-pOffset; - } else { - if (pOffset+pos > length) { - return AI_FAILURE; - } - pos += pOffset; - } - return AI_SUCCESS; - } - - // ------------------------------------------------------------------- - // Get current seek position - size_t Tell() const { - return pos; - } - - // ------------------------------------------------------------------- - // Get size of file - size_t FileSize() const { - return length; - } - - // ------------------------------------------------------------------- - // Flush file contents - void Flush() { - ai_assert(false); // won't be needed - } - -private: - const uint8_t* buffer; - size_t length,pos; - bool own; -}; - -// --------------------------------------------------------------------------- -/** Dummy IO system to read from a memory buffer */ -class MemoryIOSystem : public IOSystem { -public: - /** Constructor. */ - MemoryIOSystem(const uint8_t* buff, size_t len, IOSystem* io) - : buffer(buff) - , length(len) - , existing_io(io) - , created_streams() { - // empty - } - - /** Destructor. */ - ~MemoryIOSystem() { - } - - // ------------------------------------------------------------------- - /** Tests for the existence of a file at the given path. */ - bool Exists(const char* pFile) const override { - if (0 == strncmp( pFile, AI_MEMORYIO_MAGIC_FILENAME, AI_MEMORYIO_MAGIC_FILENAME_LENGTH ) ) { - return true; - } - return existing_io ? existing_io->Exists(pFile) : false; - } - - // ------------------------------------------------------------------- - /** Returns the directory separator. */ - char getOsSeparator() const override { - return existing_io ? existing_io->getOsSeparator() - : '/'; // why not? it doesn't care - } - - // ------------------------------------------------------------------- - /** Open a new file with a given path. */ - IOStream* Open(const char* pFile, const char* pMode = "rb") override { - if ( 0 == strncmp( pFile, AI_MEMORYIO_MAGIC_FILENAME, AI_MEMORYIO_MAGIC_FILENAME_LENGTH ) ) { - created_streams.emplace_back(new MemoryIOStream(buffer, length)); - return created_streams.back(); - } - return existing_io ? existing_io->Open(pFile, pMode) : NULL; - } - - // ------------------------------------------------------------------- - /** Closes the given file and releases all resources associated with it. */ - void Close( IOStream* pFile) override { - auto it = std::find(created_streams.begin(), created_streams.end(), pFile); - if (it != created_streams.end()) { - delete pFile; - created_streams.erase(it); - } else if (existing_io) { - existing_io->Close(pFile); - } - } - - // ------------------------------------------------------------------- - /** Compare two paths */ - bool ComparePaths(const char* one, const char* second) const override { - return existing_io ? existing_io->ComparePaths(one, second) : false; - } - - bool PushDirectory( const std::string &path ) override { - return existing_io ? existing_io->PushDirectory(path) : false; - } - - const std::string &CurrentDirectory() const override { - static std::string empty; - return existing_io ? existing_io->CurrentDirectory() : empty; - } - - size_t StackSize() const override { - return existing_io ? existing_io->StackSize() : 0; - } - - bool PopDirectory() override { - return existing_io ? existing_io->PopDirectory() : false; - } - - bool CreateDirectory( const std::string &path ) override { - return existing_io ? existing_io->CreateDirectory(path) : false; - } - - bool ChangeDirectory( const std::string &path ) override { - return existing_io ? existing_io->ChangeDirectory(path) : false; - } - - bool DeleteFile( const std::string &file ) override { - return existing_io ? existing_io->DeleteFile(file) : false; - } - -private: - const uint8_t* buffer; - size_t length; - IOSystem* existing_io; - std::vector created_streams; -}; - -} // end namespace Assimp - -#endif diff --git a/tools/ZAPD/lib/assimp/include/assimp/NullLogger.hpp b/tools/ZAPD/lib/assimp/include/assimp/NullLogger.hpp deleted file mode 100644 index c45d01bd48..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/NullLogger.hpp +++ /dev/null @@ -1,99 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ - -/** @file NullLogger.hpp - * @brief Dummy logger -*/ - -#ifndef INCLUDED_AI_NULLLOGGER_H -#define INCLUDED_AI_NULLLOGGER_H - -#include "Logger.hpp" - -namespace Assimp { - -// --------------------------------------------------------------------------- -/** @brief CPP-API: Empty logging implementation. - * - * Does nothing! Used by default if the application hasn't requested a - * custom logger via #DefaultLogger::set() or #DefaultLogger::create(); */ -class ASSIMP_API NullLogger - : public Logger { - -public: - - /** @brief Logs a debug message */ - void OnDebug(const char* message) { - (void)message; //this avoids compiler warnings - } - - /** @brief Logs an info message */ - void OnInfo(const char* message) { - (void)message; //this avoids compiler warnings - } - - /** @brief Logs a warning message */ - void OnWarn(const char* message) { - (void)message; //this avoids compiler warnings - } - - /** @brief Logs an error message */ - void OnError(const char* message) { - (void)message; //this avoids compiler warnings - } - - /** @brief Detach a still attached stream from logger */ - bool attachStream(LogStream *pStream, unsigned int severity) { - (void)pStream; (void)severity; //this avoids compiler warnings - return false; - } - - /** @brief Detach a still attached stream from logger */ - bool detatchStream(LogStream *pStream, unsigned int severity) { - (void)pStream; (void)severity; //this avoids compiler warnings - return false; - } - -private: -}; -} -#endif // !! AI_NULLLOGGER_H_INCLUDED diff --git a/tools/ZAPD/lib/assimp/include/assimp/ParsingUtils.h b/tools/ZAPD/lib/assimp/include/assimp/ParsingUtils.h deleted file mode 100644 index 6b9574fc67..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/ParsingUtils.h +++ /dev/null @@ -1,259 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ - - -/** @file ParsingUtils.h - * @brief Defines helper functions for text parsing - */ -#ifndef AI_PARSING_UTILS_H_INC -#define AI_PARSING_UTILS_H_INC - -#include "StringComparison.h" -#include "StringUtils.h" -#include - -namespace Assimp { - -// NOTE: the functions below are mostly intended as replacement for -// std::upper, std::lower, std::isupper, std::islower, std::isspace. -// we don't bother of locales. We don't want them. We want reliable -// (i.e. identical) results across all locales. - -// The functions below accept any character type, but know only -// about ASCII. However, UTF-32 is the only safe ASCII superset to -// use since it doesn't have multi-byte sequences. - -static const unsigned int BufferSize = 4096; - -// --------------------------------------------------------------------------------- -template -AI_FORCE_INLINE -char_t ToLower( char_t in ) { - return (in >= (char_t)'A' && in <= (char_t)'Z') ? (char_t)(in+0x20) : in; -} - -// --------------------------------------------------------------------------------- -template -AI_FORCE_INLINE -char_t ToUpper( char_t in) { - return (in >= (char_t)'a' && in <= (char_t)'z') ? (char_t)(in-0x20) : in; -} - -// --------------------------------------------------------------------------------- -template -AI_FORCE_INLINE -bool IsUpper( char_t in) { - return (in >= (char_t)'A' && in <= (char_t)'Z'); -} - -// --------------------------------------------------------------------------------- -template -AI_FORCE_INLINE -bool IsLower( char_t in) { - return (in >= (char_t)'a' && in <= (char_t)'z'); -} - -// --------------------------------------------------------------------------------- -template -AI_FORCE_INLINE -bool IsSpace( char_t in) { - return (in == (char_t)' ' || in == (char_t)'\t'); -} - -// --------------------------------------------------------------------------------- -template -AI_FORCE_INLINE -bool IsLineEnd( char_t in) { - return (in==(char_t)'\r'||in==(char_t)'\n'||in==(char_t)'\0'||in==(char_t)'\f'); -} - -// --------------------------------------------------------------------------------- -template -AI_FORCE_INLINE -bool IsSpaceOrNewLine( char_t in) { - return IsSpace(in) || IsLineEnd(in); -} - -// --------------------------------------------------------------------------------- -template -AI_FORCE_INLINE -bool SkipSpaces( const char_t* in, const char_t** out) { - while( *in == ( char_t )' ' || *in == ( char_t )'\t' ) { - ++in; - } - *out = in; - return !IsLineEnd(*in); -} - -// --------------------------------------------------------------------------------- -template -AI_FORCE_INLINE -bool SkipSpaces( const char_t** inout) { - return SkipSpaces(*inout,inout); -} - -// --------------------------------------------------------------------------------- -template -AI_FORCE_INLINE -bool SkipLine( const char_t* in, const char_t** out) { - while( *in != ( char_t )'\r' && *in != ( char_t )'\n' && *in != ( char_t )'\0' ) { - ++in; - } - - // files are opened in binary mode. Ergo there are both NL and CR - while( *in == ( char_t )'\r' || *in == ( char_t )'\n' ) { - ++in; - } - *out = in; - return *in != (char_t)'\0'; -} - -// --------------------------------------------------------------------------------- -template -AI_FORCE_INLINE -bool SkipLine( const char_t** inout) { - return SkipLine(*inout,inout); -} - -// --------------------------------------------------------------------------------- -template -AI_FORCE_INLINE -bool SkipSpacesAndLineEnd( const char_t* in, const char_t** out) { - while( *in == ( char_t )' ' || *in == ( char_t )'\t' || *in == ( char_t )'\r' || *in == ( char_t )'\n' ) { - ++in; - } - *out = in; - return *in != '\0'; -} - -// --------------------------------------------------------------------------------- -template -AI_FORCE_INLINE -bool SkipSpacesAndLineEnd( const char_t** inout) { - return SkipSpacesAndLineEnd(*inout,inout); -} - -// --------------------------------------------------------------------------------- -template -AI_FORCE_INLINE -bool GetNextLine( const char_t*& buffer, char_t out[ BufferSize ] ) { - if( ( char_t )'\0' == *buffer ) { - return false; - } - - char* _out = out; - char* const end = _out + BufferSize; - while( !IsLineEnd( *buffer ) && _out < end ) { - *_out++ = *buffer++; - } - *_out = (char_t)'\0'; - - while( IsLineEnd( *buffer ) && '\0' != *buffer ) { - ++buffer; - } - - return true; -} - -// --------------------------------------------------------------------------------- -template -AI_FORCE_INLINE bool IsNumeric( char_t in) { - return ( in >= '0' && in <= '9' ) || '-' == in || '+' == in; -} - -// --------------------------------------------------------------------------------- -template -AI_FORCE_INLINE -bool TokenMatch(char_t*& in, const char* token, unsigned int len) -{ - if (!::strncmp(token,in,len) && IsSpaceOrNewLine(in[len])) { - if (in[len] != '\0') { - in += len+1; - } else { - // If EOF after the token make sure we don't go past end of buffer - in += len; - } - return true; - } - - return false; -} -// --------------------------------------------------------------------------------- -/** @brief Case-ignoring version of TokenMatch - * @param in Input - * @param token Token to check for - * @param len Number of characters to check - */ -AI_FORCE_INLINE -bool TokenMatchI(const char*& in, const char* token, unsigned int len) { - if (!ASSIMP_strincmp(token,in,len) && IsSpaceOrNewLine(in[len])) { - in += len+1; - return true; - } - return false; -} - -// --------------------------------------------------------------------------------- -AI_FORCE_INLINE -void SkipToken(const char*& in) { - SkipSpaces(&in); - while ( !IsSpaceOrNewLine( *in ) ) { - ++in; - } -} - -// --------------------------------------------------------------------------------- -AI_FORCE_INLINE -std::string GetNextToken(const char*& in) { - SkipSpacesAndLineEnd(&in); - const char* cur = in; - while ( !IsSpaceOrNewLine( *in ) ) { - ++in; - } - return std::string(cur,(size_t)(in-cur)); -} - -// --------------------------------------------------------------------------------- - -} // ! namespace Assimp - -#endif // ! AI_PARSING_UTILS_H_INC diff --git a/tools/ZAPD/lib/assimp/include/assimp/Profiler.h b/tools/ZAPD/lib/assimp/include/assimp/Profiler.h deleted file mode 100644 index 6ff9d41c0a..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/Profiler.h +++ /dev/null @@ -1,99 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ - -/** @file Profiler.h - * @brief Utility to measure the respective runtime of each import step - */ -#ifndef INCLUDED_PROFILER_H -#define INCLUDED_PROFILER_H - -#include -#include -#include "TinyFormatter.h" - -#include - -namespace Assimp { -namespace Profiling { - -using namespace Formatter; - -// ------------------------------------------------------------------------------------------------ -/** Simple wrapper around boost::timer to simplify reporting. Timings are automatically - * dumped to the log file. - */ -class Profiler { -public: - Profiler() { - // empty - } - -public: - - /** Start a named timer */ - void BeginRegion(const std::string& region) { - regions[region] = std::chrono::system_clock::now(); - ASSIMP_LOG_DEBUG((format("START `"),region,"`")); - } - - - /** End a specific named timer and write its end time to the log */ - void EndRegion(const std::string& region) { - RegionMap::const_iterator it = regions.find(region); - if (it == regions.end()) { - return; - } - - std::chrono::duration elapsedSeconds = std::chrono::system_clock::now() - regions[region]; - ASSIMP_LOG_DEBUG((format("END `"),region,"`, dt= ", elapsedSeconds.count()," s")); - } - -private: - typedef std::map> RegionMap; - RegionMap regions; -}; - -} -} - -#endif - diff --git a/tools/ZAPD/lib/assimp/include/assimp/ProgressHandler.hpp b/tools/ZAPD/lib/assimp/include/assimp/ProgressHandler.hpp deleted file mode 100644 index 4e47f1d0a6..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/ProgressHandler.hpp +++ /dev/null @@ -1,145 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ - -/** @file ProgressHandler.hpp - * @brief Abstract base class 'ProgressHandler'. - */ -#pragma once -#ifndef AI_PROGRESSHANDLER_H_INC -#define AI_PROGRESSHANDLER_H_INC - -#include "types.h" - -namespace Assimp { - -// ------------------------------------------------------------------------------------ -/** @brief CPP-API: Abstract interface for custom progress report receivers. - * - * Each #Importer instance maintains its own #ProgressHandler. The default - * implementation provided by Assimp doesn't do anything at all. */ -class ASSIMP_API ProgressHandler -#ifndef SWIG - : public Intern::AllocateFromAssimpHeap -#endif -{ -protected: - /// @brief Default constructor - ProgressHandler () AI_NO_EXCEPT { - // empty - } - -public: - /// @brief Virtual destructor. - virtual ~ProgressHandler () { - } - - // ------------------------------------------------------------------- - /** @brief Progress callback. - * @param percentage An estimate of the current loading progress, - * in percent. Or -1.f if such an estimate is not available. - * - * There are restriction on what you may do from within your - * implementation of this method: no exceptions may be thrown and no - * non-const #Importer methods may be called. It is - * not generally possible to predict the number of callbacks - * fired during a single import. - * - * @return Return false to abort loading at the next possible - * occasion (loaders and Assimp are generally allowed to perform - * all needed cleanup tasks prior to returning control to the - * caller). If the loading is aborted, #Importer::ReadFile() - * returns always NULL. - * */ - virtual bool Update(float percentage = -1.f) = 0; - - // ------------------------------------------------------------------- - /** @brief Progress callback for file loading steps - * @param numberOfSteps The number of total post-processing - * steps - * @param currentStep The index of the current post-processing - * step that will run, or equal to numberOfSteps if all of - * them has finished. This number is always strictly monotone - * increasing, although not necessarily linearly. - * - * @note This is currently only used at the start and the end - * of the file parsing. - * */ - virtual void UpdateFileRead(int currentStep /*= 0*/, int numberOfSteps /*= 0*/) { - float f = numberOfSteps ? currentStep / (float)numberOfSteps : 1.0f; - Update( f * 0.5f ); - } - - // ------------------------------------------------------------------- - /** @brief Progress callback for post-processing steps - * @param numberOfSteps The number of total post-processing - * steps - * @param currentStep The index of the current post-processing - * step that will run, or equal to numberOfSteps if all of - * them has finished. This number is always strictly monotone - * increasing, although not necessarily linearly. - * */ - virtual void UpdatePostProcess(int currentStep /*= 0*/, int numberOfSteps /*= 0*/) { - float f = numberOfSteps ? currentStep / (float)numberOfSteps : 1.0f; - Update( f * 0.5f + 0.5f ); - } - - - // ------------------------------------------------------------------- - /** @brief Progress callback for export steps. - * @param numberOfSteps The number of total processing - * steps - * @param currentStep The index of the current post-processing - * step that will run, or equal to numberOfSteps if all of - * them has finished. This number is always strictly monotone - * increasing, although not necessarily linearly. - * */ - virtual void UpdateFileWrite(int currentStep /*= 0*/, int numberOfSteps /*= 0*/) { - float f = numberOfSteps ? currentStep / (float)numberOfSteps : 1.0f; - Update(f * 0.5f); - } -}; // !class ProgressHandler - -// ------------------------------------------------------------------------------------ - -} // Namespace Assimp - -#endif // AI_PROGRESSHANDLER_H_INC diff --git a/tools/ZAPD/lib/assimp/include/assimp/RemoveComments.h b/tools/ZAPD/lib/assimp/include/assimp/RemoveComments.h deleted file mode 100644 index 404b496719..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/RemoveComments.h +++ /dev/null @@ -1,91 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ - -/** @file Declares a helper class, "CommentRemover", which can be - * used to remove comments (single and multi line) from a text file. - */ -#ifndef AI_REMOVE_COMMENTS_H_INC -#define AI_REMOVE_COMMENTS_H_INC - - -#include - -namespace Assimp { - -// --------------------------------------------------------------------------- -/** \brief Helper class to remove single and multi line comments from a file - * - * Some mesh formats like MD5 have comments that are quite similar - * to those in C or C++ so this code has been moved to a separate - * module. - */ -class ASSIMP_API CommentRemover -{ - // class cannot be instanced - CommentRemover() {} - -public: - - //! Remove single-line comments. The end of a line is - //! expected to be either NL or CR or NLCR. - //! \param szComment The start sequence of the comment, e.g. "//" - //! \param szBuffer Buffer to work with - //! \param chReplacement Character to be used as replacement - //! for commented lines. By default this is ' ' - static void RemoveLineComments(const char* szComment, - char* szBuffer, char chReplacement = ' '); - - //! Remove multi-line comments. The end of a line is - //! expected to be either NL or CR or NLCR. Multi-line comments - //! may not be nested (as in C). - //! \param szCommentStart The start sequence of the comment, e.g. "/*" - //! \param szCommentEnd The end sequence of the comment, e.g. "*/" - //! \param szBuffer Buffer to work with - //! \param chReplacement Character to be used as replacement - //! for commented lines. By default this is ' ' - static void RemoveMultiLineComments(const char* szCommentStart, - const char* szCommentEnd,char* szBuffer, - char chReplacement = ' '); -}; -} // ! Assimp - -#endif // !! AI_REMOVE_COMMENTS_H_INC diff --git a/tools/ZAPD/lib/assimp/include/assimp/SGSpatialSort.h b/tools/ZAPD/lib/assimp/include/assimp/SGSpatialSort.h deleted file mode 100644 index 5b4f3f41f2..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/SGSpatialSort.h +++ /dev/null @@ -1,150 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ - -/** Small helper classes to optimize finding vertices close to a given location - */ -#ifndef AI_D3DSSPATIALSORT_H_INC -#define AI_D3DSSPATIALSORT_H_INC - -#include -#include -#include - -namespace Assimp { - -// ---------------------------------------------------------------------------------- -/** Specialized version of SpatialSort to support smoothing groups - * This is used in by the 3DS, ASE and LWO loaders. 3DS and ASE share their - * normal computation code in SmoothingGroups.inl, the LWO loader has its own - * implementation to handle all details of its file format correctly. - */ -// ---------------------------------------------------------------------------------- -class ASSIMP_API SGSpatialSort -{ -public: - - SGSpatialSort(); - - // ------------------------------------------------------------------- - /** Construction from a given face array, handling smoothing groups - * properly - */ - explicit SGSpatialSort(const std::vector& vPositions); - - // ------------------------------------------------------------------- - /** Add a vertex to the spatial sort - * @param vPosition Vertex position to be added - * @param index Index of the vrtex - * @param smoothingGroup SmoothingGroup for this vertex - */ - void Add(const aiVector3D& vPosition, unsigned int index, - unsigned int smoothingGroup); - - // ------------------------------------------------------------------- - /** Prepare the spatial sorter for use. This step runs in O(logn) - */ - void Prepare(); - - /** Destructor */ - ~SGSpatialSort(); - - // ------------------------------------------------------------------- - /** Returns an iterator for all positions close to the given position. - * @param pPosition The position to look for vertices. - * @param pSG Only included vertices with at least one shared smooth group - * @param pRadius Maximal distance from the position a vertex may have - * to be counted in. - * @param poResults The container to store the indices of the found - * positions. Will be emptied by the call so it may contain anything. - * @param exactMatch Specifies whether smoothing groups are bit masks - * (false) or integral values (true). In the latter case, a vertex - * cannot belong to more than one smoothing group. - * @return An iterator to iterate over all vertices in the given area. - */ - // ------------------------------------------------------------------- - void FindPositions( const aiVector3D& pPosition, uint32_t pSG, - float pRadius, std::vector& poResults, - bool exactMatch = false) const; - -protected: - /** Normal of the sorting plane, normalized. The center is always at (0, 0, 0) */ - aiVector3D mPlaneNormal; - - // ------------------------------------------------------------------- - /** An entry in a spatially sorted position array. Consists of a - * vertex index, its position and its pre-calculated distance from - * the reference plane */ - // ------------------------------------------------------------------- - struct Entry { - unsigned int mIndex; ///< The vertex referred by this entry - aiVector3D mPosition; ///< Position - uint32_t mSmoothGroups; - float mDistance; ///< Distance of this vertex to the sorting plane - - Entry() AI_NO_EXCEPT - : mIndex(0) - , mPosition() - , mSmoothGroups(0) - , mDistance(0.0f) { - // empty - } - - Entry( unsigned int pIndex, const aiVector3D& pPosition, float pDistance,uint32_t pSG) - : mIndex( pIndex) - , mPosition( pPosition) - , mSmoothGroups(pSG) - , mDistance( pDistance) { - // empty - } - - bool operator < (const Entry& e) const { - return mDistance < e.mDistance; - } - }; - - // all positions, sorted by distance to the sorting plane - std::vector mPositions; -}; - -} // end of namespace Assimp - -#endif // AI_SPATIALSORT_H_INC diff --git a/tools/ZAPD/lib/assimp/include/assimp/SceneCombiner.h b/tools/ZAPD/lib/assimp/include/assimp/SceneCombiner.h deleted file mode 100644 index f69a25f43b..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/SceneCombiner.h +++ /dev/null @@ -1,403 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ - -/** @file Declares a helper class, "SceneCombiner" providing various - * utilities to merge scenes. - */ -#ifndef AI_SCENE_COMBINER_H_INC -#define AI_SCENE_COMBINER_H_INC - -#include -#include -#include -#include -#include -#include -#include - -#include - -struct aiScene; -struct aiNode; -struct aiMaterial; -struct aiTexture; -struct aiCamera; -struct aiLight; -struct aiMetadata; -struct aiBone; -struct aiMesh; -struct aiAnimMesh; -struct aiAnimation; -struct aiNodeAnim; - -namespace Assimp { - -// --------------------------------------------------------------------------- -/** \brief Helper data structure for SceneCombiner. - * - * Describes to which node a scene must be attached to. - */ -struct AttachmentInfo -{ - AttachmentInfo() - : scene (NULL) - , attachToNode (NULL) - {} - - AttachmentInfo(aiScene* _scene, aiNode* _attachToNode) - : scene (_scene) - , attachToNode (_attachToNode) - {} - - aiScene* scene; - aiNode* attachToNode; -}; - -// --------------------------------------------------------------------------- -struct NodeAttachmentInfo -{ - NodeAttachmentInfo() - : node (NULL) - , attachToNode (NULL) - , resolved (false) - , src_idx (SIZE_MAX) - {} - - NodeAttachmentInfo(aiNode* _scene, aiNode* _attachToNode,size_t idx) - : node (_scene) - , attachToNode (_attachToNode) - , resolved (false) - , src_idx (idx) - {} - - aiNode* node; - aiNode* attachToNode; - bool resolved; - size_t src_idx; -}; - -// --------------------------------------------------------------------------- -/** @def AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES - * Generate unique names for all named scene items - */ -#define AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES 0x1 - -/** @def AI_INT_MERGE_SCENE_GEN_UNIQUE_MATNAMES - * Generate unique names for materials, too. - * This is not absolutely required to pass the validation. - */ -#define AI_INT_MERGE_SCENE_GEN_UNIQUE_MATNAMES 0x2 - -/** @def AI_INT_MERGE_SCENE_DUPLICATES_DEEP_CPY - * Use deep copies of duplicate scenes - */ -#define AI_INT_MERGE_SCENE_DUPLICATES_DEEP_CPY 0x4 - -/** @def AI_INT_MERGE_SCENE_RESOLVE_CROSS_ATTACHMENTS - * If attachment nodes are not found in the given master scene, - * search the other imported scenes for them in an any order. - */ -#define AI_INT_MERGE_SCENE_RESOLVE_CROSS_ATTACHMENTS 0x8 - -/** @def AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY - * Can be combined with AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES. - * Unique names are generated, but only if this is absolutely - * required to avoid name conflicts. - */ -#define AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY 0x10 - -typedef std::pair BoneSrcIndex; - -// --------------------------------------------------------------------------- -/** @brief Helper data structure for SceneCombiner::MergeBones. - */ -struct BoneWithHash : public std::pair { - std::vector pSrcBones; -}; - -// --------------------------------------------------------------------------- -/** @brief Utility for SceneCombiner - */ -struct SceneHelper -{ - SceneHelper () - : scene (NULL) - , idlen (0) - { - id[0] = 0; - } - - explicit SceneHelper (aiScene* _scene) - : scene (_scene) - , idlen (0) - { - id[0] = 0; - } - - AI_FORCE_INLINE aiScene* operator-> () const - { - return scene; - } - - // scene we're working on - aiScene* scene; - - // prefix to be added to all identifiers in the scene ... - char id [32]; - - // and its strlen() - unsigned int idlen; - - // hash table to quickly check whether a name is contained in the scene - std::set hashes; -}; - -// --------------------------------------------------------------------------- -/** \brief Static helper class providing various utilities to merge two - * scenes. It is intended as internal utility and NOT for use by - * applications. - * - * The class is currently being used by various postprocessing steps - * and loaders (ie. LWS). - */ -class ASSIMP_API SceneCombiner { - // class cannot be instanced - SceneCombiner() { - // empty - } - - ~SceneCombiner() { - // empty - } - -public: - // ------------------------------------------------------------------- - /** Merges two or more scenes. - * - * @param dest Receives a pointer to the destination scene. If the - * pointer doesn't point to NULL when the function is called, the - * existing scene is cleared and refilled. - * @param src Non-empty list of scenes to be merged. The function - * deletes the input scenes afterwards. There may be duplicate scenes. - * @param flags Combination of the AI_INT_MERGE_SCENE flags defined above - */ - static void MergeScenes(aiScene** dest,std::vector& src, - unsigned int flags = 0); - - // ------------------------------------------------------------------- - /** Merges two or more scenes and attaches all scenes to a specific - * position in the node graph of the master scene. - * - * @param dest Receives a pointer to the destination scene. If the - * pointer doesn't point to NULL when the function is called, the - * existing scene is cleared and refilled. - * @param master Master scene. It will be deleted afterwards. All - * other scenes will be inserted in its node graph. - * @param src Non-empty list of scenes to be merged along with their - * corresponding attachment points in the master scene. The function - * deletes the input scenes afterwards. There may be duplicate scenes. - * @param flags Combination of the AI_INT_MERGE_SCENE flags defined above - */ - static void MergeScenes(aiScene** dest, aiScene* master, - std::vector& src, - unsigned int flags = 0); - - // ------------------------------------------------------------------- - /** Merges two or more meshes - * - * The meshes should have equal vertex formats. Only components - * that are provided by ALL meshes will be present in the output mesh. - * An exception is made for VColors - they are set to black. The - * meshes should have the same material indices, too. The output - * material index is always the material index of the first mesh. - * - * @param dest Destination mesh. Must be empty. - * @param flags Currently no parameters - * @param begin First mesh to be processed - * @param end Points to the mesh after the last mesh to be processed - */ - static void MergeMeshes(aiMesh** dest,unsigned int flags, - std::vector::const_iterator begin, - std::vector::const_iterator end); - - // ------------------------------------------------------------------- - /** Merges two or more bones - * - * @param out Mesh to receive the output bone list - * @param flags Currently no parameters - * @param begin First mesh to be processed - * @param end Points to the mesh after the last mesh to be processed - */ - static void MergeBones(aiMesh* out,std::vector::const_iterator it, - std::vector::const_iterator end); - - // ------------------------------------------------------------------- - /** Merges two or more materials - * - * The materials should be complementary as much as possible. In case - * of a property present in different materials, the first occurrence - * is used. - * - * @param dest Destination material. Must be empty. - * @param begin First material to be processed - * @param end Points to the material after the last material to be processed - */ - static void MergeMaterials(aiMaterial** dest, - std::vector::const_iterator begin, - std::vector::const_iterator end); - - // ------------------------------------------------------------------- - /** Builds a list of uniquely named bones in a mesh list - * - * @param asBones Receives the output list - * @param it First mesh to be processed - * @param end Last mesh to be processed - */ - static void BuildUniqueBoneList(std::list& asBones, - std::vector::const_iterator it, - std::vector::const_iterator end); - - // ------------------------------------------------------------------- - /** Add a name prefix to all nodes in a scene. - * - * @param Current node. This function is called recursively. - * @param prefix Prefix to be added to all nodes - * @param len STring length - */ - static void AddNodePrefixes(aiNode* node, const char* prefix, - unsigned int len); - - // ------------------------------------------------------------------- - /** Add an offset to all mesh indices in a node graph - * - * @param Current node. This function is called recursively. - * @param offset Offset to be added to all mesh indices - */ - static void OffsetNodeMeshIndices (aiNode* node, unsigned int offset); - - // ------------------------------------------------------------------- - /** Attach a list of node graphs to well-defined nodes in a master - * graph. This is a helper for MergeScenes() - * - * @param master Master scene - * @param srcList List of source scenes along with their attachment - * points. If an attachment point is NULL (or does not exist in - * the master graph), a scene is attached to the root of the master - * graph (as an additional child node) - * @duplicates List of duplicates. If elem[n] == n the scene is not - * a duplicate. Otherwise elem[n] links scene n to its first occurrence. - */ - static void AttachToGraph ( aiScene* master, - std::vector& srcList); - - static void AttachToGraph (aiNode* attach, - std::vector& srcList); - - - // ------------------------------------------------------------------- - /** Get a deep copy of a scene - * - * @param dest Receives a pointer to the destination scene - * @param src Source scene - remains unmodified. - */ - static void CopyScene(aiScene** dest,const aiScene* source,bool allocate = true); - - - // ------------------------------------------------------------------- - /** Get a flat copy of a scene - * - * Only the first hierarchy layer is copied. All pointer members of - * aiScene are shared by source and destination scene. If the - * pointer doesn't point to NULL when the function is called, the - * existing scene is cleared and refilled. - * @param dest Receives a pointer to the destination scene - * @param src Source scene - remains unmodified. - */ - static void CopySceneFlat(aiScene** dest,const aiScene* source); - - - // ------------------------------------------------------------------- - /** Get a deep copy of a mesh - * - * @param dest Receives a pointer to the destination mesh - * @param src Source mesh - remains unmodified. - */ - static void Copy (aiMesh** dest, const aiMesh* src); - - // similar to Copy(): - static void Copy (aiAnimMesh** dest, const aiAnimMesh* src); - static void Copy (aiMaterial** dest, const aiMaterial* src); - static void Copy (aiTexture** dest, const aiTexture* src); - static void Copy (aiAnimation** dest, const aiAnimation* src); - static void Copy (aiCamera** dest, const aiCamera* src); - static void Copy (aiBone** dest, const aiBone* src); - static void Copy (aiLight** dest, const aiLight* src); - static void Copy (aiNodeAnim** dest, const aiNodeAnim* src); - static void Copy (aiMetadata** dest, const aiMetadata* src); - - // recursive, of course - static void Copy (aiNode** dest, const aiNode* src); - - -private: - - // ------------------------------------------------------------------- - // Same as AddNodePrefixes, but with an additional check - static void AddNodePrefixesChecked(aiNode* node, const char* prefix, - unsigned int len, - std::vector& input, - unsigned int cur); - - // ------------------------------------------------------------------- - // Add node identifiers to a hashing set - static void AddNodeHashes(aiNode* node, std::set& hashes); - - - // ------------------------------------------------------------------- - // Search for duplicate names - static bool FindNameMatch(const aiString& name, - std::vector& input, unsigned int cur); -}; - -} - -#endif // !! AI_SCENE_COMBINER_H_INC diff --git a/tools/ZAPD/lib/assimp/include/assimp/SkeletonMeshBuilder.h b/tools/ZAPD/lib/assimp/include/assimp/SkeletonMeshBuilder.h deleted file mode 100644 index f9b8d9f55c..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/SkeletonMeshBuilder.h +++ /dev/null @@ -1,125 +0,0 @@ -/** Helper class to construct a dummy mesh for file formats containing only motion data */ - -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above -copyright notice, this list of conditions and the -following disclaimer. - -* Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the -following disclaimer in the documentation and/or other -materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its -contributors may be used to endorse or promote products -derived from this software without specific prior -written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ - -/** @file SkeletonMeshBuilder.h - * Declares SkeletonMeshBuilder, a tiny utility to build dummy meshes - * for animation skeletons. - */ - -#ifndef AI_SKELETONMESHBUILDER_H_INC -#define AI_SKELETONMESHBUILDER_H_INC - -#include -#include - -struct aiMaterial; -struct aiScene; -struct aiNode; - -namespace Assimp { - -// --------------------------------------------------------------------------- -/** - * This little helper class constructs a dummy mesh for a given scene - * the resembles the node hierarchy. This is useful for file formats - * that don't carry any mesh data but only animation data. - */ -class ASSIMP_API SkeletonMeshBuilder -{ -public: - - // ------------------------------------------------------------------- - /** The constructor processes the given scene and adds a mesh there. - * - * Does nothing if the scene already has mesh data. - * @param pScene The scene for which a skeleton mesh should be constructed. - * @param root The node to start with. NULL is the scene root - * @param bKnobsOnly Set this to true if you don't want the connectors - * between the knobs representing the nodes. - */ - SkeletonMeshBuilder( aiScene* pScene, aiNode* root = NULL, - bool bKnobsOnly = false); - -protected: - - // ------------------------------------------------------------------- - /** Recursively builds a simple mesh representation for the given node - * and also creates a joint for the node that affects this part of - * the mesh. - * @param pNode The node to build geometry for. - */ - void CreateGeometry( const aiNode* pNode); - - // ------------------------------------------------------------------- - /** Creates the mesh from the internally accumulated stuff and returns it. - */ - aiMesh* CreateMesh(); - - // ------------------------------------------------------------------- - /** Creates a dummy material and returns it. */ - aiMaterial* CreateMaterial(); - -protected: - /** space to assemble the mesh data: points */ - std::vector mVertices; - - /** faces */ - struct Face - { - unsigned int mIndices[3]; - Face(); - Face( unsigned int p0, unsigned int p1, unsigned int p2) - { mIndices[0] = p0; mIndices[1] = p1; mIndices[2] = p2; } - }; - std::vector mFaces; - - /** bones */ - std::vector mBones; - - bool mKnobsOnly; -}; - -} // end of namespace Assimp - -#endif // AI_SKELETONMESHBUILDER_H_INC diff --git a/tools/ZAPD/lib/assimp/include/assimp/SmoothingGroups.h b/tools/ZAPD/lib/assimp/include/assimp/SmoothingGroups.h deleted file mode 100644 index 92d65cea02..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/SmoothingGroups.h +++ /dev/null @@ -1,108 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ - -/** @file Defines the helper data structures for importing 3DS files. -http://www.jalix.org/ressources/graphics/3DS/_unofficials/3ds-unofficial.txt */ - -#ifndef AI_SMOOTHINGGROUPS_H_INC -#define AI_SMOOTHINGGROUPS_H_INC - -#include -#include -#include - -// --------------------------------------------------------------------------- -/** Helper structure representing a face with smoothing groups assigned */ -struct FaceWithSmoothingGroup { - FaceWithSmoothingGroup() AI_NO_EXCEPT - : mIndices() - , iSmoothGroup(0) { - // in debug builds set all indices to a common magic value -#ifdef ASSIMP_BUILD_DEBUG - this->mIndices[0] = 0xffffffff; - this->mIndices[1] = 0xffffffff; - this->mIndices[2] = 0xffffffff; -#endif - } - - - //! Indices. .3ds is using uint16. However, after - //! an unique vertex set has been generated, - //! individual index values might exceed 2^16 - uint32_t mIndices[3]; - - //! specifies to which smoothing group the face belongs to - uint32_t iSmoothGroup; -}; - -// --------------------------------------------------------------------------- -/** Helper structure representing a mesh whose faces have smoothing - groups assigned. This allows us to reuse the code for normal computations - from smoothings groups for several loaders (3DS, ASE). All of them - use face structures which inherit from #FaceWithSmoothingGroup, - but as they add extra members and need to be copied by value we - need to use a template here. - */ -template -struct MeshWithSmoothingGroups -{ - //! Vertex positions - std::vector mPositions; - - //! Face lists - std::vector mFaces; - - //! List of normal vectors - std::vector mNormals; -}; - -// --------------------------------------------------------------------------- -/** Computes normal vectors for the mesh - */ -template -void ComputeNormalsWithSmoothingsGroups(MeshWithSmoothingGroups& sMesh); - - -// include implementations -#include "SmoothingGroups.inl" - -#endif // !! AI_SMOOTHINGGROUPS_H_INC diff --git a/tools/ZAPD/lib/assimp/include/assimp/SmoothingGroups.inl b/tools/ZAPD/lib/assimp/include/assimp/SmoothingGroups.inl deleted file mode 100644 index 84ea4a1b00..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/SmoothingGroups.inl +++ /dev/null @@ -1,138 +0,0 @@ -/* ---------------------------------------------------------------------------- -Open Asset Import Library (assimp) ---------------------------------------------------------------------------- - -Copyright (c) 2006-2012, assimp team - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the following -conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------- -*/ - -/** @file Generation of normal vectors basing on smoothing groups */ - -#ifndef AI_SMOOTHINGGROUPS_INL_INCLUDED -#define AI_SMOOTHINGGROUPS_INL_INCLUDED - -// internal headers -#include - -// CRT header -#include - -using namespace Assimp; - -// ------------------------------------------------------------------------------------------------ -template -void ComputeNormalsWithSmoothingsGroups(MeshWithSmoothingGroups& sMesh) -{ - // First generate face normals - sMesh.mNormals.resize(sMesh.mPositions.size(),aiVector3D()); - for( unsigned int a = 0; a < sMesh.mFaces.size(); a++) - { - T& face = sMesh.mFaces[a]; - - aiVector3D* pV1 = &sMesh.mPositions[face.mIndices[0]]; - aiVector3D* pV2 = &sMesh.mPositions[face.mIndices[1]]; - aiVector3D* pV3 = &sMesh.mPositions[face.mIndices[2]]; - - aiVector3D pDelta1 = *pV2 - *pV1; - aiVector3D pDelta2 = *pV3 - *pV1; - aiVector3D vNor = pDelta1 ^ pDelta2; - - for (unsigned int c = 0; c < 3;++c) - sMesh.mNormals[face.mIndices[c]] = vNor; - } - - // calculate the position bounds so we have a reliable epsilon to check position differences against - aiVector3D minVec( 1e10f, 1e10f, 1e10f), maxVec( -1e10f, -1e10f, -1e10f); - for( unsigned int a = 0; a < sMesh.mPositions.size(); a++) - { - minVec.x = std::min( minVec.x, sMesh.mPositions[a].x); - minVec.y = std::min( minVec.y, sMesh.mPositions[a].y); - minVec.z = std::min( minVec.z, sMesh.mPositions[a].z); - maxVec.x = std::max( maxVec.x, sMesh.mPositions[a].x); - maxVec.y = std::max( maxVec.y, sMesh.mPositions[a].y); - maxVec.z = std::max( maxVec.z, sMesh.mPositions[a].z); - } - const float posEpsilon = (maxVec - minVec).Length() * 1e-5f; - std::vector avNormals; - avNormals.resize(sMesh.mNormals.size()); - - // now generate the spatial sort tree - SGSpatialSort sSort; - for( typename std::vector::iterator i = sMesh.mFaces.begin(); - i != sMesh.mFaces.end();++i) - { - for (unsigned int c = 0; c < 3;++c) - sSort.Add(sMesh.mPositions[(*i).mIndices[c]],(*i).mIndices[c],(*i).iSmoothGroup); - } - sSort.Prepare(); - - std::vector vertexDone(sMesh.mPositions.size(),false); - for( typename std::vector::iterator i = sMesh.mFaces.begin(); - i != sMesh.mFaces.end();++i) - { - std::vector poResult; - for (unsigned int c = 0; c < 3;++c) - { - unsigned int idx = (*i).mIndices[c]; - if (vertexDone[idx])continue; - - sSort.FindPositions(sMesh.mPositions[idx],(*i).iSmoothGroup, - posEpsilon,poResult); - - aiVector3D vNormals; - for (std::vector::const_iterator - a = poResult.begin(); - a != poResult.end();++a) - { - vNormals += sMesh.mNormals[(*a)]; - } - vNormals.NormalizeSafe(); - - // write back into all affected normals - for (std::vector::const_iterator - a = poResult.begin(); - a != poResult.end();++a) - { - idx = *a; - avNormals [idx] = vNormals; - vertexDone[idx] = true; - } - } - } - sMesh.mNormals = avNormals; -} - -#endif // !! AI_SMOOTHINGGROUPS_INL_INCLUDED diff --git a/tools/ZAPD/lib/assimp/include/assimp/SpatialSort.h b/tools/ZAPD/lib/assimp/include/assimp/SpatialSort.h deleted file mode 100644 index 61b345bcbf..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/SpatialSort.h +++ /dev/null @@ -1,174 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ - -/** Small helper classes to optimise finding vertizes close to a given location */ -#ifndef AI_SPATIALSORT_H_INC -#define AI_SPATIALSORT_H_INC - -#include -#include - -namespace Assimp { - -// ------------------------------------------------------------------------------------------------ -/** A little helper class to quickly find all vertices in the epsilon environment of a given - * position. Construct an instance with an array of positions. The class stores the given positions - * by their indices and sorts them by their distance to an arbitrary chosen plane. - * You can then query the instance for all vertices close to a given position in an average O(log n) - * time, with O(n) worst case complexity when all vertices lay on the plane. The plane is chosen - * so that it avoids common planes in usual data sets. */ -// ------------------------------------------------------------------------------------------------ -class ASSIMP_API SpatialSort -{ -public: - - SpatialSort(); - - // ------------------------------------------------------------------------------------ - /** Constructs a spatially sorted representation from the given position array. - * Supply the positions in its layout in memory, the class will only refer to them - * by index. - * @param pPositions Pointer to the first position vector of the array. - * @param pNumPositions Number of vectors to expect in that array. - * @param pElementOffset Offset in bytes from the beginning of one vector in memory - * to the beginning of the next vector. */ - SpatialSort( const aiVector3D* pPositions, unsigned int pNumPositions, - unsigned int pElementOffset); - - /** Destructor */ - ~SpatialSort(); - -public: - - // ------------------------------------------------------------------------------------ - /** Sets the input data for the SpatialSort. This replaces existing data, if any. - * The new data receives new indices in ascending order. - * - * @param pPositions Pointer to the first position vector of the array. - * @param pNumPositions Number of vectors to expect in that array. - * @param pElementOffset Offset in bytes from the beginning of one vector in memory - * to the beginning of the next vector. - * @param pFinalize Specifies whether the SpatialSort's internal representation - * is finalized after the new data has been added. Finalization is - * required in order to use #FindPosition() or #GenerateMappingTable(). - * If you don't finalize yet, you can use #Append() to add data from - * other sources.*/ - void Fill( const aiVector3D* pPositions, unsigned int pNumPositions, - unsigned int pElementOffset, - bool pFinalize = true); - - - // ------------------------------------------------------------------------------------ - /** Same as #Fill(), except the method appends to existing data in the #SpatialSort. */ - void Append( const aiVector3D* pPositions, unsigned int pNumPositions, - unsigned int pElementOffset, - bool pFinalize = true); - - - // ------------------------------------------------------------------------------------ - /** Finalize the spatial hash data structure. This can be useful after - * multiple calls to #Append() with the pFinalize parameter set to false. - * This is finally required before one of #FindPositions() and #GenerateMappingTable() - * can be called to query the spatial sort.*/ - void Finalize(); - - // ------------------------------------------------------------------------------------ - /** Returns an iterator for all positions close to the given position. - * @param pPosition The position to look for vertices. - * @param pRadius Maximal distance from the position a vertex may have to be counted in. - * @param poResults The container to store the indices of the found positions. - * Will be emptied by the call so it may contain anything. - * @return An iterator to iterate over all vertices in the given area.*/ - void FindPositions( const aiVector3D& pPosition, ai_real pRadius, - std::vector& poResults) const; - - // ------------------------------------------------------------------------------------ - /** Fills an array with indices of all positions identical to the given position. In - * opposite to FindPositions(), not an epsilon is used but a (very low) tolerance of - * four floating-point units. - * @param pPosition The position to look for vertices. - * @param poResults The container to store the indices of the found positions. - * Will be emptied by the call so it may contain anything.*/ - void FindIdenticalPositions( const aiVector3D& pPosition, - std::vector& poResults) const; - - // ------------------------------------------------------------------------------------ - /** Compute a table that maps each vertex ID referring to a spatially close - * enough position to the same output ID. Output IDs are assigned in ascending order - * from 0...n. - * @param fill Will be filled with numPositions entries. - * @param pRadius Maximal distance from the position a vertex may have to - * be counted in. - * @return Number of unique vertices (n). */ - unsigned int GenerateMappingTable(std::vector& fill, - ai_real pRadius) const; - -protected: - /** Normal of the sorting plane, normalized. The center is always at (0, 0, 0) */ - aiVector3D mPlaneNormal; - - /** An entry in a spatially sorted position array. Consists of a vertex index, - * its position and its pre-calculated distance from the reference plane */ - struct Entry { - unsigned int mIndex; ///< The vertex referred by this entry - aiVector3D mPosition; ///< Position - ai_real mDistance; ///< Distance of this vertex to the sorting plane - - Entry() AI_NO_EXCEPT - : mIndex( 999999999 ), mPosition(), mDistance( 99999. ) { - // empty - } - Entry( unsigned int pIndex, const aiVector3D& pPosition, ai_real pDistance) - : mIndex( pIndex), mPosition( pPosition), mDistance( pDistance) { - // empty - } - - bool operator < (const Entry& e) const { return mDistance < e.mDistance; } - }; - - // all positions, sorted by distance to the sorting plane - std::vector mPositions; -}; - -} // end of namespace Assimp - -#endif // AI_SPATIALSORT_H_INC diff --git a/tools/ZAPD/lib/assimp/include/assimp/StandardShapes.h b/tools/ZAPD/lib/assimp/include/assimp/StandardShapes.h deleted file mode 100644 index 3791569b83..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/StandardShapes.h +++ /dev/null @@ -1,200 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ - -/** @file Declares a helper class, "StandardShapes" which generates - * vertices for standard shapes, such as cylnders, cones, spheres .. - */ -#ifndef AI_STANDARD_SHAPES_H_INC -#define AI_STANDARD_SHAPES_H_INC - -#include -#include - -struct aiMesh; - -namespace Assimp { - -// --------------------------------------------------------------------------- -/** \brief Helper class to generate vertex buffers for standard geometric - * shapes, such as cylinders, cones, boxes, spheres, elipsoids ... . - */ -class ASSIMP_API StandardShapes -{ - // class cannot be instanced - StandardShapes() {} - -public: - - - // ---------------------------------------------------------------- - /** Generates a mesh from an array of vertex positions. - * - * @param positions List of vertex positions - * @param numIndices Number of indices per primitive - * @return Output mesh - */ - static aiMesh* MakeMesh(const std::vector& positions, - unsigned int numIndices); - - - static aiMesh* MakeMesh ( unsigned int (*GenerateFunc) - (std::vector&)); - - static aiMesh* MakeMesh ( unsigned int (*GenerateFunc) - (std::vector&, bool)); - - static aiMesh* MakeMesh ( unsigned int n, void (*GenerateFunc) - (unsigned int,std::vector&)); - - // ---------------------------------------------------------------- - /** @brief Generates a hexahedron (cube) - * - * Hexahedrons can be scaled on all axes. - * @param positions Receives output triangles. - * @param polygons If you pass true here quads will be returned - * @return Number of vertices per face - */ - static unsigned int MakeHexahedron( - std::vector& positions, - bool polygons = false); - - // ---------------------------------------------------------------- - /** @brief Generates an icosahedron - * - * @param positions Receives output triangles. - * @return Number of vertices per face - */ - static unsigned int MakeIcosahedron( - std::vector& positions); - - - // ---------------------------------------------------------------- - /** @brief Generates a dodecahedron - * - * @param positions Receives output triangles - * @param polygons If you pass true here pentagons will be returned - * @return Number of vertices per face - */ - static unsigned int MakeDodecahedron( - std::vector& positions, - bool polygons = false); - - - // ---------------------------------------------------------------- - /** @brief Generates an octahedron - * - * @param positions Receives output triangles. - * @return Number of vertices per face - */ - static unsigned int MakeOctahedron( - std::vector& positions); - - - // ---------------------------------------------------------------- - /** @brief Generates a tetrahedron - * - * @param positions Receives output triangles. - * @return Number of vertices per face - */ - static unsigned int MakeTetrahedron( - std::vector& positions); - - - - // ---------------------------------------------------------------- - /** @brief Generates a sphere - * - * @param tess Number of subdivions - 0 generates a octahedron - * @param positions Receives output triangles. - */ - static void MakeSphere(unsigned int tess, - std::vector& positions); - - - // ---------------------------------------------------------------- - /** @brief Generates a cone or a cylinder, either open or closed. - * - * @code - * - * |-----| <- radius 1 - * - * __x__ <- ] ^ - * / \ | height | - * / \ | Y - * / \ | - * / \ | - * /______x______\ <- ] <- end cap - * - * |-------------| <- radius 2 - * - * @endcode - * - * @param height Height of the cone - * @param radius1 First radius - * @param radius2 Second radius - * @param tess Number of triangles. - * @param bOpened true for an open cone/cylinder. An open shape has - * no 'end caps' - * @param positions Receives output triangles - */ - static void MakeCone(ai_real height,ai_real radius1, - ai_real radius2,unsigned int tess, - std::vector& positions,bool bOpen= false); - - - // ---------------------------------------------------------------- - /** @brief Generates a flat circle - * - * The circle is constructed in the planned formed by the x,z - * axes of the cartesian coordinate system. - * - * @param radius Radius of the circle - * @param tess Number of segments. - * @param positions Receives output triangles. - */ - static void MakeCircle(ai_real radius, unsigned int tess, - std::vector& positions); - -}; -} // ! Assimp - -#endif // !! AI_STANDARD_SHAPES_H_INC diff --git a/tools/ZAPD/lib/assimp/include/assimp/StreamReader.h b/tools/ZAPD/lib/assimp/include/assimp/StreamReader.h deleted file mode 100644 index 9116c14261..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/StreamReader.h +++ /dev/null @@ -1,343 +0,0 @@ -/* ---------------------------------------------------------------------------- -Open Asset Import Library (assimp) ---------------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the following -conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------- -*/ - -/** @file Defines the StreamReader class which reads data from - * a binary stream with a well-defined endianness. - */ - -#ifndef AI_STREAMREADER_H_INCLUDED -#define AI_STREAMREADER_H_INCLUDED - -#include -#include - -#include "ByteSwapper.h" -#include "Exceptional.h" -#include - -namespace Assimp { - -// -------------------------------------------------------------------------------------------- -/** Wrapper class around IOStream to allow for consistent reading of binary data in both - * little and big endian format. Don't attempt to instance the template directly. Use - * StreamReaderLE to read from a little-endian stream and StreamReaderBE to read from a - * BE stream. The class expects that the endianness of any input data is known at - * compile-time, which should usually be true (#BaseImporter::ConvertToUTF8 implements - * runtime endianness conversions for text files). - * - * XXX switch from unsigned int for size types to size_t? or ptrdiff_t?*/ -// -------------------------------------------------------------------------------------------- -template -class StreamReader { -public: - // FIXME: use these data types throughout the whole library, - // then change them to 64 bit values :-) - using diff = int; - using pos = unsigned int; - - // --------------------------------------------------------------------- - /** Construction from a given stream with a well-defined endianness. - * - * The StreamReader holds a permanent strong reference to the - * stream, which is released upon destruction. - * @param stream Input stream. The stream is not restarted if - * its file pointer is not at 0. Instead, the stream reader - * reads from the current position to the end of the stream. - * @param le If @c RuntimeSwitch is true: specifies whether the - * stream is in little endian byte order. Otherwise the - * endianness information is contained in the @c SwapEndianess - * template parameter and this parameter is meaningless. */ - StreamReader(std::shared_ptr stream, bool le = false) - : stream(stream) - , le(le) - { - ai_assert(stream); - InternBegin(); - } - - // --------------------------------------------------------------------- - StreamReader(IOStream* stream, bool le = false) - : stream(std::shared_ptr(stream)) - , le(le) - { - ai_assert(stream); - InternBegin(); - } - - // --------------------------------------------------------------------- - ~StreamReader() { - delete[] buffer; - } - - // deprecated, use overloaded operator>> instead - - // --------------------------------------------------------------------- - /** Read a float from the stream */ - float GetF4() - { - return Get(); - } - - // --------------------------------------------------------------------- - /** Read a double from the stream */ - double GetF8() { - return Get(); - } - - // --------------------------------------------------------------------- - /** Read a signed 16 bit integer from the stream */ - int16_t GetI2() { - return Get(); - } - - // --------------------------------------------------------------------- - /** Read a signed 8 bit integer from the stream */ - int8_t GetI1() { - return Get(); - } - - // --------------------------------------------------------------------- - /** Read an signed 32 bit integer from the stream */ - int32_t GetI4() { - return Get(); - } - - // --------------------------------------------------------------------- - /** Read a signed 64 bit integer from the stream */ - int64_t GetI8() { - return Get(); - } - - // --------------------------------------------------------------------- - /** Read a unsigned 16 bit integer from the stream */ - uint16_t GetU2() { - return Get(); - } - - // --------------------------------------------------------------------- - /** Read a unsigned 8 bit integer from the stream */ - uint8_t GetU1() { - return Get(); - } - - // --------------------------------------------------------------------- - /** Read an unsigned 32 bit integer from the stream */ - uint32_t GetU4() { - return Get(); - } - - // --------------------------------------------------------------------- - /** Read a unsigned 64 bit integer from the stream */ - uint64_t GetU8() { - return Get(); - } - - // --------------------------------------------------------------------- - /** Get the remaining stream size (to the end of the stream) */ - unsigned int GetRemainingSize() const { - return (unsigned int)(end - current); - } - - // --------------------------------------------------------------------- - /** Get the remaining stream size (to the current read limit). The - * return value is the remaining size of the stream if no custom - * read limit has been set. */ - unsigned int GetRemainingSizeToLimit() const { - return (unsigned int)(limit - current); - } - - // --------------------------------------------------------------------- - /** Increase the file pointer (relative seeking) */ - void IncPtr(intptr_t plus) { - current += plus; - if (current > limit) { - throw DeadlyImportError("End of file or read limit was reached"); - } - } - - // --------------------------------------------------------------------- - /** Get the current file pointer */ - int8_t* GetPtr() const { - return current; - } - - // --------------------------------------------------------------------- - /** Set current file pointer (Get it from #GetPtr). This is if you - * prefer to do pointer arithmetics on your own or want to copy - * large chunks of data at once. - * @param p The new pointer, which is validated against the size - * limit and buffer boundaries. */ - void SetPtr(int8_t* p) { - current = p; - if (current > limit || current < buffer) { - throw DeadlyImportError("End of file or read limit was reached"); - } - } - - // --------------------------------------------------------------------- - /** Copy n bytes to an external buffer - * @param out Destination for copying - * @param bytes Number of bytes to copy */ - void CopyAndAdvance(void* out, size_t bytes) { - int8_t* ur = GetPtr(); - SetPtr(ur+bytes); // fire exception if eof - - ::memcpy(out,ur,bytes); - } - - // --------------------------------------------------------------------- - /** Get the current offset from the beginning of the file */ - int GetCurrentPos() const { - return (unsigned int)(current - buffer); - } - - void SetCurrentPos(size_t pos) { - SetPtr(buffer + pos); - } - - // --------------------------------------------------------------------- - /** Setup a temporary read limit - * - * @param limit Maximum number of bytes to be read from - * the beginning of the file. Specifying UINT_MAX - * resets the limit to the original end of the stream. - * Returns the previously set limit. */ - unsigned int SetReadLimit(unsigned int _limit) { - unsigned int prev = GetReadLimit(); - if (UINT_MAX == _limit) { - limit = end; - return prev; - } - - limit = buffer + _limit; - if (limit > end) { - throw DeadlyImportError("StreamReader: Invalid read limit"); - } - return prev; - } - - // --------------------------------------------------------------------- - /** Get the current read limit in bytes. Reading over this limit - * accidentally raises an exception. */ - unsigned int GetReadLimit() const { - return (unsigned int)(limit - buffer); - } - - // --------------------------------------------------------------------- - /** Skip to the read limit in bytes. Reading over this limit - * accidentally raises an exception. */ - void SkipToReadLimit() { - current = limit; - } - - // --------------------------------------------------------------------- - /** overload operator>> and allow chaining of >> ops. */ - template - StreamReader& operator >> (T& f) { - f = Get(); - return *this; - } - - // --------------------------------------------------------------------- - /** Generic read method. ByteSwap::Swap(T*) *must* be defined */ - template - T Get() { - if ( current + sizeof(T) > limit) { - throw DeadlyImportError("End of file or stream limit was reached"); - } - - T f; - ::memcpy (&f, current, sizeof(T)); - Intern::Getter() (&f,le); - current += sizeof(T); - - return f; - } - -private: - // --------------------------------------------------------------------- - void InternBegin() { - if (!stream) { - // in case someone wonders: StreamReader is frequently invoked with - // no prior validation whether the input stream is valid. Since - // no one bothers changing the error message, this message here - // is passed down to the caller and 'unable to open file' - // simply describes best what happened. - throw DeadlyImportError("StreamReader: Unable to open file"); - } - - const size_t s = stream->FileSize() - stream->Tell(); - if (!s) { - throw DeadlyImportError("StreamReader: File is empty or EOF is already reached"); - } - - current = buffer = new int8_t[s]; - const size_t read = stream->Read(current,1,s); - // (read < s) can only happen if the stream was opened in text mode, in which case FileSize() is not reliable - ai_assert(read <= s); - end = limit = &buffer[read-1] + 1; - } - -private: - std::shared_ptr stream; - int8_t *buffer, *current, *end, *limit; - bool le; -}; - -// -------------------------------------------------------------------------------------------- -// `static` StreamReaders. Their byte order is fixed and they might be a little bit faster. -#ifdef AI_BUILD_BIG_ENDIAN - typedef StreamReader StreamReaderLE; - typedef StreamReader StreamReaderBE; -#else - typedef StreamReader StreamReaderBE; - typedef StreamReader StreamReaderLE; -#endif - -// `dynamic` StreamReader. The byte order of the input data is specified in the -// c'tor. This involves runtime branching and might be a little bit slower. -typedef StreamReader StreamReaderAny; - -} // end namespace Assimp - -#endif // !! AI_STREAMREADER_H_INCLUDED diff --git a/tools/ZAPD/lib/assimp/include/assimp/StreamWriter.h b/tools/ZAPD/lib/assimp/include/assimp/StreamWriter.h deleted file mode 100644 index c7cf6c0d74..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/StreamWriter.h +++ /dev/null @@ -1,303 +0,0 @@ -/* ---------------------------------------------------------------------------- -Open Asset Import Library (assimp) ---------------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the following -conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------- -*/ - -/** @file Defines the StreamWriter class which writes data to - * a binary stream with a well-defined endianness. */ - -#ifndef AI_STREAMWRITER_H_INCLUDED -#define AI_STREAMWRITER_H_INCLUDED - -#include "ByteSwapper.h" -#include - -#include -#include - -namespace Assimp { - -// -------------------------------------------------------------------------------------------- -/** Wrapper class around IOStream to allow for consistent writing of binary data in both - * little and big endian format. Don't attempt to instance the template directly. Use - * StreamWriterLE to write to a little-endian stream and StreamWriterBE to write to a - * BE stream. Alternatively, there is StreamWriterAny if the endianness of the output - * stream is to be determined at runtime. - */ -// -------------------------------------------------------------------------------------------- -template -class StreamWriter -{ - enum { - INITIAL_CAPACITY = 1024 - }; - -public: - - // --------------------------------------------------------------------- - /** Construction from a given stream with a well-defined endianness. - * - * The StreamReader holds a permanent strong reference to the - * stream, which is released upon destruction. - * @param stream Input stream. The stream is not re-seeked and writing - continues at the current position of the stream cursor. - * @param le If @c RuntimeSwitch is true: specifies whether the - * stream is in little endian byte order. Otherwise the - * endianness information is defined by the @c SwapEndianess - * template parameter and this parameter is meaningless. */ - StreamWriter(std::shared_ptr stream, bool le = false) - : stream(stream) - , le(le) - , cursor() - { - ai_assert(stream); - buffer.reserve(INITIAL_CAPACITY); - } - - // --------------------------------------------------------------------- - StreamWriter(IOStream* stream, bool le = false) - : stream(std::shared_ptr(stream)) - , le(le) - , cursor() - { - ai_assert(stream); - buffer.reserve(INITIAL_CAPACITY); - } - - // --------------------------------------------------------------------- - ~StreamWriter() { - stream->Write(buffer.data(), 1, buffer.size()); - stream->Flush(); - } - -public: - - // --------------------------------------------------------------------- - /** Flush the contents of the internal buffer, and the output IOStream */ - void Flush() - { - stream->Write(buffer.data(), 1, buffer.size()); - stream->Flush(); - buffer.clear(); - cursor = 0; - } - - // --------------------------------------------------------------------- - /** Seek to the given offset / origin in the output IOStream. - * - * Flushes the internal buffer and the output IOStream prior to seeking. */ - aiReturn Seek(size_t pOffset, aiOrigin pOrigin=aiOrigin_SET) - { - Flush(); - return stream->Seek(pOffset, pOrigin); - } - - // --------------------------------------------------------------------- - /** Tell the current position in the output IOStream. - * - * First flushes the internal buffer and the output IOStream. */ - size_t Tell() - { - Flush(); - return stream->Tell(); - } - -public: - - // --------------------------------------------------------------------- - /** Write a float to the stream */ - void PutF4(float f) - { - Put(f); - } - - // --------------------------------------------------------------------- - /** Write a double to the stream */ - void PutF8(double d) { - Put(d); - } - - // --------------------------------------------------------------------- - /** Write a signed 16 bit integer to the stream */ - void PutI2(int16_t n) { - Put(n); - } - - // --------------------------------------------------------------------- - /** Write a signed 8 bit integer to the stream */ - void PutI1(int8_t n) { - Put(n); - } - - // --------------------------------------------------------------------- - /** Write an signed 32 bit integer to the stream */ - void PutI4(int32_t n) { - Put(n); - } - - // --------------------------------------------------------------------- - /** Write a signed 64 bit integer to the stream */ - void PutI8(int64_t n) { - Put(n); - } - - // --------------------------------------------------------------------- - /** Write a unsigned 16 bit integer to the stream */ - void PutU2(uint16_t n) { - Put(n); - } - - // --------------------------------------------------------------------- - /** Write a unsigned 8 bit integer to the stream */ - void PutU1(uint8_t n) { - Put(n); - } - - // --------------------------------------------------------------------- - /** Write an unsigned 32 bit integer to the stream */ - void PutU4(uint32_t n) { - Put(n); - } - - // --------------------------------------------------------------------- - /** Write a unsigned 64 bit integer to the stream */ - void PutU8(uint64_t n) { - Put(n); - } - - // --------------------------------------------------------------------- - /** Write a single character to the stream */ - void PutChar(char c) { - Put(c); - } - - // --------------------------------------------------------------------- - /** Write an aiString to the stream */ - void PutString(const aiString& s) - { - // as Put(T f) below - if (cursor + s.length >= buffer.size()) { - buffer.resize(cursor + s.length); - } - void* dest = &buffer[cursor]; - ::memcpy(dest, s.C_Str(), s.length); - cursor += s.length; - } - - // --------------------------------------------------------------------- - /** Write a std::string to the stream */ - void PutString(const std::string& s) - { - // as Put(T f) below - if (cursor + s.size() >= buffer.size()) { - buffer.resize(cursor + s.size()); - } - void* dest = &buffer[cursor]; - ::memcpy(dest, s.c_str(), s.size()); - cursor += s.size(); - } - -public: - - // --------------------------------------------------------------------- - /** overload operator<< and allow chaining of MM ops. */ - template - StreamWriter& operator << (T f) { - Put(f); - return *this; - } - - // --------------------------------------------------------------------- - std::size_t GetCurrentPos() const { - return cursor; - } - - // --------------------------------------------------------------------- - void SetCurrentPos(std::size_t new_cursor) { - cursor = new_cursor; - } - - // --------------------------------------------------------------------- - /** Generic write method. ByteSwap::Swap(T*) *must* be defined */ - template - void Put(T f) { - Intern :: Getter() (&f, le); - - if (cursor + sizeof(T) >= buffer.size()) { - buffer.resize(cursor + sizeof(T)); - } - - void* dest = &buffer[cursor]; - - // reinterpret_cast + assignment breaks strict aliasing rules - // and generally causes trouble on platforms such as ARM that - // do not silently ignore alignment faults. - ::memcpy(dest, &f, sizeof(T)); - cursor += sizeof(T); - } - -private: - - std::shared_ptr stream; - bool le; - - std::vector buffer; - std::size_t cursor; -}; - - -// -------------------------------------------------------------------------------------------- -// `static` StreamWriter. Their byte order is fixed and they might be a little bit faster. -#ifdef AI_BUILD_BIG_ENDIAN - typedef StreamWriter StreamWriterLE; - typedef StreamWriter StreamWriterBE; -#else - typedef StreamWriter StreamWriterBE; - typedef StreamWriter StreamWriterLE; -#endif - -// `dynamic` StreamWriter. The byte order of the input data is specified in the -// c'tor. This involves runtime branching and might be a little bit slower. -typedef StreamWriter StreamWriterAny; - -} // end namespace Assimp - -#endif // !! AI_STREAMWriter_H_INCLUDED diff --git a/tools/ZAPD/lib/assimp/include/assimp/StringComparison.h b/tools/ZAPD/lib/assimp/include/assimp/StringComparison.h deleted file mode 100644 index 8acef277b9..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/StringComparison.h +++ /dev/null @@ -1,233 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ - -/** @file Definition of platform independent string workers: - - ASSIMP_itoa10 - ASSIMP_stricmp - ASSIMP_strincmp - - These functions are not consistently available on all platforms, - or the provided implementations behave too differently. -*/ -#ifndef INCLUDED_AI_STRING_WORKERS_H -#define INCLUDED_AI_STRING_WORKERS_H - -#include -#include -#include "StringComparison.h" - -#include -#include -#include - -namespace Assimp { - -// ------------------------------------------------------------------------------- -/** @brief itoa with a fixed base 10 - * 'itoa' is not consistently available on all platforms so it is quite useful - * to have a small replacement function here. No need to use a full sprintf() - * if we just want to print a number ... - * @param out Output buffer - * @param max Maximum number of characters to be written, including '\0'. - * This parameter may not be 0. - * @param number Number to be written - * @return Length of the output string, excluding the '\0' - */ -AI_FORCE_INLINE -unsigned int ASSIMP_itoa10( char* out, unsigned int max, int32_t number) { - ai_assert(NULL != out); - - // write the unary minus to indicate we have a negative number - unsigned int written = 1u; - if (number < 0 && written < max) { - *out++ = '-'; - ++written; - number = -number; - } - - // We begin with the largest number that is not zero. - int32_t cur = 1000000000; // 2147483648 - bool mustPrint = false; - while (written < max) { - - const unsigned int digit = number / cur; - if (mustPrint || digit > 0 || 1 == cur) { - // print all future zeroe's from now - mustPrint = true; - - *out++ = '0'+static_cast(digit); - - ++written; - number -= digit*cur; - if (1 == cur) { - break; - } - } - cur /= 10; - } - - // append a terminal zero - *out++ = '\0'; - return written-1; -} - -// ------------------------------------------------------------------------------- -/** @brief itoa with a fixed base 10 (Secure template overload) - * The compiler should choose this function if he or she is able to determine the - * size of the array automatically. - */ -template -AI_FORCE_INLINE -unsigned int ASSIMP_itoa10( char(& out)[length], int32_t number) { - return ASSIMP_itoa10(out,length,number); -} - -// ------------------------------------------------------------------------------- -/** @brief Helper function to do platform independent string comparison. - * - * This is required since stricmp() is not consistently available on - * all platforms. Some platforms use the '_' prefix, others don't even - * have such a function. - * - * @param s1 First input string - * @param s2 Second input string - * @return 0 if the given strings are identical - */ -AI_FORCE_INLINE -int ASSIMP_stricmp(const char *s1, const char *s2) { - ai_assert( NULL != s1 ); - ai_assert( NULL != s2 ); - -#if (defined _MSC_VER) - - return ::_stricmp(s1,s2); -#elif defined( __GNUC__ ) - - return ::strcasecmp(s1,s2); -#else - - char c1, c2; - do { - c1 = tolower(*s1++); - c2 = tolower(*s2++); - } - while ( c1 && (c1 == c2) ); - return c1 - c2; -#endif -} - -// ------------------------------------------------------------------------------- -/** @brief Case independent comparison of two std::strings - * - * @param a First string - * @param b Second string - * @return 0 if a == b - */ -AI_FORCE_INLINE -int ASSIMP_stricmp(const std::string& a, const std::string& b) { - int i = (int)b.length()-(int)a.length(); - return (i ? i : ASSIMP_stricmp(a.c_str(),b.c_str())); -} - -// ------------------------------------------------------------------------------- -/** @brief Helper function to do platform independent string comparison. - * - * This is required since strincmp() is not consistently available on - * all platforms. Some platforms use the '_' prefix, others don't even - * have such a function. - * - * @param s1 First input string - * @param s2 Second input string - * @param n Macimum number of characters to compare - * @return 0 if the given strings are identical - */ -AI_FORCE_INLINE -int ASSIMP_strincmp(const char *s1, const char *s2, unsigned int n) { - ai_assert( NULL != s1 ); - ai_assert( NULL != s2 ); - if ( !n ) { - return 0; - } - -#if (defined _MSC_VER) - - return ::_strnicmp(s1,s2,n); - -#elif defined( __GNUC__ ) - - return ::strncasecmp(s1,s2, n); - -#else - char c1, c2; - unsigned int p = 0; - do - { - if (p++ >= n)return 0; - c1 = tolower(*s1++); - c2 = tolower(*s2++); - } - while ( c1 && (c1 == c2) ); - - return c1 - c2; -#endif -} - - -// ------------------------------------------------------------------------------- -/** @brief Evaluates an integer power - * - * todo: move somewhere where it fits better in than here - */ -AI_FORCE_INLINE -unsigned int integer_pow( unsigned int base, unsigned int power ) { - unsigned int res = 1; - for ( unsigned int i = 0; i < power; ++i ) { - res *= base; - } - - return res; -} - -} // end of namespace - -#endif // ! AI_STRINGCOMPARISON_H_INC diff --git a/tools/ZAPD/lib/assimp/include/assimp/StringUtils.h b/tools/ZAPD/lib/assimp/include/assimp/StringUtils.h deleted file mode 100644 index d68b7fa479..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/StringUtils.h +++ /dev/null @@ -1,143 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above -copyright notice, this list of conditions and the -following disclaimer. - -* Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the -following disclaimer in the documentation and/or other -materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its -contributors may be used to endorse or promote products -derived from this software without specific prior -written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ -#ifndef INCLUDED_AI_STRINGUTILS_H -#define INCLUDED_AI_STRINGUTILS_H - -#include - -#include -#include -#include - -/// @fn ai_snprintf -/// @brief The portable version of the function snprintf ( C99 standard ), which works on visual studio compilers 2013 and earlier. -/// @param outBuf The buffer to write in -/// @param size The buffer size -/// @param format The format string -/// @param ap The additional arguments. -/// @return The number of written characters if the buffer size was big enough. If an encoding error occurs, a negative number is returned. -#if defined(_MSC_VER) && _MSC_VER < 1900 - - AI_FORCE_INLINE - int c99_ai_vsnprintf(char *outBuf, size_t size, const char *format, va_list ap) { - int count(-1); - if (0 != size) { - count = _vsnprintf_s(outBuf, size, _TRUNCATE, format, ap); - } - if (count == -1) { - count = _vscprintf(format, ap); - } - - return count; - } - - AI_FORCE_INLINE - int ai_snprintf(char *outBuf, size_t size, const char *format, ...) { - int count; - va_list ap; - - va_start(ap, format); - count = c99_ai_vsnprintf(outBuf, size, format, ap); - va_end(ap); - - return count; - } - -#else -# define ai_snprintf snprintf -#endif - -/// @fn to_string -/// @brief The portable version of to_string ( some gcc-versions on embedded devices are not supporting this). -/// @param value The value to write into the std::string. -/// @return The value as a std::string -template -AI_FORCE_INLINE -std::string to_string( T value ) { - std::ostringstream os; - os << value; - - return os.str(); -} - -/// @fn ai_strtof -/// @brief The portable version of strtof. -/// @param begin The first character of the string. -/// @param end The last character -/// @return The float value, 0.0f in cas of an error. -AI_FORCE_INLINE -float ai_strtof( const char *begin, const char *end ) { - if ( nullptr == begin ) { - return 0.0f; - } - float val( 0.0f ); - if ( nullptr == end ) { - val = static_cast< float >( ::atof( begin ) ); - } else { - std::string::size_type len( end - begin ); - std::string token( begin, len ); - val = static_cast< float >( ::atof( token.c_str() ) ); - } - - return val; -} - -/// @fn DecimalToHexa -/// @brief The portable to convert a decimal value into a hexadecimal string. -/// @param toConvert Value to convert -/// @return The hexadecimal string, is empty in case of an error. -template -AI_FORCE_INLINE -std::string DecimalToHexa( T toConvert ) { - std::string result; - std::stringstream ss; - ss << std::hex << toConvert; - ss >> result; - - for ( size_t i = 0; i < result.size(); ++i ) { - result[ i ] = toupper( result[ i ] ); - } - - return result; -} - -#endif // INCLUDED_AI_STRINGUTILS_H diff --git a/tools/ZAPD/lib/assimp/include/assimp/Subdivision.h b/tools/ZAPD/lib/assimp/include/assimp/Subdivision.h deleted file mode 100644 index 43feb73b30..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/Subdivision.h +++ /dev/null @@ -1,131 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ - -/** @file Defines a helper class to evaluate subdivision surfaces.*/ -#pragma once -#ifndef AI_SUBDISIVION_H_INC -#define AI_SUBDISIVION_H_INC - -#include -#include - -struct aiMesh; - -namespace Assimp { - -// ------------------------------------------------------------------------------ -/** Helper class to evaluate subdivision surfaces. Different algorithms - * are provided for choice. */ -// ------------------------------------------------------------------------------ -class ASSIMP_API Subdivider { -public: - - /** Enumerates all supported subvidision algorithms */ - enum Algorithm { - CATMULL_CLARKE = 0x1 - }; - - virtual ~Subdivider(); - - // --------------------------------------------------------------- - /** Create a subdivider of a specific type - * - * @param algo Algorithm to be used for subdivision - * @return Subdivider instance. */ - static Subdivider* Create (Algorithm algo); - - // --------------------------------------------------------------- - /** Subdivide a mesh using the selected algorithm - * - * @param mesh First mesh to be subdivided. Must be in verbose - * format. - * @param out Receives the output mesh, allocated by me. - * @param num Number of subdivisions to perform. - * @param discard_input If true is passed, the input mesh is - * deleted after the subdivision is complete. This can - * improve performance because it allows the optimization - * to reuse the existing mesh for intermediate results. - * @pre out!=mesh*/ - virtual void Subdivide ( aiMesh* mesh, - aiMesh*& out, unsigned int num, - bool discard_input = false) = 0; - - // --------------------------------------------------------------- - /** Subdivide multiple meshes using the selected algorithm. This - * avoids erroneous smoothing on objects consisting of multiple - * per-material meshes. Usually, most 3d modellers smooth on a - * per-object base, regardless the materials assigned to the - * meshes. - * - * @param smesh Array of meshes to be subdivided. Must be in - * verbose format. - * @param nmesh Number of meshes in smesh. - * @param out Receives the output meshes. The array must be - * sufficiently large (at least @c nmesh elements) and may not - * overlap the input array. Output meshes map one-to-one to - * their corresponding input meshes. The meshes are allocated - * by the function. - * @param discard_input If true is passed, input meshes are - * deleted after the subdivision is complete. This can - * improve performance because it allows the optimization - * of reusing existing meshes for intermediate results. - * @param num Number of subdivisions to perform. - * @pre nmesh != 0, smesh and out may not overlap*/ - virtual void Subdivide ( - aiMesh** smesh, - size_t nmesh, - aiMesh** out, - unsigned int num, - bool discard_input = false) = 0; - -}; - -inline -Subdivider::~Subdivider() { - // empty -} - -} // end namespace Assimp - - -#endif // !! AI_SUBDISIVION_H_INC - diff --git a/tools/ZAPD/lib/assimp/include/assimp/TinyFormatter.h b/tools/ZAPD/lib/assimp/include/assimp/TinyFormatter.h deleted file mode 100644 index 1226b482e6..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/TinyFormatter.h +++ /dev/null @@ -1,166 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ - -/** @file TinyFormatter.h - * @brief Utility to format log messages more easily. Introduced - * to get rid of the boost::format dependency. Much slinker, - * basically just extends stringstream. - */ -#ifndef INCLUDED_TINY_FORMATTER_H -#define INCLUDED_TINY_FORMATTER_H - -#include - -namespace Assimp { -namespace Formatter { - -// ------------------------------------------------------------------------------------------------ -/** stringstream utility. Usage: - * @code - * void writelog(const std::string&s); - * void writelog(const std::wstring&s); - * ... - * writelog(format()<< "hi! this is a number: " << 4); - * writelog(wformat()<< L"hi! this is a number: " << 4); - * - * @endcode */ -template < typename T, - typename CharTraits = std::char_traits, - typename Allocator = std::allocator -> -class basic_formatter -{ - -public: - - typedef class std::basic_string< - T,CharTraits,Allocator - > string; - - typedef class std::basic_ostringstream< - T,CharTraits,Allocator - > stringstream; - -public: - - basic_formatter() {} - - /* Allow basic_formatter's to be used almost interchangeably - * with std::(w)string or const (w)char* arguments because the - * conversion c'tor is called implicitly. */ - template - basic_formatter(const TT& sin) { - underlying << sin; - } - - - // The problem described here: - // https://sourceforge.net/tracker/?func=detail&atid=1067632&aid=3358562&group_id=226462 - // can also cause trouble here. Apparently, older gcc versions sometimes copy temporaries - // being bound to const ref& function parameters. Copying streams is not permitted, though. - // This workaround avoids this by manually specifying a copy ctor. -#if !defined(__GNUC__) || !defined(__APPLE__) || __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6) - explicit basic_formatter(const basic_formatter& other) { - underlying << (string)other; - } -#endif - - -public: - - operator string () const { - return underlying.str(); - } - - - /* note - this is declared const because binding temporaries does only - * work for const references, so many function prototypes will - * include const basic_formatter& s but might still want to - * modify the formatted string without the need for a full copy.*/ - template - const basic_formatter& operator << (const TToken& s) const { - underlying << s; - return *this; - } - - template - basic_formatter& operator << (const TToken& s) { - underlying << s; - return *this; - } - - - // comma operator overloaded as well, choose your preferred way. - template - const basic_formatter& operator, (const TToken& s) const { - underlying << s; - return *this; - } - - template - basic_formatter& operator, (const TToken& s) { - underlying << s; - return *this; - } - - // Fix for MSVC8 - // See https://sourceforge.net/projects/assimp/forums/forum/817654/topic/4372824 - template - basic_formatter& operator, (TToken& s) { - underlying << s; - return *this; - } - - -private: - mutable stringstream underlying; -}; - - -typedef basic_formatter< char > format; -typedef basic_formatter< wchar_t > wformat; - -} // ! namespace Formatter - -} // ! namespace Assimp - -#endif diff --git a/tools/ZAPD/lib/assimp/include/assimp/Vertex.h b/tools/ZAPD/lib/assimp/include/assimp/Vertex.h deleted file mode 100644 index 2a7f0256ad..0000000000 --- a/tools/ZAPD/lib/assimp/include/assimp/Vertex.h +++ /dev/null @@ -1,348 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2019, assimp team - - -All rights reserved. - -Redistribution and use of this software in source and binary forms, -with or without modification, are permitted provided that the -following conditions are met: - -* Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other - materials provided with the distribution. - -* Neither the name of the assimp team, nor the names of its - contributors may be used to endorse or promote products - derived from this software without specific prior - written permission of the assimp team. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -*/ -/** @file Defines a helper class to represent an interleaved vertex - along with arithmetic operations to support vertex operations - such as subdivision, smoothing etc. - - While the code is kept as general as possible, arithmetic operations - that are not currently well-defined (and would cause compile errors - due to missing operators in the math library), are commented. - */ -#ifndef AI_VERTEX_H_INC -#define AI_VERTEX_H_INC - -#include -#include -#include -#include - -namespace Assimp { - - /////////////////////////////////////////////////////////////////////////// - // std::plus-family operates on operands with identical types - we need to - // support all the (vectype op float) combinations in vector maths. - // Providing T(float) would open the way to endless implicit conversions. - /////////////////////////////////////////////////////////////////////////// - namespace Intern { - template struct plus { - TRES operator() (const T0& t0, const T1& t1) const { - return t0+t1; - } - }; - template struct minus { - TRES operator() (const T0& t0, const T1& t1) const { - return t0-t1; - } - }; - template struct multiplies { - TRES operator() (const T0& t0, const T1& t1) const { - return t0*t1; - } - }; - template struct divides { - TRES operator() (const T0& t0, const T1& t1) const { - return t0/t1; - } - }; - } - -// ------------------------------------------------------------------------------------------------ -/** Intermediate description a vertex with all possible components. Defines a full set of - * operators, so you may use such a 'Vertex' in basic arithmetics. All operators are applied - * to *all* vertex components equally. This is useful for stuff like interpolation - * or subdivision, but won't work if special handling is required for some vertex components. */ -// ------------------------------------------------------------------------------------------------ -class Vertex -{ - friend Vertex operator + (const Vertex&,const Vertex&); - friend Vertex operator - (const Vertex&,const Vertex&); - -// friend Vertex operator + (const Vertex&,ai_real); -// friend Vertex operator - (const Vertex&,ai_real); - friend Vertex operator * (const Vertex&,ai_real); - friend Vertex operator / (const Vertex&,ai_real); - -// friend Vertex operator + (ai_real, const Vertex&); -// friend Vertex operator - (ai_real, const Vertex&); - friend Vertex operator * (ai_real, const Vertex&); -// friend Vertex operator / (ai_real, const Vertex&); - -public: - - Vertex() {} - - // ---------------------------------------------------------------------------- - /** Extract a particular vertex from a mesh and interleave all components */ - explicit Vertex(const aiMesh* msh, unsigned int idx) { - ai_assert(idx < msh->mNumVertices); - position = msh->mVertices[idx]; - - if (msh->HasNormals()) { - normal = msh->mNormals[idx]; - } - - if (msh->HasTangentsAndBitangents()) { - tangent = msh->mTangents[idx]; - bitangent = msh->mBitangents[idx]; - } - - for (unsigned int i = 0; msh->HasTextureCoords(i); ++i) { - texcoords[i] = msh->mTextureCoords[i][idx]; - } - - for (unsigned int i = 0; msh->HasVertexColors(i); ++i) { - colors[i] = msh->mColors[i][idx]; - } - } - - // ---------------------------------------------------------------------------- - /** Extract a particular vertex from a anim mesh and interleave all components */ - explicit Vertex(const aiAnimMesh* msh, unsigned int idx) { - ai_assert(idx < msh->mNumVertices); - position = msh->mVertices[idx]; - - if (msh->HasNormals()) { - normal = msh->mNormals[idx]; - } - - if (msh->HasTangentsAndBitangents()) { - tangent = msh->mTangents[idx]; - bitangent = msh->mBitangents[idx]; - } - - for (unsigned int i = 0; msh->HasTextureCoords(i); ++i) { - texcoords[i] = msh->mTextureCoords[i][idx]; - } - - for (unsigned int i = 0; msh->HasVertexColors(i); ++i) { - colors[i] = msh->mColors[i][idx]; - } - } - -public: - - Vertex& operator += (const Vertex& v) { - *this = *this+v; - return *this; - } - - Vertex& operator -= (const Vertex& v) { - *this = *this-v; - return *this; - } - - -/* - Vertex& operator += (ai_real v) { - *this = *this+v; - return *this; - } - - Vertex& operator -= (ai_real v) { - *this = *this-v; - return *this; - } -*/ - Vertex& operator *= (ai_real v) { - *this = *this*v; - return *this; - } - - Vertex& operator /= (ai_real v) { - *this = *this/v; - return *this; - } - -public: - - // ---------------------------------------------------------------------------- - /** Convert back to non-interleaved storage */ - void SortBack(aiMesh* out, unsigned int idx) const { - - ai_assert(idxmNumVertices); - out->mVertices[idx] = position; - - if (out->HasNormals()) { - out->mNormals[idx] = normal; - } - - if (out->HasTangentsAndBitangents()) { - out->mTangents[idx] = tangent; - out->mBitangents[idx] = bitangent; - } - - for(unsigned int i = 0; out->HasTextureCoords(i); ++i) { - out->mTextureCoords[i][idx] = texcoords[i]; - } - - for(unsigned int i = 0; out->HasVertexColors(i); ++i) { - out->mColors[i][idx] = colors[i]; - } - } - -private: - - // ---------------------------------------------------------------------------- - /** Construct from two operands and a binary operation to combine them */ - template