diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fce4515 --- /dev/null +++ b/.gitignore @@ -0,0 +1,18 @@ + +# / +/revision.h +/*.aps +/*.ncb +/*.suo +/*.user +/*.sdf +/*.opensdf +/Debug32 +/Release32 +/Trial32 +/Debug64 +/Release64 +/ipch +/bin +/obj +/.vs diff --git a/Include/API/lib3mf_accessright.hpp b/Include/API/lib3mf_accessright.hpp new file mode 100644 index 0000000..a1e8fe6 --- /dev/null +++ b/Include/API/lib3mf_accessright.hpp @@ -0,0 +1,74 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CAccessRight + +*/ + + +#ifndef __LIB3MF_DECRYPTRIGHT +#define __LIB3MF_DECRYPTRIGHT + +#include "lib3mf_interfaces.hpp" +#include "lib3mf_base.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +// Include custom headers here. +#include "Model/Classes/NMR_KeyStoreAccessRight.h" +namespace Lib3MF { + namespace Impl { + + + /************************************************************************************************************************* + Class declaration of CAccessRight + **************************************************************************************************************************/ + + class CAccessRight : public virtual IAccessRight, public virtual CBase { + private: + NMR::PKeyStoreAccessRight m_pAccessRight; + public: + CAccessRight(NMR::PKeyStoreAccessRight ar); + + // Inherited via IAccessRight + virtual IConsumer * GetConsumer() override; + + virtual Lib3MF::eWrappingAlgorithm GetWrappingAlgorithm(); + + virtual Lib3MF::eMgfAlgorithm GetMgfAlgorithm(); + + virtual Lib3MF::eDigestMethod GetDigestMethod(); + + // Other access methods + NMR::PKeyStoreAccessRight accessRight() const; + + + }; + } +} +#endif diff --git a/Include/API/lib3mf_attachment.hpp b/Include/API/lib3mf_attachment.hpp new file mode 100644 index 0000000..1c3bfa7 --- /dev/null +++ b/Include/API/lib3mf_attachment.hpp @@ -0,0 +1,109 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CAttachment + +*/ + + +#ifndef __LIB3MF_ATTACHMENT +#define __LIB3MF_ATTACHMENT + +#include "lib3mf_interfaces.hpp" +#include "lib3mf_base.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +// Include custom headers here. +#include "Model/Classes/NMR_ModelAttachment.h" + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CAttachment +**************************************************************************************************************************/ + +class CAttachment : public virtual IAttachment, public virtual CBase { +private: + + /** + * Put private members here. + */ + NMR::PModelAttachment m_pModelAttachment; + +protected: + + /** + * Put protected members here. + */ + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + CAttachment(NMR::PModelAttachment pModelAttachment); + + /** + * Public member functions to implement. + */ + + std::string GetPath (); + + void SetPath (const std::string & sPath); + + IPackagePart * PackagePart(); + + std::string GetRelationShipType (); + + void SetRelationShipType (const std::string & sPath); + + void WriteToFile (const std::string & sFileName); + + void ReadFromFile (const std::string & sFileName); + + void ReadFromCallback(const Lib3MF::ReadCallback pTheReadCallback, const Lib3MF_uint64 nStreamSize, const Lib3MF::SeekCallback pTheSeekCallback, const Lib3MF_pvoid pUserData); + + Lib3MF_uint64 GetStreamSize (); + + void WriteToBuffer (Lib3MF_uint64 nBufferBufferSize, Lib3MF_uint64* pBufferNeededCount, Lib3MF_uint8 * pBufferBuffer); + + void ReadFromBuffer(const Lib3MF_uint64 nBufferBufferSize, const Lib3MF_uint8 * pBufferBuffer); + +}; + +} +} + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +#endif // __LIB3MF_ATTACHMENT diff --git a/Include/API/lib3mf_base.hpp b/Include/API/lib3mf_base.hpp new file mode 100644 index 0000000..a22a641 --- /dev/null +++ b/Include/API/lib3mf_base.hpp @@ -0,0 +1,93 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CBase + +*/ + + +#ifndef __LIB3MF_BASE +#define __LIB3MF_BASE + +#include "lib3mf_interfaces.hpp" +#include +#include +#include + + +// Include custom headers here. + + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CBase +**************************************************************************************************************************/ + +class CBase : public virtual IBase { +private: + + std::unique_ptr> m_pErrors; + Lib3MF_uint32 m_nReferenceCount = 1; + + /** + * Put private members here. + */ + +protected: + + /** + * Put protected members here. + */ + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + + bool GetLastErrorMessage(std::string & sErrorMessage); + + void ClearErrorMessages(); + + void RegisterErrorMessage(const std::string & sErrorMessage); + + void IncRefCount(); + + bool DecRefCount(); + + /** + * Public member functions to implement. + */ + +}; + +} // namespace Impl +} // namespace Lib3MF + +#endif // __LIB3MF_BASE diff --git a/Include/API/lib3mf_basematerialgroup.hpp b/Include/API/lib3mf_basematerialgroup.hpp new file mode 100644 index 0000000..21260b5 --- /dev/null +++ b/Include/API/lib3mf_basematerialgroup.hpp @@ -0,0 +1,103 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CBaseMaterial + +*/ + + +#ifndef __LIB3MF_BASEMATERIALGROUP +#define __LIB3MF_BASEMATERIALGROUP + +#include "lib3mf_interfaces.hpp" + +// Parent classes +#include "lib3mf_resource.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +// Include custom headers here. +#include "Model/Classes/NMR_ModelBaseMaterial.h" +#include "Model/Classes/NMR_ModelBaseMaterials.h" + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CBaseMaterialGroup +**************************************************************************************************************************/ + +class CBaseMaterialGroup : public virtual IBaseMaterialGroup, public virtual CResource { +private: + + /** + * Put private members here. + */ +protected: + + /** + * Put protected members here. + */ + NMR::CModelBaseMaterialResource& baseMaterialGroup(); + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + CBaseMaterialGroup(NMR::PModelBaseMaterialResource pResource); + + /** + * Public member functions to implement. + */ + + Lib3MF_uint32 GetCount (); + + Lib3MF_uint32 AddMaterial(const std::string & sName, const sLib3MFColor DisplayColor); + + void RemoveMaterial (const Lib3MF_uint32 nPropertyID); + + std::string GetName (const Lib3MF_uint32 nPropertyID); + + void SetName (const Lib3MF_uint32 nPropertyID, const std::string & sName); + + void SetDisplayColor(const Lib3MF_uint32 nPropertyID, const sLib3MFColor TheColor); + + sLib3MFColor GetDisplayColor(const Lib3MF_uint32 nPropertyID); + + void GetAllPropertyIDs(Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer); +}; + +} +} + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_BASEMATERIALGROUP diff --git a/Include/API/lib3mf_basematerialgroupiterator.hpp b/Include/API/lib3mf_basematerialgroupiterator.hpp new file mode 100644 index 0000000..25a0aee --- /dev/null +++ b/Include/API/lib3mf_basematerialgroupiterator.hpp @@ -0,0 +1,89 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CBaseMaterialGroupIterator + +*/ + + +#ifndef __LIB3MF_BASEMATERIALGROUPITERATOR +#define __LIB3MF_BASEMATERIALGROUPITERATOR + +#include "lib3mf_interfaces.hpp" + +// Parent classes +#include "lib3mf_resourceiterator.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +// Include custom headers here. + + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CBaseMaterialGroupIterator +**************************************************************************************************************************/ + +class CBaseMaterialGroupIterator : public virtual IBaseMaterialGroupIterator, public virtual CResourceIterator { +private: + + /** + * Put private members here. + */ + +protected: + + /** + * Put protected members here. + */ + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + + + /** + * Public member functions to implement. + */ + + IBaseMaterialGroup * GetCurrentBaseMaterialGroup (); + +}; + +} // namespace Impl +} // namespace Lib3MF + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_BASEMATERIALGROUPITERATOR diff --git a/Include/API/lib3mf_beamlattice.hpp b/Include/API/lib3mf_beamlattice.hpp new file mode 100644 index 0000000..3dd2742 --- /dev/null +++ b/Include/API/lib3mf_beamlattice.hpp @@ -0,0 +1,137 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CBeamLattice + +*/ + + +#ifndef __LIB3MF_BEAMLATTICE +#define __LIB3MF_BEAMLATTICE + +#include "lib3mf_interfaces.hpp" +#include "lib3mf_base.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +#include "Common/Mesh/NMR_Mesh.h" +#include "Model/Classes/NMR_ModelMeshBeamLatticeAttributes.h" +#include "Model/Classes/NMR_ModelMeshObject.h" +// Include custom headers here. + + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CBeamLattice +**************************************************************************************************************************/ + +class CBeamLattice : public virtual IBeamLattice, public virtual CBase { +private: + + /** + * Put private members here. + */ + NMR::CMesh& m_mesh; + NMR::PModelMeshBeamLatticeAttributes m_pAttributes; + NMR::PModelMeshObject m_pMeshObject; + +protected: + + /** + * Put protected members here. + */ + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + CBeamLattice(NMR::PModelMeshObject pMeshObject, NMR::PModelMeshBeamLatticeAttributes pAttributes); + + /** + * Public member functions to implement. + */ + + Lib3MF_double GetMinLength (); + + void SetMinLength (const Lib3MF_double dMinLength); + + void GetClipping (eBeamLatticeClipMode & eClipMode, Lib3MF_uint32 & nUniqueResourceID); + + void SetClipping (const eBeamLatticeClipMode eClipMode, const Lib3MF_uint32 nUniqueResourceID); + + bool GetRepresentation(Lib3MF_uint32 & nUniqueResourceID); + + void SetRepresentation(const Lib3MF_uint32 nUniqueResourceID); + + void GetBallOptions (eBeamLatticeBallMode & eBallMode, Lib3MF_double & dBallRadius); + + void SetBallOptions (const eBeamLatticeBallMode eBallMode, const Lib3MF_double dBallRadius); + + Lib3MF_uint32 GetBeamCount (); + + sLib3MFBeam GetBeam (const Lib3MF_uint32 nIndex); + + Lib3MF_uint32 AddBeam (const sLib3MFBeam BeamInfo); + + void SetBeam (const Lib3MF_uint32 nIndex, const sLib3MFBeam BeamInfo); + + void SetBeams (const Lib3MF_uint64 nBeamInfoBufferSize, const sLib3MFBeam * pBeamInfoBuffer); + + void GetBeams (Lib3MF_uint64 nBeamInfoBufferSize, Lib3MF_uint64 * pBeamInfoNeededCount, sLib3MFBeam * pBeamInfoBuffer); + + Lib3MF_uint32 GetBallCount (); + + sLib3MFBall GetBall (const Lib3MF_uint32 nIndex); + + Lib3MF_uint32 AddBall (const sLib3MFBall BallInfo); + + void SetBall (const Lib3MF_uint32 nIndex, const sLib3MFBall BallInfo); + + void SetBalls (const Lib3MF_uint64 nBallInfoBufferSize, const sLib3MFBall * pBallInfoBuffer); + + void GetBalls (Lib3MF_uint64 nBeamInfoBufferSize, Lib3MF_uint64 * pBallInfoNeededCount, sLib3MFBall * pBallInfoBuffer); + + Lib3MF_uint32 GetBeamSetCount (); + + IBeamSet * AddBeamSet (); + + IBeamSet * GetBeamSet (const Lib3MF_uint32 nIndex); + +}; + +} // namespace Impl +} // namespace Lib3MF + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_BEAMLATTICE diff --git a/Include/API/lib3mf_beamset.hpp b/Include/API/lib3mf_beamset.hpp new file mode 100644 index 0000000..924c225 --- /dev/null +++ b/Include/API/lib3mf_beamset.hpp @@ -0,0 +1,111 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CBeamSet + +*/ + + +#ifndef __LIB3MF_BEAMSET +#define __LIB3MF_BEAMSET + +#include "lib3mf_interfaces.hpp" +#include "lib3mf_base.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +#include "Common/Mesh/NMR_MeshTypes.h" +#include "Common/Mesh/NMR_Mesh.h" +#include "Model/Classes/NMR_ModelMeshObject.h" +// Include custom headers here. + + +namespace Lib3MF { +namespace Impl { + +#define LIB3MF_MAXBEAMCOUNT (1UL << 31) + +/************************************************************************************************************************* + Class declaration of CBeamSet +**************************************************************************************************************************/ + +class CBeamSet : public virtual IBeamSet, public virtual CBase { +private: + + /** + * Put private members here. + */ + NMR::PBEAMSET m_pBeamSet; + NMR::CMesh& m_mesh; + +protected: + + /** + * Put protected members here. + */ + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + CBeamSet(NMR::PBEAMSET pBeamSet, NMR::PModelMeshObject pMeshObject); + + /** + * Public member functions to implement. + */ + + virtual void SetName(const std::string & sName); + + virtual std::string GetName(); + + virtual void SetIdentifier(const std::string & sIdentifier); + + virtual std::string GetIdentifier(); + + virtual Lib3MF_uint32 GetReferenceCount(); + + virtual void SetReferences(const Lib3MF_uint64 nReferencesBufferSize, const Lib3MF_uint32 * pReferencesBuffer); + + virtual void GetReferences(Lib3MF_uint64 nReferencesBufferSize, Lib3MF_uint64 * pReferencesNeededCount, Lib3MF_uint32 * pReferencesBuffer); + + virtual Lib3MF_uint32 GetBallReferenceCount(); + + virtual void SetBallReferences(const Lib3MF_uint64 nBallReferencesBufferSize, const Lib3MF_uint32 * pBallReferencesBuffer); + + virtual void GetBallReferences(Lib3MF_uint64 nBallReferencesBufferSize, Lib3MF_uint64 * pBallReferencesNeededCount, Lib3MF_uint32 * pBallReferencesBuffer); + +}; + +} +} + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_BEAMSET diff --git a/Include/API/lib3mf_builditem.hpp b/Include/API/lib3mf_builditem.hpp new file mode 100644 index 0000000..5a693ac --- /dev/null +++ b/Include/API/lib3mf_builditem.hpp @@ -0,0 +1,111 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CBuildItem + +*/ + + +#ifndef __LIB3MF_BUILDITEM +#define __LIB3MF_BUILDITEM + +#include "lib3mf_interfaces.hpp" +#include "lib3mf_base.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + + +// Include custom headers here. +#include "Model/Classes/NMR_ModelBuildItem.h" + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CBuildItem +**************************************************************************************************************************/ + +class CBuildItem : public virtual IBuildItem, public virtual CBase { +private: + + /** + * Put private members here. + */ + NMR::PModelBuildItem m_pBuildItem; + +protected: + + /** + * Put protected members here. + */ + NMR::CModelBuildItem& buildItem(); + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + CBuildItem(NMR::PModelBuildItem pBuildItem); + + Lib3MF_uint32 GetHandle(); + + /** + * Public member functions to implement. + */ + + IObject * GetObjectResource (); + + std::string GetUUID (bool & bHasUUID); + + void SetUUID (const std::string & sUUID); + + Lib3MF_uint32 GetObjectResourceID (); + + bool HasObjectTransform (); + + sLib3MFTransform GetObjectTransform (); + + void SetObjectTransform (const sLib3MFTransform Transform); + + std::string GetPartNumber (); + + void SetPartNumber (const std::string & sSetPartnumber); + + IMetaDataGroup * GetMetaDataGroup (); + + Lib3MF::sBox GetOutbox(); +}; + +} +} + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_BUILDITEM diff --git a/Include/API/lib3mf_builditemiterator.hpp b/Include/API/lib3mf_builditemiterator.hpp new file mode 100644 index 0000000..daffaab --- /dev/null +++ b/Include/API/lib3mf_builditemiterator.hpp @@ -0,0 +1,100 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CBuildItemIterator + +*/ + + +#ifndef __LIB3MF_BUILDITEMITERATOR +#define __LIB3MF_BUILDITEMITERATOR + +#include "lib3mf_interfaces.hpp" +#include "lib3mf_base.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + + +// Include custom headers here. +#include "Model/Classes/NMR_ModelBuildItem.h" + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CBuildItemIterator +**************************************************************************************************************************/ + +class CBuildItemIterator : public virtual IBuildItemIterator, public virtual CBase { +private: + + /** + * Put private members here. + */ + std::vector m_pBuildItems; + Lib3MF_int32 m_nCurrentIndex; + +protected: + + /** + * Put protected members here. + */ + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + CBuildItemIterator(); + + void addBuildItem(NMR::PModelBuildItem pBuildItem); + + /** + * Public member functions to implement. + */ + + bool MoveNext (); + + bool MovePrevious (); + + IBuildItem * GetCurrent (); + + IBuildItemIterator * Clone (); + + Lib3MF_uint64 Count(); + +}; + +} +} + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_BUILDITEMITERATOR diff --git a/Include/API/lib3mf_colorgroup.hpp b/Include/API/lib3mf_colorgroup.hpp new file mode 100644 index 0000000..9f6d79b --- /dev/null +++ b/Include/API/lib3mf_colorgroup.hpp @@ -0,0 +1,101 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CColorGroup + +*/ + + +#ifndef __LIB3MF_COLORGROUP +#define __LIB3MF_COLORGROUP + +#include "lib3mf_interfaces.hpp" + +// Parent classes +#include "lib3mf_resource.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +// Include custom headers here. +#include "Model/Classes/NMR_ModelColorGroup.h" + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CColorGroup +**************************************************************************************************************************/ + +class CColorGroup : public virtual IColorGroup, public virtual CResource { +private: + + /** + * Put private members here. + */ + +protected: + + /** + * Put protected members here. + */ + NMR::CModelColorGroupResource& colorGroup(); + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + CColorGroup(NMR::PModelColorGroupResource pResource); + + + /** + * Public member functions to implement. + */ + + Lib3MF_uint32 GetCount (); + + void GetAllPropertyIDs (Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer); + + Lib3MF_uint32 AddColor (const sLib3MFColor TheColor); + + void SetColor (const Lib3MF_uint32 nPropertyID, const sLib3MFColor TheColor); + + sLib3MFColor GetColor (const Lib3MF_uint32 nPropertyID); + + void RemoveColor(const Lib3MF_uint32 nPropertyID); + +}; + +} // namespace Impl +} // namespace Lib3MF + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_COLORGROUP diff --git a/Include/API/lib3mf_colorgroupiterator.hpp b/Include/API/lib3mf_colorgroupiterator.hpp new file mode 100644 index 0000000..0187a9a --- /dev/null +++ b/Include/API/lib3mf_colorgroupiterator.hpp @@ -0,0 +1,89 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CColorGroupIterator + +*/ + + +#ifndef __LIB3MF_COLORGROUPITERATOR +#define __LIB3MF_COLORGROUPITERATOR + +#include "lib3mf_interfaces.hpp" + +// Parent classes +#include "lib3mf_resourceiterator.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +// Include custom headers here. + + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CColorGroupIterator +**************************************************************************************************************************/ + +class CColorGroupIterator : public virtual IColorGroupIterator, public virtual CResourceIterator { +private: + + /** + * Put private members here. + */ + +protected: + + /** + * Put protected members here. + */ + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + + + /** + * Public member functions to implement. + */ + + IColorGroup * GetCurrentColorGroup (); + +}; + +} // namespace Impl +} // namespace Lib3MF + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_COLORGROUPITERATOR diff --git a/Include/API/lib3mf_component.hpp b/Include/API/lib3mf_component.hpp new file mode 100644 index 0000000..4bd53ca --- /dev/null +++ b/Include/API/lib3mf_component.hpp @@ -0,0 +1,100 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CComponent + +*/ + + +#ifndef __LIB3MF_COMPONENT +#define __LIB3MF_COMPONENT + +#include "lib3mf_interfaces.hpp" +#include "lib3mf_base.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + + +// Include custom headers here. +#include "Model/Classes/NMR_ModelComponent.h" + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CComponent +**************************************************************************************************************************/ + +class CComponent : public virtual IComponent, public virtual CBase { +private: + + /** + * Put private members here. + */ + NMR::PModelComponent m_pComponent; + +protected: + + /** + * Put protected members here. + */ + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + CComponent(NMR::PModelComponent pComponent); + + /** + * Public member functions to implement. + */ + + IObject * GetObjectResource (); + + Lib3MF_uint32 GetObjectResourceID (); + + std::string GetUUID (bool & bHasUUID); + + void SetUUID (const std::string & sUUID); + + bool HasTransform (); + + void SetTransform (const sLib3MFTransform Transform); + + virtual sLib3MFTransform GetTransform(); +}; + +} +} + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_COMPONENT diff --git a/Include/API/lib3mf_componentsobject.hpp b/Include/API/lib3mf_componentsobject.hpp new file mode 100644 index 0000000..83f2cff --- /dev/null +++ b/Include/API/lib3mf_componentsobject.hpp @@ -0,0 +1,94 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CComponentsObject + +*/ + + +#ifndef __LIB3MF_COMPONENTSOBJECT +#define __LIB3MF_COMPONENTSOBJECT + +#include "lib3mf_interfaces.hpp" + +// Parent classes +#include "lib3mf_object.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +// Include custom headers here. +#include "Model/Classes/NMR_ModelComponentsObject.h" + + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CComponentsObject +**************************************************************************************************************************/ + +class CComponentsObject : public virtual IComponentsObject, public virtual CObject { +private: + + /** + * Put private members here. + */ + +protected: + + NMR::CModelComponentsObject * getComponentsObject(); + +public: + /** + * Put additional public members here. They will not be visible in the external API. + */ + CComponentsObject(NMR::PModelResource pResource); + + static IComponentsObject* fnCreateComponentsObjectFromModelResource(NMR::PModelResource pResource, bool bFailIfUnkownClass); + + /** + * Public member functions to implement. + */ + + IComponent * AddComponent (IObject* pObjectResource, const sLib3MFTransform Transform); + + IComponent * GetComponent (const Lib3MF_uint32 nIndex); + + Lib3MF_uint32 GetComponentCount (); + + bool IsMeshObject(); + + bool IsComponentsObject(); + +}; + +} +} + +#endif // __LIB3MF_COMPONENTSOBJECT diff --git a/Include/API/lib3mf_componentsobjectiterator.hpp b/Include/API/lib3mf_componentsobjectiterator.hpp new file mode 100644 index 0000000..5229c2c --- /dev/null +++ b/Include/API/lib3mf_componentsobjectiterator.hpp @@ -0,0 +1,89 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CComponentsObjectIterator + +*/ + + +#ifndef __LIB3MF_COMPONENTSOBJECTITERATOR +#define __LIB3MF_COMPONENTSOBJECTITERATOR + +#include "lib3mf_interfaces.hpp" + +// Parent classes +#include "lib3mf_resourceiterator.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +// Include custom headers here. + + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CComponentsObjectIterator +**************************************************************************************************************************/ + +class CComponentsObjectIterator : public virtual IComponentsObjectIterator, public virtual CResourceIterator { +private: + + /** + * Put private members here. + */ + +protected: + + /** + * Put protected members here. + */ + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + + + /** + * Public member functions to implement. + */ + + IComponentsObject * GetCurrentComponentsObject (); + +}; + +} // namespace Impl +} // namespace Lib3MF + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_COMPONENTSOBJECTITERATOR diff --git a/Include/API/lib3mf_compositematerials.hpp b/Include/API/lib3mf_compositematerials.hpp new file mode 100644 index 0000000..f250e8a --- /dev/null +++ b/Include/API/lib3mf_compositematerials.hpp @@ -0,0 +1,102 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CCompositeMaterials + +*/ + + +#ifndef __LIB3MF_COMPOSITEMATERIALS +#define __LIB3MF_COMPOSITEMATERIALS + +#include "lib3mf_interfaces.hpp" + +// Parent classes +#include "lib3mf_resource.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +// Include custom headers here. +#include "Model/Classes/NMR_ModelCompositeMaterials.h" + +#define LIB3MF_MAXCOMPOSITEMATERIALS (1UL << 31) + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CCompositeMaterials +**************************************************************************************************************************/ + +class CCompositeMaterials : public virtual ICompositeMaterials, public virtual CResource { +private: + + /** + * Put private members here. + */ + +protected: + + /** + * Put protected members here. + */ + NMR::CModelCompositeMaterialsResource& compositeMaterials(); + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + CCompositeMaterials(NMR::PModelCompositeMaterialsResource pResource); + + + /** + * Public member functions to implement. + */ + + Lib3MF_uint32 GetCount (); + + void GetAllPropertyIDs (Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer); + + IBaseMaterialGroup * GetBaseMaterialGroup (); + + Lib3MF_uint32 AddComposite(const Lib3MF_uint64 nCompositeBufferSize, const sLib3MFCompositeConstituent * pCompositeBuffer); + + void RemoveComposite (const Lib3MF_uint32 nPropertyID); + + void GetComposite(const Lib3MF_uint32 nPropertyID, Lib3MF_uint64 nCompositeBufferSize, Lib3MF_uint64* pCompositeNeededCount, sLib3MFCompositeConstituent * pCompositeBuffer); +}; + +} // namespace Impl +} // namespace Lib3MF + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_COMPOSITEMATERIALS diff --git a/Include/API/lib3mf_compositematerialsiterator.hpp b/Include/API/lib3mf_compositematerialsiterator.hpp new file mode 100644 index 0000000..6f12527 --- /dev/null +++ b/Include/API/lib3mf_compositematerialsiterator.hpp @@ -0,0 +1,89 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CCompositeMaterialsIterator + +*/ + + +#ifndef __LIB3MF_COMPOSITEMATERIALSITERATOR +#define __LIB3MF_COMPOSITEMATERIALSITERATOR + +#include "lib3mf_interfaces.hpp" + +// Parent classes +#include "lib3mf_resourceiterator.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +// Include custom headers here. + + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CCompositeMaterialsIterator +**************************************************************************************************************************/ + +class CCompositeMaterialsIterator : public virtual ICompositeMaterialsIterator, public virtual CResourceIterator { +private: + + /** + * Put private members here. + */ + +protected: + + /** + * Put protected members here. + */ + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + + + /** + * Public member functions to implement. + */ + + ICompositeMaterials * GetCurrentCompositeMaterials (); + +}; + +} // namespace Impl +} // namespace Lib3MF + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_COMPOSITEMATERIALSITERATOR diff --git a/Include/API/lib3mf_consumer.hpp b/Include/API/lib3mf_consumer.hpp new file mode 100644 index 0000000..b6afcc0 --- /dev/null +++ b/Include/API/lib3mf_consumer.hpp @@ -0,0 +1,66 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CConsumer + +*/ + + +#ifndef __LIB3MF_CONSUMER +#define __LIB3MF_CONSUMER + +#include "lib3mf_interfaces.hpp" +#include "lib3mf_base.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +#include "Model/Classes/NMR_KeyStoreConsumer.h" +// Include custom headers here. +namespace Lib3MF { + namespace Impl { + + /************************************************************************************************************************* + Class declaration of CConsumer + **************************************************************************************************************************/ + + class CConsumer : public virtual IConsumer, public virtual CBase { + private: + NMR::PKeyStoreConsumer m_Consumer; + public: + inline NMR::PKeyStoreConsumer consumer() const { + return m_Consumer; + } + CConsumer(NMR::PKeyStoreConsumer const & consumer); + // Inherited via IConsumer + std::string GetConsumerID() override; + std::string GetKeyID() override; + std::string GetKeyValue() override; + }; + } +} +#endif diff --git a/Include/API/lib3mf_contentencryptionparams.hpp b/Include/API/lib3mf_contentencryptionparams.hpp new file mode 100644 index 0000000..f644545 --- /dev/null +++ b/Include/API/lib3mf_contentencryptionparams.hpp @@ -0,0 +1,74 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CContentEncryptionParams + +*/ + + +#ifndef __LIB3MF_CIPHERDATA +#define __LIB3MF_CIPHERDATA + +#include "lib3mf_interfaces.hpp" +#include "lib3mf_base.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + + +#include "Model/Classes/NMR_KeyStoreCEKParams.h" +// Include custom headers here. +namespace Lib3MF { + namespace Impl { + + /************************************************************************************************************************* + Class declaration of CContentEncryptionParams + **************************************************************************************************************************/ + + class CContentEncryptionParams : public virtual IContentEncryptionParams, public virtual CBase { + private: + NMR::PCKeyStoreContentEncryptionParams m_pParams; + public: + CContentEncryptionParams(NMR::PCKeyStoreContentEncryptionParams const & p); + // Inherited via IContentEncryptionParams + Lib3MF_uint64 GetDescriptor(); + Lib3MF::eEncryptionAlgorithm GetEncryptionAlgorithm(); + void GetKey(Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64 *pByteDataNeededCount, Lib3MF_uint8 *pByteDataBuffer); + void GetInitializationVector(Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64 *pByteDataNeededCount, Lib3MF_uint8 *pByteDataBuffer); + void GetAuthenticationTag(Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64 *pByteDataNeededCount, Lib3MF_uint8 *pByteDataBuffer); + void SetAuthenticationTag(Lib3MF_uint64 const nByteDataBufferSize, const Lib3MF_uint8 *pByteDataBuffer); + void GetAdditionalAuthenticationData(Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64 *pByteDataNeededCount, Lib3MF_uint8 *pByteDataBuffer); + void SetAdditionalAuthenticationData(Lib3MF_uint64 const nByteDataBufferSize, const Lib3MF_uint8 *pByteDataBuffer); + std::string GetKeyUUID(); + + inline NMR::PKeyStoreCEKParams params() const { + return m_pParams; + } + }; + } +} +#endif diff --git a/Include/API/lib3mf_keystore.hpp b/Include/API/lib3mf_keystore.hpp new file mode 100644 index 0000000..cfc4bb2 --- /dev/null +++ b/Include/API/lib3mf_keystore.hpp @@ -0,0 +1,119 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CKeyStore + +*/ + + +#ifndef __LIB3MF_KEYSTORE +#define __LIB3MF_KEYSTORE + +#include "lib3mf_interfaces.hpp" +#include "lib3mf_base.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +// Include custom headers here. +#include "Model/Classes/NMR_KeyStore.h" +#include "Model/Classes/NMR_Model.h" +namespace Lib3MF { + namespace Impl { + + + /************************************************************************************************************************* + Class declaration of CKeyStore + **************************************************************************************************************************/ + + class CKeyStore : public virtual IKeyStore, public virtual CBase { + private: + + /** + * Put private members here. + */ + NMR::PKeyStore m_pKeyStore; + NMR::PModel m_pModel; + protected: + + /** + * Put protected members here. + */ + + public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + CKeyStore(NMR::PModel const & pModel); + + /** + * Public member functions to implement. + */ + + + // Inherited via IKeyStore + IConsumer * AddConsumer(const std::string & sConsumerID, const std::string & sKeyID, const std::string & sKeyValue) override; + + Lib3MF_uint64 GetConsumerCount() override; + + IConsumer * GetConsumer(const Lib3MF_uint64 nConsumerIndex) override; + + IConsumer * FindConsumer(const std::string & sConsumerID) override; + + virtual void RemoveConsumer(IConsumer * pConsumerInstance) override; + + std::string GetUUID(bool & bHasUUID) override; + + void SetUUID(const std::string & sUUID) override; + + virtual Lib3MF_uint64 GetResourceDataGroupCount() override; + + virtual IResourceDataGroup * GetResourceDataGroup(const Lib3MF_uint64 nResourceDataIndex) override; + + virtual IResourceDataGroup * AddResourceDataGroup() override; + + virtual void RemoveResourceDataGroup(IResourceDataGroup * pTheResourceDataGroup) override; + + virtual Lib3MF::Impl::IResourceDataGroup * FindResourceDataGroup(Lib3MF::Impl::IPackagePart *pPartPath); + + virtual IResourceData * AddResourceData(IResourceDataGroup* pResourceDataGroup, IPackagePart* pPartPath, const Lib3MF::eEncryptionAlgorithm eAlgorithm, const Lib3MF::eCompression eCompression, const Lib3MF_uint64 nAdditionalAuthenticationDataBufferSize, const Lib3MF_uint8 * pAdditionalAuthenticationDataBuffer); + + virtual void RemoveResourceData(Lib3MF::Impl::IResourceData *pResourceData); + + virtual Lib3MF_uint64 GetResourceDataCount(); + + virtual Lib3MF::Impl::IResourceData * GetResourceData(const Lib3MF_uint64 nResourceDataIndex); + + virtual IResourceData * FindResourceData(IPackagePart * pResourcePath) override; + + }; + + } // namespace Impl +} // namespace Lib3MF + +#endif // __LIB3MF_KEYSTORE \ No newline at end of file diff --git a/Include/API/lib3mf_meshobject.hpp b/Include/API/lib3mf_meshobject.hpp new file mode 100644 index 0000000..edc714c --- /dev/null +++ b/Include/API/lib3mf_meshobject.hpp @@ -0,0 +1,137 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CMeshObject + +*/ + + +#ifndef __LIB3MF_MESHOBJECT +#define __LIB3MF_MESHOBJECT + +#include "lib3mf_interfaces.hpp" + +// Parent classes +#include "lib3mf_object.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +// Include custom headers here. +#include "Model/Classes/NMR_ModelMeshObject.h" +#include "Common/MeshInformation/NMR_MeshInformation_Properties.h" + +namespace Lib3MF { +namespace Impl { + +/************************************************************************************************************************* + Class declaration of CMeshObject +**************************************************************************************************************************/ + +class CMeshObject : public virtual IMeshObject, public virtual CObject { +private: + + /** + * Put private members here. + */ + NMR::PModelMeshObject meshObject(); + NMR::CMesh* mesh(); + + NMR::CMeshInformation_Properties* getMeshInformationProperties(); + +protected: + + /** + * Put protected members here. + */ + +public: + static IMeshObject* fnCreateMeshObjectFromModelResource(NMR::PModelResource pResource, bool bFailIfUnkownClass); + + /** + * Put additional public members here. They will not be visible in the external API. + */ + CMeshObject(NMR::PModelResource pResource); + + /** + * Public member functions to implement. + */ + + Lib3MF_uint32 GetVertexCount (); + + Lib3MF_uint32 GetTriangleCount (); + + void SetVertex (const Lib3MF_uint32 nIndex, const sLib3MFPosition Coordinates); + + sLib3MFPosition GetVertex(const Lib3MF_uint32 nIndex); + + Lib3MF_uint32 AddVertex (const sLib3MFPosition Coordinates); + + virtual void GetVertices(Lib3MF_uint64 nVerticesBufferSize, Lib3MF_uint64* pVerticesNeededCount, sLib3MFPosition * pVerticesBuffer); + + sLib3MFTriangle GetTriangle (const Lib3MF_uint32 nIndex); + + void SetTriangle (const Lib3MF_uint32 nIndex, const sLib3MFTriangle Indices); + + Lib3MF_uint32 AddTriangle (const sLib3MFTriangle Indices); + + void GetTriangleIndices (Lib3MF_uint64 nIndicesBufferSize, Lib3MF_uint64* pIndicesNeededCount, sLib3MFTriangle * pIndicesBuffer); + + void SetGeometry(const Lib3MF_uint64 nVerticesBufferSize, const sLib3MFPosition * pVerticesBuffer, const Lib3MF_uint64 nIndicesBufferSize, const sLib3MFTriangle * pIndicesBuffer); + + bool IsManifoldAndOriented(); + + bool IsMeshObject(); + + bool IsComponentsObject(); + + bool IsValid(); + + virtual IBeamLattice * BeamLattice(); + + void SetObjectLevelProperty(const Lib3MF_uint32 nUniqueResourceID, const Lib3MF_uint32 nPropertyID); + + bool GetObjectLevelProperty(Lib3MF_uint32 & nUniqueResourceID, Lib3MF_uint32 & nPropertyID); + + void SetTriangleProperties(const Lib3MF_uint32 nIndex, const sLib3MFTriangleProperties Properties); + + void GetTriangleProperties(const Lib3MF_uint32 nIndex, sLib3MFTriangleProperties & sProperty); + + void SetAllTriangleProperties(const Lib3MF_uint64 nPropertiesArrayBufferSize, const sLib3MFTriangleProperties * pPropertiesArrayBuffer); + + void GetAllTriangleProperties(Lib3MF_uint64 nPropertiesArrayBufferSize, Lib3MF_uint64* pPropertiesArrayNeededCount, sLib3MFTriangleProperties * pPropertiesArrayBuffer); + + void ClearAllProperties(); +}; + +} +} + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_MESHOBJECT diff --git a/Include/API/lib3mf_meshobjectiterator.hpp b/Include/API/lib3mf_meshobjectiterator.hpp new file mode 100644 index 0000000..c8a35a1 --- /dev/null +++ b/Include/API/lib3mf_meshobjectiterator.hpp @@ -0,0 +1,89 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CMeshObjectIterator + +*/ + + +#ifndef __LIB3MF_MESHOBJECTITERATOR +#define __LIB3MF_MESHOBJECTITERATOR + +#include "lib3mf_interfaces.hpp" + +// Parent classes +#include "lib3mf_resourceiterator.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +// Include custom headers here. + + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CMeshObjectIterator +**************************************************************************************************************************/ + +class CMeshObjectIterator : public virtual IMeshObjectIterator, public virtual CResourceIterator { +private: + + /** + * Put private members here. + */ + +protected: + + /** + * Put protected members here. + */ + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + + + /** + * Public member functions to implement. + */ + + IMeshObject * GetCurrentMeshObject (); + +}; + +} // namespace Impl +} // namespace Lib3MF + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_MESHOBJECTITERATOR diff --git a/Include/API/lib3mf_metadata.hpp b/Include/API/lib3mf_metadata.hpp new file mode 100644 index 0000000..db7d2de --- /dev/null +++ b/Include/API/lib3mf_metadata.hpp @@ -0,0 +1,110 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CMetaData + +*/ + + +#ifndef __LIB3MF_METADATA +#define __LIB3MF_METADATA + +#include "lib3mf_interfaces.hpp" +#include "lib3mf_base.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +#include "Model/Classes/NMR_ModelMetaData.h" + +// Include custom headers here. + + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CMetaData +**************************************************************************************************************************/ + +class CMetaData : public virtual IMetaData, public virtual CBase { +private: + + /** + * Put private members here. + */ + NMR::PModelMetaData m_pMetaData; + +protected: + + /** + * Put protected members here. + */ + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + CMetaData(NMR::PModelMetaData pMetaData); + + /** + * Public member functions to implement. + */ + + std::string GetNameSpace (); + + void SetNameSpace (const std::string & sNameSpace); + + std::string GetName (); + + std::string GetKey(); + + void SetName (const std::string & sName); + + bool GetMustPreserve (); + + void SetMustPreserve (const bool bMustPreserve); + + std::string GetType (); + + void SetType (const std::string & sType); + + std::string GetValue (); + + void SetValue (const std::string & sValue); + +}; + +} +} + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_METADATA diff --git a/Include/API/lib3mf_metadatagroup.hpp b/Include/API/lib3mf_metadatagroup.hpp new file mode 100644 index 0000000..76fc36b --- /dev/null +++ b/Include/API/lib3mf_metadatagroup.hpp @@ -0,0 +1,101 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CMetaDataGroup + +*/ + + +#ifndef __LIB3MF_METADATAGROUP +#define __LIB3MF_METADATAGROUP + +#include "lib3mf_interfaces.hpp" +#include "lib3mf_base.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +#include "Model/Classes/NMR_ModelMetaDataGroup.h" + +// Include custom headers here. + + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CMetaDataGroup +**************************************************************************************************************************/ + +class CMetaDataGroup : public virtual IMetaDataGroup, public virtual CBase { +private: + + /** + * Put private members here. + */ + NMR::PModelMetaDataGroup m_pModelMetaDataGroup; + +protected: + + /** + * Put protected members here. + */ + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + CMetaDataGroup(NMR::PModelMetaDataGroup pMetaDataGroup); + + /** + * Public member functions to implement. + */ + + virtual Lib3MF_uint32 GetMetaDataCount(); + + IMetaData * GetMetaData(const Lib3MF_uint32 nIndex); + + IMetaData * GetMetaDataByKey(const std::string & sNameSpace, const std::string & sName); + + void RemoveMetaDataByIndex(const Lib3MF_uint32 nIndex); + + void RemoveMetaData(IMetaData* pTheMetaData); + + IMetaData * AddMetaData(const std::string & sNameSpace, const std::string & sName, const std::string & sValue, const std::string & sType, const bool bMustPreserve); + + +}; + +} +} + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_METADATAGROUP diff --git a/Include/API/lib3mf_model.hpp b/Include/API/lib3mf_model.hpp new file mode 100644 index 0000000..5e63c74 --- /dev/null +++ b/Include/API/lib3mf_model.hpp @@ -0,0 +1,206 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CModel + +*/ + + +#ifndef __LIB3MF_MODEL +#define __LIB3MF_MODEL + +#include "lib3mf_interfaces.hpp" +#include "lib3mf_base.hpp" + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + + +// Include custom headers here. +#include "Model/Classes/NMR_Model.h" +#include "Model/Classes/NMR_KeyStore.h" + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CModel +**************************************************************************************************************************/ + +class CModel : public virtual IModel, public virtual CBase { +private: + + NMR::PModel m_model; + +protected: + + /** + * Put protected members here. + */ + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + CModel(); + + NMR::CModel& model(); + + /** + * Public member functions to implement. + */ + + IPackagePart * RootModelPart() override; + + IPackagePart * FindOrCreatePackagePart(const std::string & sAbsolutePath) override; + + void SetUnit (const eLib3MFModelUnit eUnit) override; + + eLib3MFModelUnit GetUnit() override; + + std::string GetLanguage() override; + + void SetLanguage(const std::string & sLanguage) override; + + IWriter * QueryWriter(const std::string & sWriterClass) override; + + IReader * QueryReader(const std::string & sReaderClass) override; + + ITexture2D * GetTexture2DByID(const Lib3MF_uint32 nUniqueResourceID) override; + + eLib3MFPropertyType GetPropertyTypeByID(const Lib3MF_uint32 nUniqueResourceID) override; + + IBaseMaterialGroup * GetBaseMaterialGroupByID(const Lib3MF_uint32 nUniqueResourceID) override; + + IMeshObject * GetMeshObjectByID(const Lib3MF_uint32 nUniqueResourceID) override; + + IComponentsObject * GetComponentsObjectByID(const Lib3MF_uint32 nUniqueResourceID) override; + + IColorGroup * GetColorGroupByID(const Lib3MF_uint32 nUniqueResourceID) override; + + ITexture2DGroup * GetTexture2DGroupByID(const Lib3MF_uint32 nUniqueResourceID) override; + + ICompositeMaterials * GetCompositeMaterialsByID(const Lib3MF_uint32 nUniqueResourceID) override; + + IMultiPropertyGroup * GetMultiPropertyGroupByID(const Lib3MF_uint32 nUniqueResourceID) override; + + ISliceStack * GetSliceStackByID(const Lib3MF_uint32 nUniqueResourceID) override; + + std::string GetBuildUUID (bool & bHasUUID) override; + + void SetBuildUUID (const std::string & sUUID) override; + + IBuildItemIterator * GetBuildItems() override; + + IResourceIterator * GetResources() override; + + IObjectIterator * GetObjects() override; + + IMeshObjectIterator * GetMeshObjects() override; + + IComponentsObjectIterator * GetComponentsObjects() override; + + ITexture2DIterator * GetTexture2Ds() override; + + IBaseMaterialGroupIterator * GetBaseMaterialGroups() override; + + IColorGroupIterator * GetColorGroups() override; + + ITexture2DGroupIterator * GetTexture2DGroups() override; + + ICompositeMaterialsIterator * GetCompositeMaterials() override; + + IMultiPropertyGroupIterator * GetMultiPropertyGroups() override; + + ISliceStackIterator * GetSliceStacks() override; + + IModel * MergeToModel() override; + + IMeshObject * AddMeshObject() override; + + IComponentsObject * AddComponentsObject() override; + + ISliceStack * AddSliceStack(const Lib3MF_double dZBottom) override; + + ITexture2D * AddTexture2DFromAttachment(IAttachment* pTextureAttachment) override; + + IBaseMaterialGroup * AddBaseMaterialGroup() override; + + IColorGroup * AddColorGroup() override; + + ITexture2DGroup * AddTexture2DGroup(ITexture2D* pTexture2DInstance) override; + + ICompositeMaterials * AddCompositeMaterials(IBaseMaterialGroup* pBaseMaterialGroupInstance) override; + + IMultiPropertyGroup * AddMultiPropertyGroup() override; + + IBuildItem * AddBuildItem(IObject* pObject, const sLib3MFTransform Transform) override; + + void RemoveBuildItem(IBuildItem* pBuildItemInstance) override; + + IMetaDataGroup * GetMetaDataGroup() override; + + IAttachment * AddAttachment(const std::string & sURI, const std::string & sRelationShipType) override; + + void RemoveAttachment(IAttachment* pAttachmentInstance) override; + + IAttachment * GetAttachment(const Lib3MF_uint32 nIndex) override; + + IAttachment * FindAttachment(const std::string & sURI) override; + + Lib3MF_uint32 GetAttachmentCount() override; + + bool HasPackageThumbnailAttachment() override; + + IAttachment * CreatePackageThumbnailAttachment() override; + + IAttachment * GetPackageThumbnailAttachment() override; + + void RemovePackageThumbnailAttachment() override; + + void AddCustomContentType(const std::string & sExtension, const std::string & sContentType) override; + + void RemoveCustomContentType(const std::string & sExtension) override; + + Lib3MF::sBox GetOutbox() override; + + IKeyStore * GetKeyStore(); + + void SetRandomNumberCallback(const Lib3MF::RandomNumberCallback pTheCallback, const Lib3MF_pvoid pUserData); +}; + +} +} + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +#endif // __LIB3MF_MODEL diff --git a/Include/API/lib3mf_multipropertygroup.hpp b/Include/API/lib3mf_multipropertygroup.hpp new file mode 100644 index 0000000..f50b451 --- /dev/null +++ b/Include/API/lib3mf_multipropertygroup.hpp @@ -0,0 +1,111 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CMultiPropertyGroup + +*/ + + +#ifndef __LIB3MF_MULTIPROPERTYGROUP +#define __LIB3MF_MULTIPROPERTYGROUP + +#include "lib3mf_interfaces.hpp" + +// Parent classes +#include "lib3mf_resource.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +// Include custom headers here. +#include "Model/Classes/NMR_ModelMultiPropertyGroup.h" + +#define LIB3MF_MAXMULTIPROPERTIES (1UL << 31) + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CMultiPropertyGroup +**************************************************************************************************************************/ + +class CMultiPropertyGroup : public virtual IMultiPropertyGroup, public virtual CResource { +private: + + /** + * Put private members here. + */ + +protected: + + /** + * Put protected members here. + */ + + NMR::CModelMultiPropertyGroupResource& multiPropertyGroup(); + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + CMultiPropertyGroup(NMR::PModelMultiPropertyGroupResource pResource); + + /** + * Public member functions to implement. + */ + + Lib3MF_uint32 GetCount (); + + void GetAllPropertyIDs (Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer); + + Lib3MF_uint32 AddMultiProperty (const Lib3MF_uint64 nPropertyIDsBufferSize, const Lib3MF_uint32 * pPropertyIDsBuffer); + + void SetMultiProperty (const Lib3MF_uint32 nPropertyID, const Lib3MF_uint64 nPropertyIDsBufferSize, const Lib3MF_uint32 * pPropertyIDsBuffer); + + void GetMultiProperty (const Lib3MF_uint32 nPropertyID, Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer); + + void RemoveMultiProperty (const Lib3MF_uint32 nPropertyID); + + Lib3MF_uint32 GetLayerCount (); + + Lib3MF_uint32 AddLayer (const sLib3MFMultiPropertyLayer TheLayer); + + sLib3MFMultiPropertyLayer GetLayer (const Lib3MF_uint32 nLayerIndex); + + void RemoveLayer (const Lib3MF_uint32 nLayerIndex); + +}; + +} // namespace Impl +} // namespace Lib3MF + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_MULTIPROPERTYGROUP diff --git a/Include/API/lib3mf_multipropertygroupiterator.hpp b/Include/API/lib3mf_multipropertygroupiterator.hpp new file mode 100644 index 0000000..2150650 --- /dev/null +++ b/Include/API/lib3mf_multipropertygroupiterator.hpp @@ -0,0 +1,89 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CMultiPropertyGroupIterator + +*/ + + +#ifndef __LIB3MF_MULTIPROPERTYGROUPITERATOR +#define __LIB3MF_MULTIPROPERTYGROUPITERATOR + +#include "lib3mf_interfaces.hpp" + +// Parent classes +#include "lib3mf_resourceiterator.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +// Include custom headers here. + + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CMultiPropertyGroupIterator +**************************************************************************************************************************/ + +class CMultiPropertyGroupIterator : public virtual IMultiPropertyGroupIterator, public virtual CResourceIterator { +private: + + /** + * Put private members here. + */ + +protected: + + /** + * Put protected members here. + */ + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + + + /** + * Public member functions to implement. + */ + + IMultiPropertyGroup * GetCurrentMultiPropertyGroup (); + +}; + +} // namespace Impl +} // namespace Lib3MF + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_MULTIPROPERTYGROUPITERATOR diff --git a/Include/API/lib3mf_object.hpp b/Include/API/lib3mf_object.hpp new file mode 100644 index 0000000..24bee6c --- /dev/null +++ b/Include/API/lib3mf_object.hpp @@ -0,0 +1,135 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CObject + +*/ + + +#ifndef __LIB3MF_OBJECT +#define __LIB3MF_OBJECT + +#include "lib3mf_interfaces.hpp" + +// Parent classes +#include "lib3mf_resource.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +// Include custom headers here. +#include "Model/Classes/NMR_ModelResource.h" + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CObject +**************************************************************************************************************************/ + +class CObject : public virtual IObject, public virtual CResource { +private: + + /** + * Put private members here. + */ + +protected: + NMR::CModelObject* object(); + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + CObject(NMR::PModelResource pResource); + CObject() = delete; + + static IObject* fnCreateObjectFromModelResource(NMR::PModelResource pResource, bool bFailIfUnkownClass); + + /** + * Public member functions to implement. + */ + + eLib3MFObjectType GetType (); + + void SetType (const eLib3MFObjectType eObjectType); + + std::string GetName (); + + void SetName (const std::string & sName); + + std::string GetPartNumber (); + + void SetPartNumber (const std::string & sPartNumber); + + virtual bool IsMeshObject (); + + virtual bool IsComponentsObject (); + + virtual IMeshObject * AsMeshObject(); + + virtual IComponentsObject * AsComponentsObject(); + + bool IsValid (); + + void SetAttachmentAsThumbnail(IAttachment* pAttachment); + + IAttachment * GetThumbnailAttachment(); + + void ClearThumbnailAttachment(); + + IMetaDataGroup * GetMetaDataGroup (); + + std::string GetUUID(bool & bHasUUID); + + void SetUUID(const std::string & sUUID); + + void SetSlicesMeshResolution(const eLib3MFSlicesMeshResolution eMeshResolution); + + eLib3MFSlicesMeshResolution GetSlicesMeshResolution(); + + bool HasSlices(const bool bRecursive); + + void ClearSliceStack(); + + ISliceStack * GetSliceStack(); + + void AssignSliceStack(ISliceStack* pSliceStackInstance); + + Lib3MF::sBox GetOutbox(); + +}; + +} +} + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_OBJECT diff --git a/Include/API/lib3mf_objectiterator.hpp b/Include/API/lib3mf_objectiterator.hpp new file mode 100644 index 0000000..e3b23f1 --- /dev/null +++ b/Include/API/lib3mf_objectiterator.hpp @@ -0,0 +1,89 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CObjectIterator + +*/ + + +#ifndef __LIB3MF_OBJECTITERATOR +#define __LIB3MF_OBJECTITERATOR + +#include "lib3mf_interfaces.hpp" + +// Parent classes +#include "lib3mf_resourceiterator.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +// Include custom headers here. + + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CObjectIterator +**************************************************************************************************************************/ + +class CObjectIterator : public virtual IObjectIterator, public virtual CResourceIterator { +private: + + /** + * Put private members here. + */ + +protected: + + /** + * Put protected members here. + */ + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + + + /** + * Public member functions to implement. + */ + + IObject * GetCurrentObject (); + +}; + +} // namespace Impl +} // namespace Lib3MF + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_OBJECTITERATOR diff --git a/Include/API/lib3mf_packagepart.hpp b/Include/API/lib3mf_packagepart.hpp new file mode 100644 index 0000000..ccf9b2d --- /dev/null +++ b/Include/API/lib3mf_packagepart.hpp @@ -0,0 +1,92 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CPackagePart + +*/ + + +#ifndef __LIB3MF_MODELPART +#define __LIB3MF_MODELPART + +#include "lib3mf_interfaces.hpp" + +// Parent classes +#include "lib3mf_base.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +// Include custom headers here. +#include "Model/Classes/NMR_PackageResourceID.h" + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CPackagePart +**************************************************************************************************************************/ + +class CPackagePart : public virtual IPackagePart, public virtual CBase { +private: + + /** + * Put private members here. + */ + NMR::PPackageModelPath m_pPath; + +protected: + + /** + * Put protected members here. + */ + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + CPackagePart(NMR::PPackageModelPath pPath); + + /** + * Public member functions to implement. + */ + + std::string GetPath() override; + + void SetPath(const std::string & sPath) override; + +}; + +} // namespace Impl +} // namespace Lib3MF + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_MODELPART diff --git a/Include/API/lib3mf_reader.hpp b/Include/API/lib3mf_reader.hpp new file mode 100644 index 0000000..50a4c78 --- /dev/null +++ b/Include/API/lib3mf_reader.hpp @@ -0,0 +1,114 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CReader + +*/ + + +#ifndef __LIB3MF_READER +#define __LIB3MF_READER + +#include "lib3mf_interfaces.hpp" +#include "lib3mf_base.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + + +// Include custom headers here. +#include "Model/Reader/NMR_ModelReader.h" +#include "Model/Reader/NMR_ModelReader_3MF_Native.h" +#include "Model/Reader/NMR_ModelReader_STL.h" + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CReader +**************************************************************************************************************************/ + +class CReader : public virtual IReader, public virtual CBase { +private: + + /** + * Put private members here. + */ + NMR::PModelReader m_pReader; + +protected: + + /** + * Put protected members here. + */ + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + CReader(std::string sReaderClass, NMR::PModel model); + + NMR::CModelReader& reader(); + /** + * Public member functions to implement. + */ + + void ReadFromFile (const std::string & sFilename); + + void ReadFromBuffer (const Lib3MF_uint64 nBufferBufferSize, const Lib3MF_uint8 * pBufferBuffer); + + void ReadFromCallback(const Lib3MFReadCallback pTheReadCallback, const Lib3MF_uint64 nStreamSize, const Lib3MFSeekCallback pTheSeekCallback, const Lib3MF_pvoid pUserData); + + void AddRelationToRead (const std::string & sRelationShipType); + + void SetProgressCallback(const Lib3MFProgressCallback pProgressCallback, const Lib3MF_pvoid pUserData); + + void RemoveRelationToRead (const std::string & sRelationShipType); + + void SetStrictModeActive (const bool bStrictModeActive); + + bool GetStrictModeActive (); + + std::string GetWarning (const Lib3MF_uint32 nIndex, Lib3MF_uint32 & nErrorCode); + + Lib3MF_uint32 GetWarningCount (); + + void AddKeyWrappingCallback(const std::string &sConsumerID, const Lib3MF::KeyWrappingCallback pTheCallback, const Lib3MF_pvoid pUserData); + + void SetContentEncryptionCallback(const Lib3MF::ContentEncryptionCallback pTheCallback, const Lib3MF_pvoid pUserData); + +}; + +} +} + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_READER diff --git a/Include/API/lib3mf_resource.hpp b/Include/API/lib3mf_resource.hpp new file mode 100644 index 0000000..a24bf7f --- /dev/null +++ b/Include/API/lib3mf_resource.hpp @@ -0,0 +1,97 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CResource + +*/ + + +#ifndef __LIB3MF_RESOURCE +#define __LIB3MF_RESOURCE + +#include "lib3mf_interfaces.hpp" +#include "lib3mf_base.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + + +// Include custom headers here. +#include "Model/Classes/NMR_ModelResource.h" + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CResource +**************************************************************************************************************************/ + +class CResource : public virtual IResource, public virtual CBase { +private: + + /** + * Put private members here. + */ + NMR::PModelResource m_pResource; + +protected: + + NMR::PModelResource resource(); + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + CResource() = delete; + CResource(NMR::PModelResource pResource); + + /** + * Public member functions to implement. + */ + + Lib3MF_uint32 GetResourceID() override; + + Lib3MF_uint32 GetUniqueResourceID() override; + + virtual IObject * AsObject(); + + IPackagePart * PackagePart() override; + + void SetPackagePart(IPackagePart* pPackagePath) override; + + Lib3MF_uint32 GetModelResourceID() override; +}; + +} +} + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_RESOURCE diff --git a/Include/API/lib3mf_resourcedata.hpp b/Include/API/lib3mf_resourcedata.hpp new file mode 100644 index 0000000..cae2902 --- /dev/null +++ b/Include/API/lib3mf_resourcedata.hpp @@ -0,0 +1,74 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CResourceData + +*/ + + +#ifndef __LIB3MF_RESOURCEDATA +#define __LIB3MF_RESOURCEDATA + +#include "lib3mf_interfaces.hpp" +#include "lib3mf_base.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +#include "Model/Classes/NMR_KeyStoreResourceData.h" +// Include custom headers here. +namespace Lib3MF { + namespace Impl { + + + /************************************************************************************************************************* + Class declaration of CResourceData + **************************************************************************************************************************/ + + class CResourceData : public virtual IResourceData, public virtual CBase { + private: + NMR::PKeyStoreResourceData m_pResourceData; + public: + CResourceData(NMR::PKeyStoreResourceData resourceData); + + + // Inherited via IResourceData + IPackagePart * GetPath() override; + + Lib3MF::eEncryptionAlgorithm GetEncryptionAlgorithm() override; + + Lib3MF::eCompression GetCompression() override; + + void GetAdditionalAuthenticationData(Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64 * pByteDataNeededCount, Lib3MF_uint8 * pByteDataBuffer) override; + + inline NMR::PKeyStoreResourceData resourceData() const { + return m_pResourceData; + } + }; + } +} +#endif diff --git a/Include/API/lib3mf_resourcedatagroup.hpp b/Include/API/lib3mf_resourcedatagroup.hpp new file mode 100644 index 0000000..cc88bcc --- /dev/null +++ b/Include/API/lib3mf_resourcedatagroup.hpp @@ -0,0 +1,74 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CResourceDataGroup + +*/ + + +#ifndef __LIB3MF_RESOURCEDATAGROUP +#define __LIB3MF_RESOURCEDATAGROUP + + +#include "lib3mf_interfaces.hpp" +#include "lib3mf_base.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +#include "Model/Classes/NMR_KeyStoreResourceDataGroup.h" +#include "Model/Classes/NMR_KeyStore.h" + +namespace Lib3MF { + namespace Impl { + + /************************************************************************************************************************* + Class declaration of CResourceData + **************************************************************************************************************************/ + + class CResourceDataGroup : public virtual IResourceDataGroup, public virtual CBase { + NMR::PKeyStoreResourceDataGroup m_pDataGroup; + public: + CResourceDataGroup(NMR::PKeyStoreResourceDataGroup const & dg); + + // Inherited via IResourceDataGroup + virtual IAccessRight * AddAccessRight(IConsumer * pConsumer, const Lib3MF::eWrappingAlgorithm eWrappingAlgorithm, const Lib3MF::eMgfAlgorithm eMgfAlgorithm, const Lib3MF::eDigestMethod eDigestMethod) override; + virtual IAccessRight * FindAccessRightByConsumer(IConsumer * pConsumerInstance) override; + virtual void RemoveAccessRight(IConsumer * pConsumerInstance) override; + virtual std::string GetKeyUUID() override; + + + inline NMR::PKeyStoreResourceDataGroup resourceDataGroup() const { + return m_pDataGroup; + } + + }; + } +} + + +#endif // !__LIB3MF_RESOURCEDATAGROUP diff --git a/Include/API/lib3mf_resourceiterator.hpp b/Include/API/lib3mf_resourceiterator.hpp new file mode 100644 index 0000000..0641172 --- /dev/null +++ b/Include/API/lib3mf_resourceiterator.hpp @@ -0,0 +1,93 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CResourceIterator + +*/ + + +#ifndef __LIB3MF_RESOURCEITERATOR +#define __LIB3MF_RESOURCEITERATOR + +#include "lib3mf_interfaces.hpp" +#include "lib3mf_base.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + + +// Include custom headers here. +#include "Model/Classes/NMR_ModelResource.h" + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CResourceIterator +**************************************************************************************************************************/ + +class CResourceIterator : public virtual IResourceIterator, public virtual CBase { + +private: + std::vector m_pResources; + Lib3MF_int32 m_nCurrentIndex; + +protected: + virtual NMR::PModelResource GetCurrentResource(); +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + CResourceIterator(); + + void addResource(NMR::PModelResource pResource); + + /** + * Public member functions to implement. + */ + + bool MoveNext (); + + bool MovePrevious (); + + IResource * GetCurrent (); + + IResourceIterator * Clone (); + + Lib3MF_uint64 Count(); + +}; + +} +} + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_RESOURCEITERATOR diff --git a/Include/API/lib3mf_slice.hpp b/Include/API/lib3mf_slice.hpp new file mode 100644 index 0000000..d329264 --- /dev/null +++ b/Include/API/lib3mf_slice.hpp @@ -0,0 +1,104 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CSlice + +*/ + + +#ifndef __LIB3MF_SLICE +#define __LIB3MF_SLICE + +#include "lib3mf_interfaces.hpp" +#include "lib3mf_base.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + + +// Include custom headers here. +#include "Model/Classes/NMR_ModelSlice.h" + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CSlice +**************************************************************************************************************************/ + +class CSlice : public virtual ISlice, public virtual CBase { +private: + + /** + * Put private members here. + */ + NMR::PSlice m_pSlice; + +protected: + + /** + * Put protected members here. + */ + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + CSlice(NMR::PSlice); + + /** + * Public member functions to implement. + */ + + void SetVertices (const Lib3MF_uint64 nVerticesBufferSize, const sLib3MFPosition2D * pVerticesBuffer); + + void GetVertices (Lib3MF_uint64 nVerticesBufferSize, Lib3MF_uint64* pVerticesNeededCount, sLib3MFPosition2D * pVerticesBuffer); + + Lib3MF_uint64 GetVertexCount (); + + Lib3MF_uint64 GetPolygonCount(); + + Lib3MF_uint64 AddPolygon(const Lib3MF_uint64 nIndicesBufferSize, const Lib3MF_uint32 * pIndicesBuffer); + + void SetPolygonIndices (const Lib3MF_uint64 nIndex, const Lib3MF_uint64 nIndicesBufferSize, const Lib3MF_uint32 * pIndicesBuffer); + + void GetPolygonIndices (const Lib3MF_uint64 nIndex, Lib3MF_uint64 nIndicesBufferSize, Lib3MF_uint64* pIndicesNeededCount, Lib3MF_uint32 * pIndicesBuffer); + + Lib3MF_uint64 GetPolygonIndexCount (const Lib3MF_uint64 nIndex); + + double GetZTop(); +}; + +} // namespace Impl +} // namespace Lib3MF + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_SLICE diff --git a/Include/API/lib3mf_slicestack.hpp b/Include/API/lib3mf_slicestack.hpp new file mode 100644 index 0000000..3221ddb --- /dev/null +++ b/Include/API/lib3mf_slicestack.hpp @@ -0,0 +1,108 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CSliceStack + +*/ + + +#ifndef __LIB3MF_SLICESTACK +#define __LIB3MF_SLICESTACK + +#include "lib3mf_interfaces.hpp" + +// Parent classes +#include "lib3mf_resource.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +// Include custom headers here. +#include "Model/Classes/NMR_ModelSliceStack.h" + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CSliceStack +**************************************************************************************************************************/ + +class CSliceStack : public virtual ISliceStack, public virtual CResource { +private: + + /** + * Put private members here. + */ + +protected: + + /** + * Put protected members here. + */ + NMR::PModelSliceStack sliceStack(); + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + CSliceStack(NMR::PModelSliceStack pSliceStack); + + + /** + * Public member functions to implement. + */ + + double GetBottomZ(); + + Lib3MF_uint64 GetSliceCount (); + + ISlice * AddSlice(const double fZTop); + + ISlice * GetSlice (const Lib3MF_uint64 nSliceIndex); + + Lib3MF_uint64 GetSliceRefCount(); + + void AddSliceStackReference(ISliceStack* pTheSliceStack) ; + + ISliceStack * GetSliceStackReference(const Lib3MF_uint64 nSliceRefIndex); + + void CollapseSliceReferences(); + + virtual void SetOwnPath(const std::string & sPath); + + virtual std::string GetOwnPath(); +}; + +} // namespace Impl +} // namespace Lib3MF + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_SLICESTACK diff --git a/Include/API/lib3mf_slicestackiterator.hpp b/Include/API/lib3mf_slicestackiterator.hpp new file mode 100644 index 0000000..ab1c589 --- /dev/null +++ b/Include/API/lib3mf_slicestackiterator.hpp @@ -0,0 +1,89 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CSliceStackIterator + +*/ + + +#ifndef __LIB3MF_SLICESTACKITERATOR +#define __LIB3MF_SLICESTACKITERATOR + +#include "lib3mf_interfaces.hpp" + +// Parent classes +#include "lib3mf_resourceiterator.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +// Include custom headers here. + + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CSliceStackIterator +**************************************************************************************************************************/ + +class CSliceStackIterator : public virtual ISliceStackIterator, public virtual CResourceIterator { +private: + + /** + * Put private members here. + */ + +protected: + + /** + * Put protected members here. + */ + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + + + /** + * Public member functions to implement. + */ + + ISliceStack * GetCurrentSliceStack (); + +}; + +} // namespace Impl +} // namespace Lib3MF + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_SLICESTACKITERATOR diff --git a/Include/API/lib3mf_texture2d.hpp b/Include/API/lib3mf_texture2d.hpp new file mode 100644 index 0000000..1bd4123 --- /dev/null +++ b/Include/API/lib3mf_texture2d.hpp @@ -0,0 +1,105 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CTexture2D + +*/ + + +#ifndef __LIB3MF_TEXTURE2D +#define __LIB3MF_TEXTURE2D + +#include "lib3mf_interfaces.hpp" + +// Parent classes +#include "lib3mf_resource.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +// Include custom headers here. +#include "Model/Classes/NMR_ModelTexture2D.h" + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CTexture2D +**************************************************************************************************************************/ + +class CTexture2D : public virtual ITexture2D, public virtual CResource { +private: + + /** + * Put private members here. + */ + +protected: + + /** + * Put protected members here. + */ + NMR::PModelTexture2DResource texture(); + + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + CTexture2D(NMR::PModelTexture2DResource pResource); + + /** + * Public member functions to implement. + */ + + IAttachment * GetAttachment (); + + void SetAttachment (IAttachment* pAttachment); + + eLib3MFTextureType GetContentType (); + + void SetContentType (const eLib3MFTextureType eContentType); + + void GetTileStyleUV (eLib3MFTextureTileStyle & eTileStyleU, eLib3MFTextureTileStyle & eTileStyleV); + + void SetTileStyleUV (const eLib3MFTextureTileStyle eTileStyleU, const eLib3MFTextureTileStyle eTileStyleV); + + eLib3MFTextureFilter GetFilter (); + + void SetFilter (const eLib3MFTextureFilter eFilter); + +}; + +} +} + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_TEXTURE2D diff --git a/Include/API/lib3mf_texture2dgroup.hpp b/Include/API/lib3mf_texture2dgroup.hpp new file mode 100644 index 0000000..6553832 --- /dev/null +++ b/Include/API/lib3mf_texture2dgroup.hpp @@ -0,0 +1,101 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CTexture2DGroup + +*/ + + +#ifndef __LIB3MF_TEXTURE2DGROUP +#define __LIB3MF_TEXTURE2DGROUP + +#include "lib3mf_interfaces.hpp" + +// Parent classes +#include "lib3mf_resource.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +// Include custom headers here. +#include "Model/Classes/NMR_ModelTexture2DGroup.h" + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CTexture2DGroup +**************************************************************************************************************************/ + +class CTexture2DGroup : public virtual ITexture2DGroup, public virtual CResource { +private: + + /** + * Put private members here. + */ + +protected: + + /** + * Put protected members here. + */ + NMR::CModelTexture2DGroupResource& texture2DGroup(); + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + CTexture2DGroup(NMR::PModelTexture2DGroupResource pResource); + + + /** + * Public member functions to implement. + */ + + ITexture2D * GetTexture2D(); + + Lib3MF_uint32 GetCount (); + + void GetAllPropertyIDs (Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer); + + Lib3MF_uint32 AddTex2Coord (const sLib3MFTex2Coord UVCoordinate); + + sLib3MFTex2Coord GetTex2Coord (const Lib3MF_uint32 nPropertyID); + + void RemoveTex2Coord(const Lib3MF_uint32 nPropertyID); + +}; + +} // namespace Impl +} // namespace Lib3MF + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_TEXTURE2DGROUP diff --git a/Include/API/lib3mf_texture2dgroupiterator.hpp b/Include/API/lib3mf_texture2dgroupiterator.hpp new file mode 100644 index 0000000..140ce6a --- /dev/null +++ b/Include/API/lib3mf_texture2dgroupiterator.hpp @@ -0,0 +1,89 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CTexture2DGroupIterator + +*/ + + +#ifndef __LIB3MF_TEXTURE2DGROUPITERATOR +#define __LIB3MF_TEXTURE2DGROUPITERATOR + +#include "lib3mf_interfaces.hpp" + +// Parent classes +#include "lib3mf_resourceiterator.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +// Include custom headers here. + + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CTexture2DGroupIterator +**************************************************************************************************************************/ + +class CTexture2DGroupIterator : public virtual ITexture2DGroupIterator, public virtual CResourceIterator { +private: + + /** + * Put private members here. + */ + +protected: + + /** + * Put protected members here. + */ + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + + + /** + * Public member functions to implement. + */ + + ITexture2DGroup * GetCurrentTexture2DGroup (); + +}; + +} // namespace Impl +} // namespace Lib3MF + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_TEXTURE2DGROUPITERATOR diff --git a/Include/API/lib3mf_texture2diterator.hpp b/Include/API/lib3mf_texture2diterator.hpp new file mode 100644 index 0000000..74a8f28 --- /dev/null +++ b/Include/API/lib3mf_texture2diterator.hpp @@ -0,0 +1,89 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CTexture2DIterator + +*/ + + +#ifndef __LIB3MF_TEXTURE2DITERATOR +#define __LIB3MF_TEXTURE2DITERATOR + +#include "lib3mf_interfaces.hpp" + +// Parent classes +#include "lib3mf_resourceiterator.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + +// Include custom headers here. + + +namespace Lib3MF { +namespace Impl { + + +/************************************************************************************************************************* + Class declaration of CTexture2DIterator +**************************************************************************************************************************/ + +class CTexture2DIterator : public virtual ITexture2DIterator, public virtual CResourceIterator { +private: + + /** + * Put private members here. + */ + +protected: + + /** + * Put protected members here. + */ + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + + + /** + * Public member functions to implement. + */ + + ITexture2D * GetCurrentTexture2D (); + +}; + +} // namespace Impl +} // namespace Lib3MF + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_TEXTURE2DITERATOR diff --git a/Include/API/lib3mf_utils.hpp b/Include/API/lib3mf_utils.hpp new file mode 100644 index 0000000..235df5d --- /dev/null +++ b/Include/API/lib3mf_utils.hpp @@ -0,0 +1,60 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This file contains utilties used in the API of lib3mf + +*/ + + +#ifndef __LIB3MF_UTILS +#define __LIB3MF_UTILS + +#include "lib3mf_interfaces.hpp" + +// Include custom headers here. +#include "Common/Math/NMR_Matrix.h" +#include "Common/NMR_SecureContentTypes.h" + +namespace Lib3MF { + +NMR::NMATRIX3 TransformToMatrix(const sLib3MFTransform Transform); + +sLib3MFTransform MatrixToTransform(const NMR::NMATRIX3 matrix); + +eLib3MFEncryptionAlgorithm translateEncryptionAlgorithm(const NMR::eKeyStoreEncryptAlgorithm algorithm); + +NMR::eKeyStoreEncryptAlgorithm translateEncryptionAlgorithm(const eLib3MFEncryptionAlgorithm algorithm); + +eLib3MFWrappingAlgorithm translateWrappingAlgorithm(const NMR::eKeyStoreWrapAlgorithm algorithm); + +NMR::eKeyStoreWrapAlgorithm translateWrappingAlgorithm(const eLib3MFWrappingAlgorithm algorithm); + +eLib3MFCompression translateCompression(bool compression); +bool translateCompression(const eLib3MFCompression compression); + +} + +#endif // __LIB3MF_UTILS diff --git a/Include/API/lib3mf_writer.hpp b/Include/API/lib3mf_writer.hpp new file mode 100644 index 0000000..6cf997f --- /dev/null +++ b/Include/API/lib3mf_writer.hpp @@ -0,0 +1,121 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is the class declaration of CWriter + +*/ + + +#ifndef __LIB3MF_WRITER +#define __LIB3MF_WRITER + +#include "lib3mf_interfaces.hpp" +#include "lib3mf_base.hpp" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4250) +#endif + + +// Include custom headers here. +#include "Model/Writer/NMR_ModelWriter.h" +#include "Model/Writer/NMR_ModelWriter_3MF_Native.h" +#include "Model/Writer/NMR_ModelWriter_STL.h" + +namespace NMR { + class CExportStreamMemory; + using PExportStreamMemory = std::shared_ptr; +} + +namespace Lib3MF { +namespace Impl { + +/************************************************************************************************************************* + Class declaration of CWriter +**************************************************************************************************************************/ + +class CWriter : public virtual IWriter, public virtual CBase { +private: + + /** + * Put private members here. + */ + NMR::PModelWriter m_pWriter; + + NMR::PExportStreamMemory momentBuffer; +protected: + + /** + * Put protected members here. + */ + +public: + + /** + * Put additional public members here. They will not be visible in the external API. + */ + CWriter(std::string sWriterClass, NMR::PModel model); + + NMR::CModelWriter& writer(); + /** + * Public member functions to implement. + */ + + void WriteToFile(const std::string & sFilename) override; + + Lib3MF_uint64 GetStreamSize() override; + + void WriteToBuffer(Lib3MF_uint64 nBufferBufferSize, Lib3MF_uint64* pBufferNeededCount, Lib3MF_uint8 * pBufferBuffer) override; + + void WriteToCallback(const Lib3MFWriteCallback pTheWriteCallback, const Lib3MFSeekCallback pTheSeekCallback, const Lib3MF_pvoid pUserData) override; + + void SetProgressCallback(const Lib3MFProgressCallback pProgressCallback, const Lib3MF_pvoid pUserData) override; + + Lib3MF_uint32 GetDecimalPrecision() override; + + void SetDecimalPrecision(const Lib3MF_uint32 nDecimalPrecision) override; + + void AddKeyWrappingCallback(const std::string & sConsumerID, const Lib3MF::KeyWrappingCallback pTheCallback, const Lib3MF_pvoid pUserData); + + void SetContentEncryptionCallback(const Lib3MF::ContentEncryptionCallback pTheCallback, const Lib3MF_pvoid pUserData); + + void SetStrictModeActive(const bool bStrictModeActive); + + bool GetStrictModeActive(); + + std::string GetWarning(const Lib3MF_uint32 nIndex, Lib3MF_uint32 & nErrorCode); + + Lib3MF_uint32 GetWarningCount(); + +}; + +} +} + +#ifdef _MSC_VER +#pragma warning(pop) +#endif +#endif // __LIB3MF_WRITER diff --git a/Include/Common/3MF_ProgressMonitor.h b/Include/Common/3MF_ProgressMonitor.h new file mode 100644 index 0000000..ada9ae2 --- /dev/null +++ b/Include/Common/3MF_ProgressMonitor.h @@ -0,0 +1,81 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: Progress Monitor + +--*/ + +#ifndef __NMR_PROGRESSMONITOR +#define __NMR_PROGRESSMONITOR + +#include "Common/3MF_ProgressTypes.h" + +#include +#include +#include +#include + +namespace NMR +{ +#define PROGRESS_SLICEUPDATE 1000 +#define PROGRESS_NODEUPDATE 100000 +#define PROGRESS_TRIANGLEUPDATE 100000 +#define PROGRESS_READUPDATE 20000 +#define PROGRESS_READSLICESUPDATE 100 +#define PROGRESS_READBUFFERUPDATE 100 + + class CProgressMonitor + { + public: + CProgressMonitor(); + void SetProgressCallback(Lib3MFProgressCallback callback, void* userData); + void ClearProgressCallback(); + // Returns true if the last callback call returned false + bool WasAborted(); + bool QueryCancelled(bool throwIfCancelled); + bool ReportProgressAndQueryCancelled(bool throwIfCancelled); + + void IncrementProgress(double dProgressIncrement); + void SetProgressIdentifier(ProgressIdentifier identifier); + void SetMaxProgress(double); + void DecreaseMaxProgress(double); + + static void GetProgressMessage(ProgressIdentifier progressIdentifier, std::string& progressString); + + private: + ProgressIdentifier m_eProgressIdentifier; + double m_dProgress; + double m_dProgressMax; + Lib3MFProgressCallback m_progressCallback; + void* m_userData; + bool m_lastCallbackResult; + std::mutex m_callbackMutex; + }; + + typedef std::shared_ptr PProgressMonitor; +}; + +#endif // __NMR_PROGRESSMONITOR diff --git a/Include/Common/3MF_ProgressTypes.h b/Include/Common/3MF_ProgressTypes.h new file mode 100644 index 0000000..2fc2ba4 --- /dev/null +++ b/Include/Common/3MF_ProgressTypes.h @@ -0,0 +1,67 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: Progress Types + +--*/ + +#pragma once + +#include + +namespace NMR +{ + enum ProgressIdentifier { + PROGRESS_QUERYCANCELED = 0, + PROGRESS_DONE, + PROGRESS_CLEANUP, + PROGRESS_READSTREAM, + PROGRESS_EXTRACTOPCPACKAGE, + PROGRESS_READNONROOTMODELS, + PROGRESS_READROOTMODEL, + PROGRESS_READRESOURCES, + PROGRESS_READMESH, + PROGRESS_READSLICES, + PROGRESS_READBUILD, + PROGRESS_READCUSTOMATTACHMENTS, + PROGRESS_READTEXTURETACHMENTS, + PROGRESS_CREATEOPCPACKAGE, + PROGRESS_WRITEMODELSTOSTREAM, + PROGRESS_WRITEROOTMODEL, + PROGRESS_WRITENONROOTMODELS, + PROGRESS_WRITEATTACHMENTS, + PROGRESS_WRITECONTENTTYPES, + PROGRESS_WRITEOBJECTS, + PROGRESS_WRITENODES, + PROGRESS_WRITETRIANGLES, + PROGRESS_WRITESLICES + }; + + // Matches dll interface type, always modify both! + // If the first parameter is -1, it does not indicate progress;In that case + // it must only be used to stop the execution of the calling function. + typedef std::function Lib3MFProgressCallback; +}; diff --git a/Include/Common/Math/NMR_Geometry.h b/Include/Common/Math/NMR_Geometry.h new file mode 100644 index 0000000..6a8ace3 --- /dev/null +++ b/Include/Common/Math/NMR_Geometry.h @@ -0,0 +1,117 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_Geometry.h defines all basic structures for vector and matrix calculations. + +--*/ + +#ifndef __NMR_GEOMETRY +#define __NMR_GEOMETRY + +#include "Common/NMR_Types.h" +#include "Common/NMR_Local.h" + +#define NMR_VECTOR_MINNORMALIZELENGTH 1.0e-10f +#define NMR_VECTOR_DEFAULTUNITS 0.001f +#define NMR_VECTOR_MINUNITS 0.00001f +#define NMR_VECTOR_MAXUNITS 1000.0f +#define NMR_OUTBOX_MAXCOORDINATE 10000000000.0f + +namespace NMR { + + typedef union { + nfFloat m_fields[2]; + struct { nfFloat x; nfFloat y; } m_values; + } NVEC2; + + typedef union { + nfFloat m_fields[3]; + struct { nfFloat x; nfFloat y; nfFloat z; } m_values; + } NVEC3; + + typedef union { + nfDouble m_fields[3]; + struct { nfDouble x; nfDouble y; nfDouble z; } m_values; + } NVEC3D; + + typedef union { + nfInt32 m_fields[2]; + struct { nfInt32 x; nfInt32 y; } m_values; + } NVEC2I; + + typedef union { + nfInt32 m_fields[3]; + struct { nfInt32 x; nfInt32 y; nfInt32 z; } m_values; + } NVEC3I; + + typedef union { + nfInt64 m_fields[3]; + struct { nfInt64 x; nfInt64 y; nfInt64 z; } m_values; + } NVEC3I64; + + typedef struct { + nfFloat m_fields[3][3]; + } NMATRIX2; + + typedef struct { + nfFloat m_fields[2][2]; + } NLINMATRIX2; + + typedef struct { + nfFloat m_fields[4][4]; + } NMATRIX3; + + typedef struct { + NVEC2 m_min; + NVEC2 m_max; + } NOUTBOX2; + + typedef struct { + NVEC3 m_min; + NVEC3 m_max; + } NOUTBOX3; + + typedef struct { + NVEC2I m_vMin; + NVEC2I m_vMax; + } NOUTBOX2I; + + typedef struct { + NVEC3I m_vMin; + NVEC3I m_vMax; + } NOUTBOX3I; + + typedef struct { + NVEC2 m_vPoints[3]; + NLINMATRIX2 m_vMatrix; + NLINMATRIX2 m_vInvMatrix; + } NBARYCENTRICTRIANGLE; + +} + +#endif // __NMR_GEOMETRY diff --git a/Include/Common/Math/NMR_Matrix.h b/Include/Common/Math/NMR_Matrix.h new file mode 100644 index 0000000..573420e --- /dev/null +++ b/Include/Common/Math/NMR_Matrix.h @@ -0,0 +1,77 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_Matrix.h defines all needed matrix calculations and transforms for +2D and 3D vectors. + +--*/ + +#ifndef __NMR_MATRIX +#define __NMR_MATRIX + +#include "Common/Math/NMR_Geometry.h" +#include + +#define NMR_MATRIX_MINDETERMINANT 0.00001f +#define NMR_MATRIX_IDENTITYTHRESHOLD 0.0000001 + +namespace NMR { + + NMATRIX2 fnMATRIX2_identity(); + NMATRIX2 fnMATRIX2_rotation(_In_ const nfFloat fAngle); + NMATRIX2 fnMATRIX2_translation(_In_ const NVEC2 vTranslation); + NMATRIX2 fnMATRIX2_uniformscale(_In_ nfFloat fScale); + NMATRIX2 fnMATRIX2_scale(_In_ nfFloat fScaleX, _In_ nfFloat fScaleY); + NMATRIX2 fnMATRIX2_transformation(_In_ const nfFloat fAngle, _In_ const NVEC2 vTranslation); + NMATRIX2 fnMATRIX2_multiply(_In_ const NMATRIX2 mMatrix1, _In_ const NMATRIX2 mMatrix2); + NVEC2 fnMATRIX2_apply(_In_ const NMATRIX2 mMatrix, _In_ const NVEC2 vVector); + + NLINMATRIX2 fnLINMATRIX2_identity(); + NLINMATRIX2 fnLINMATRIX2_rotation(_In_ const nfFloat fAngle); + NLINMATRIX2 fnLINMATRIX2_uniformscale(_In_ nfFloat fScale); + NLINMATRIX2 fnLINMATRIX2_scale(_In_ nfFloat fScaleX, _In_ nfFloat fScaleY); + NLINMATRIX2 fnLINMATRIX2_multiply(_In_ const NLINMATRIX2 mMatrix1, _In_ const NLINMATRIX2 mMatrix2); + NVEC2 fnLINMATRIX2_apply(_In_ const NLINMATRIX2 mMatrix, _In_ const NVEC2 vVector); + NLINMATRIX2 fnLINMATRIX2_invert(_In_ const NLINMATRIX2 mMatrix, _In_ nfBool bFailIfSingular); + + NMATRIX3 fnMATRIX3_identity(); + NMATRIX3 fnMATRIX3_rotation(_In_ const NVEC3 vAxis, _In_ const nfFloat fAngle); + NMATRIX3 fnMATRIX3_translation(_In_ const NVEC3 vTranslation); + NMATRIX3 fnMATRIX3_transformation(_In_ const NVEC3 vAxis, _In_ const nfFloat fAngle, _In_ const NVEC3 vTranslation); + NMATRIX3 fnMATRIX3_multiply(_In_ const NMATRIX3 mMatrix1, _In_ const NMATRIX3 mMatrix2); + NMATRIX3 fnMATRIX3_uniformscale(_In_ nfFloat fScale); + NMATRIX3 fnMATRIX3_scale(_In_ nfFloat fScaleX, _In_ nfFloat fScaleY, _In_ nfFloat fScaleZ); + NVEC3 fnMATRIX3_apply(_In_ const NMATRIX3 mMatrix, _In_ const NVEC3 vVector); + nfBool fnMATRIX3_isIdentity(_In_ const NMATRIX3 mMatrix); + std::string fnMATRIX3_toString(_In_ const NMATRIX3 mMatrix); + NMATRIX3 fnMATRIX3_fromString(_In_ const std::string sString); + + nfBool fnMATRIX3_isplanar(_In_ const NMATRIX3 mMatrix); +} + +#endif // __NMR_MATRIX diff --git a/Include/Common/Math/NMR_PairMatchingTree.h b/Include/Common/Math/NMR_PairMatchingTree.h new file mode 100644 index 0000000..cb8558c --- /dev/null +++ b/Include/Common/Math/NMR_PairMatchingTree.h @@ -0,0 +1,68 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_PairMatchingTree.h defines a n-log-n tree class which is able to identify +duplicate pairs of numbers in a given data set. + +--*/ + +#ifndef __NMR_PAIRMATCHINGTREE +#define __NMR_PAIRMATCHINGTREE + +#include "Common/Math/NMR_Geometry.h" +#include "Common/NMR_Types.h" + +#include + +namespace NMR { + + typedef struct { + nfInt32 m_pair[2]; + } PAIRMATCHINGTREEENTRY; + + bool operator< (_In_ const PAIRMATCHINGTREEENTRY & entry1, _In_ const PAIRMATCHINGTREEENTRY & entry2); + + class CPairMatchingTree { + private: + std::map m_entries; + public: + CPairMatchingTree(); + ~CPairMatchingTree(); + + void addMatch(_In_ nfInt32 data1, _In_ nfInt32 data2, _In_ nfInt32 param); + _Success_(return) nfBool checkMatch(_In_ nfInt32 data1, _In_ nfInt32 data2, _Out_opt_ nfInt32 ¶m); + void deleteMatch(_In_ nfInt32 data1, _In_ nfInt32 data2); + }; + +} + +#endif // __NMR_PAIRMATCHINGTREE + + + + diff --git a/Include/Common/Math/NMR_Vector.h b/Include/Common/Math/NMR_Vector.h new file mode 100644 index 0000000..a4ae840 --- /dev/null +++ b/Include/Common/Math/NMR_Vector.h @@ -0,0 +1,131 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_Vector.cpp implements all needed direct operations on 2D and 3D vectors. + +--*/ + +#ifndef __NMR_VECTOR +#define __NMR_VECTOR + +#include "Common/Math/NMR_Geometry.h" + +namespace NMR { + + NVEC2 fnVEC2_make(_In_ nfFloat fX, _In_ nfFloat fY); + NVEC2 fnVEC2_add(_In_ const NVEC2 vVector1, _In_ const NVEC2 vVector2); + NVEC2 fnVEC2_sub(_In_ const NVEC2 vMinuend, _In_ const NVEC2 vSubtrahend); + NVEC2 fnVEC2_scale(_In_ const NVEC2 vVector, _In_ nfFloat vFactor); + NVEC2 fnVEC2_combine(_In_ const NVEC2 vVector1, _In_ nfFloat vFactor1, _In_ const NVEC2 vVector2, _In_ nfFloat vFactor2); + nfFloat fnVEC2_dotproduct(_In_ const NVEC2 vVector1, _In_ const NVEC2 vVector2); + nfFloat fnVEC2_crossproduct(_In_ const NVEC2 vVector1, _In_ const NVEC2 vVector2); + nfFloat fnVEC2_length(_In_ const NVEC2 vVector); + nfFloat fnVEC2_distance(_In_ const NVEC2 vPoint1, _In_ const NVEC2 vPoint2); + NVEC2 fnVEC2_normalize(_In_ const NVEC2 vVector); + + NVEC3 fnVEC3_make(_In_ nfFloat fX, _In_ nfFloat fY, _In_ nfFloat fZ); + NVEC3 fnVEC3_add(_In_ const NVEC3 vVector1, _In_ const NVEC3 vVector2); + NVEC3 fnVEC3_sub(_In_ const NVEC3 vMinuend, _In_ const NVEC3 vSubtrahend); + NVEC3 fnVEC3_scale(_In_ const NVEC3 vVector, _In_ nfFloat vFactor); + NVEC3 fnVEC3_combine(_In_ const NVEC3 vVector1, _In_ nfFloat vFactor1, _In_ const NVEC3 vVector2, _In_ nfFloat vFactor2); + nfFloat fnVEC3_dotproduct(_In_ const NVEC3 vVector1, _In_ const NVEC3 vVector2); + NVEC3 fnVEC3_crossproduct(_In_ const NVEC3 vVector1, _In_ const NVEC3 vVector2); + nfFloat fnVEC3_length(_In_ const NVEC3 vVector); + nfFloat fnVEC3_distance(_In_ const NVEC3 vPoint1, _In_ const NVEC3 vPoint2); + NVEC3 fnVEC3_normalize(_In_ const NVEC3 vVector); + NVEC3 fnVEC3_calcTriangleNormal(_In_ const NVEC3 vVector1, _In_ const NVEC3 vVector2, _In_ const NVEC3 vVector3); + + NVEC2I fnVEC2I_make(_In_ nfInt32 nX, _In_ nfInt32 nY); + NVEC2I fnVEC2I_floor(_In_ NVEC2 vVector, _In_ nfFloat fUnits); + NVEC2 fnVEC2I_uncast(_In_ NVEC2I vVector, _In_ nfFloat fUnits); + NVEC2I fnVEC2I_add(_In_ const NVEC2I vVector1, _In_ const NVEC2I vVector2); + NVEC2I fnVEC2I_sub(_In_ const NVEC2I vMinuend, _In_ const NVEC2I vSubtrahend); + NVEC2I fnVEC2I_scale(_In_ const NVEC2I vVector, _In_ nfInt32 vFactor); + nfInt64 fnVEC2I_dotproduct(_In_ const NVEC2I vVector1, _In_ const NVEC2I vVector2); + nfFloat fnVEC2I_distance(_In_ const NVEC2I vPoint1, _In_ const NVEC2I vPoint2); + nfFloat fnVEC2I_length(_In_ const NVEC2I vVector); + + NVEC3I fnVEC3I_make(_In_ nfInt32 nX, _In_ nfInt32 nY, _In_ nfInt32 nZ); + NVEC3I fnVEC3I_floor(_In_ NVEC3 vVector, _In_ nfFloat fUnits); + NVEC3I fnVEC3I_round(_In_ NVEC3 vVector, _In_ nfFloat fUnits); + NVEC3 fnVEC3I_uncast(_In_ NVEC3I vVector, _In_ nfFloat fUnits); + NVEC3I fnVEC3I_add(_In_ const NVEC3I vVector1, _In_ const NVEC3I vVector2); + NVEC3I fnVEC3I_sub(_In_ const NVEC3I vMinuend, _In_ const NVEC3I vSubtrahend); + NVEC3I fnVEC3I_scale(_In_ const NVEC3I vVector, _In_ nfInt32 vFactor); + nfInt64 fnVEC3I_dotproduct(_In_ const NVEC3I vVector1, _In_ const NVEC3I vVector2); + NVEC3I fnVEC3I_crossproduct(_In_ const NVEC3I vVector1, _In_ const NVEC3I vVector2); + NVEC3I64 fnVEC3I_crossproduct64(_In_ const NVEC3I vVector1, _In_ const NVEC3I vVector2); + nfFloat fnVEC3I_length(_In_ const NVEC3I vVector); + nfFloat fnVEC3I_distance(_In_ const NVEC3I vPoint1, _In_ const NVEC3I vPoint2); + nfInt32 fnVEC3I_comparelexicographic(_In_ const NVEC3I vVector1, _In_ const NVEC3I vVector2); + nfBool fnVEC3I_iszero(_In_ const NVEC3I vVector); + nfBool fnVEC3I_triangleIsDegenerate(_In_ const NVEC3I vVector1, _In_ const NVEC3I vVector2, _In_ const NVEC3I vVector3); + NVEC3I fnVEC3I_setOrderedVector(_In_ nfInt32 nValue1, _In_ nfInt32 nValue2, _In_ nfInt32 nValue3); + nfBool fnVEC3I_checkForCollinearity(_In_ NVEC3I vVector1, _In_ NVEC3I vVector2); + NVEC2 operator+ (_In_ const NVEC2 vVector1, _In_ const NVEC2 vVector2); + NVEC2 operator- (_In_ const NVEC2 vMinuend, _In_ const NVEC2 vSubtrahend); + NVEC2 operator* (_In_ const NVEC2 vVector, _In_ nfFloat vFactor); + NVEC2 operator* (_In_ nfFloat vFactor, _In_ const NVEC2 vVector); + nfFloat operator* (_In_ const NVEC2 vVector1, _In_ const NVEC2 vVector2); + + NVEC2I operator+ (_In_ const NVEC2I vVector1, _In_ const NVEC2I vVector2); + NVEC2I operator- (_In_ const NVEC2I vMinuend, _In_ const NVEC2I vSubtrahend); + NVEC2I operator* (_In_ const NVEC2I vVector, _In_ nfInt32 vFactor); + NVEC2I operator* (_In_ nfInt32 vFactor, _In_ const NVEC2I vVector); + nfUint64 operator* (_In_ const NVEC2I vVector1, _In_ const NVEC2I vVector2); + + NVEC3 operator+ (_In_ const NVEC3 vVector1, _In_ const NVEC3 vVector2); + NVEC3 operator- (_In_ const NVEC3 vMinuend, _In_ const NVEC3 vSubtrahend); + NVEC3 operator* (_In_ const NVEC3 vVector, nfFloat vFactor); + NVEC3 operator* (nfFloat vFactor, _In_ const NVEC3 vVector); + nfFloat operator* (_In_ const NVEC3 vVector1, _In_ const NVEC3 vVector2); + + NVEC3I operator+ (_In_ const NVEC3I vVector1, _In_ const NVEC3I vVector2); + NVEC3I operator- (_In_ const NVEC3I vMinuend, _In_ const NVEC3I vSubtrahend); + NVEC3I operator* (_In_ const NVEC3I vVector, _In_ nfInt32 vFactor); + NVEC3I operator* (_In_ nfInt32 vFactor, _In_ const NVEC3I vVector); + nfUint64 operator* (_In_ const NVEC3I vVector1, _In_ const NVEC3I vVector2); + + nfInt32 fnInt32_sign(_In_ nfInt32 nValue); + nfInt32 fnInt64_sign(_In_ nfInt64 nValue); + nfInt32 fnInt32_compare(_In_ nfInt32 nValue1, _In_ nfInt32 nValue2); + nfInt32 fnInt64_compare(_In_ nfInt64 nValue1, _In_ nfInt64 nValue2); + + void fnOutboxInitialize(_Out_ NOUTBOX3 &oOutbox); + void fnOutboxMergeVector(_Inout_ NOUTBOX3 &oOutbox, _In_ NVEC3 vVector); + void fnOutboxMergeOutbox(_Inout_ NOUTBOX3 &oOutboxDest, _In_ NOUTBOX3 &oOutboxSource); + nfBool fnOutboxIsValid(_In_ const NOUTBOX3 oOutbox); + + void fnOutbox3IMergeVector(_Inout_ NOUTBOX3I &oOutbox, _In_ NVEC3I vVector); + void fnOutbox3IMergeOutbox(_Inout_ NOUTBOX3I &oOutboxDest, _In_ NOUTBOX3I &oOutboxSource); + NOUTBOX3I fnCalcTriangleOutbox3I(_In_ const NVEC3I vVector1, _In_ const NVEC3I vVector2, _In_ const NVEC3I vVector3); + nfBool fnOutbox3IDoIntersect(_In_ const NOUTBOX3I oOutbox1, _In_ const NOUTBOX3I oOutbox2); + +} + +#endif // __NMR_VECTOR diff --git a/Include/Common/Math/NMR_VectorTree.h b/Include/Common/Math/NMR_VectorTree.h new file mode 100644 index 0000000..b96ad83 --- /dev/null +++ b/Include/Common/Math/NMR_VectorTree.h @@ -0,0 +1,79 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_VectorTree.h defines a n*log(n) lookup tree class to identify vectors by +their position. + +--*/ + +#ifndef __NMR_VECTORTREE +#define __NMR_VECTORTREE + +#include "Common/Math/NMR_Geometry.h" +#include "Common/NMR_Types.h" + +#include + +namespace NMR { + + typedef struct { + NVEC3I m_position; + } VECTORTREEENTRY; + + bool operator< (_In_ const VECTORTREEENTRY & entry1, _In_ const VECTORTREEENTRY & entry2); + + class CVectorTree { + private: + nfFloat m_fUnits; + std::map m_entries; + public: + CVectorTree(); + CVectorTree(_In_ nfFloat fUnits); + + nfFloat getUnits(); + void setUnits(_In_ nfFloat fUnits); + + _Success_(return) nfBool findVector2(_In_ NVEC2 vVector, _Out_opt_ nfUint32 & value); + _Success_(return) nfBool findVector3(_In_ NVEC3 vVector, _Out_opt_ nfUint32 & value); + _Success_(return) nfBool findIntVector2(_In_ NVEC2I vVector, _Out_opt_ nfUint32 & value); + _Success_(return) nfBool findIntVector3(_In_ NVEC3I vVector, _Out_opt_ nfUint32 & value); + + void addVector2(_In_ NVEC2 vVector, _In_ nfUint32 value); + void addVector3(_In_ NVEC3 vVector, _In_ nfUint32 value); + void addIntVector2(_In_ NVEC2I vVector, _In_ nfUint32 value); + void addIntVector3(_In_ NVEC3I vVector, _In_ nfUint32 value); + + void removeVector2(_In_ NVEC2 vVector); + void removeVector3(_In_ NVEC3 vVector); + void removeIntVector2(_In_ NVEC2I vVector); + void removeIntVector3(_In_ NVEC3I vVector); + }; + +} + +#endif // __NMR_VECTORTREE diff --git a/Include/Common/Mesh/NMR_BeamLattice.h b/Include/Common/Mesh/NMR_BeamLattice.h new file mode 100644 index 0000000..b78d639 --- /dev/null +++ b/Include/Common/Mesh/NMR_BeamLattice.h @@ -0,0 +1,70 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_MeshBeamLattice.h defines the class CMeshBeamLattice. + +--*/ + +#ifndef __NMR_MESHBEAMLATTICE +#define __NMR_MESHBEAMLATTICE + +#include "Common/Math/NMR_Geometry.h" +#include "Common/Mesh/NMR_MeshTypes.h" +#include "Common/NMR_Types.h" +#include "Model/Classes/NMR_ModelTypes.h" + +#include + +namespace NMR { + + class CBeamLattice { + private: + friend class CMesh; + + MESHNODES &m_Nodes; // reference to the nodes of the parent mesh + std::unordered_set m_OccupiedNodes; // datastructure used to ensure that balls are only placed at nodes with beams + MESHBEAMS m_Beams; + std::vector m_pBeamSets; + MESHBALLS m_Balls; + + nfDouble m_dMinLength; + eModelBeamLatticeBallMode m_eBallMode; + nfDouble m_dDefaultBallRadius; + public: + CBeamLattice(_In_ MESHNODES &nodes); + + void clearBeams(); + void clearBalls(); + void clear(); + }; + + typedef std::shared_ptr PBeamLattice; + +} + +#endif // __NMR_BEAMLATTICE diff --git a/Include/Common/Mesh/NMR_Mesh.h b/Include/Common/Mesh/NMR_Mesh.h new file mode 100644 index 0000000..628f43d --- /dev/null +++ b/Include/Common/Mesh/NMR_Mesh.h @@ -0,0 +1,130 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_Mesh.h defines the class CMesh. + +The class CMesh is not really a mesh, since it lacks the component edges and the +topological information. It only holds the nodes and the faces (triangles). +Each node, and face have a ID, which allows to identify them. Each face have an +orientation (i.e. the face can look up or look down) and have three nodes. +The orientation is defined by the order of its nodes. + +You can only add nodes and faces to mesh. You cannot remove the existing structure. + +--*/ + +#ifndef __NMR_MESH +#define __NMR_MESH + +#include "Common/Math/NMR_Geometry.h" +#include "Common/Mesh/NMR_MeshTypes.h" +#include "Common/MeshInformation/NMR_MeshInformationHandler.h" +#include "Common/NMR_Types.h" +#include "Common/Mesh/NMR_BeamLattice.h" + +#include + +namespace NMR { + + class CMesh { + private: + MESHNODES m_Nodes; + MESHFACES m_Faces; + CBeamLattice m_BeamLattice; + + PMeshInformationHandler m_pMeshInformationHandler; + + public: + CMesh(); + CMesh(_In_opt_ CMesh * pMesh); + + void mergeMesh(_In_opt_ CMesh * pMesh); + void addToMesh(_In_opt_ CMesh * pMesh); + void mergeMesh(_In_opt_ CMesh * pMesh, _In_ NMATRIX3 mMatrix); + void addToMesh(_In_opt_ CMesh * pMesh, _In_ NMATRIX3 mMatrix); + + _Ret_notnull_ MESHNODE * addNode(_In_ const NVEC3 vPosition); + _Ret_notnull_ MESHNODE * addNode(_In_ const nfFloat posX, _In_ const nfFloat posY, _In_ const nfFloat posZ); + _Ret_notnull_ MESHFACE * addFace(_In_ MESHNODE * pNode1, _In_ MESHNODE * pNode2, _In_ MESHNODE * pNode3); + _Ret_notnull_ MESHFACE * addFace(_In_ nfInt32 nNodeIndex1, _In_ nfInt32 nNodeIndex2, _In_ nfInt32 nNodeIndex3); + _Ret_notnull_ MESHBEAM * addBeam(_In_ MESHNODE * pNode1, _In_ MESHNODE * pNode2, _In_ nfDouble dRadius1, _In_ nfDouble dRadius2, + _In_ nfInt32 eCapMode1, _In_ nfInt32 eCapMode2); + _Ret_notnull_ MESHBALL * addBall(_In_ MESHNODE * pNode, _In_ nfDouble dRadius); + _Ret_notnull_ PBEAMSET addBeamSet(); + + nfUint32 getNodeCount(); + nfUint32 getFaceCount(); + nfUint32 getBeamCount(); + nfUint32 getBallCount(); + nfUint32 getBeamSetCount(); + nfUint32 getOccupiedNodeCount(); + nfBool isNodeOccupied(_In_ nfUint32 nIdx); + + _Ret_notnull_ MESHNODE * getNode(_In_ nfUint32 nIdx); + _Ret_notnull_ MESHFACE * getFace(_In_ nfUint32 nIdx); + _Ret_notnull_ MESHBEAM * getBeam(_In_ nfUint32 nIdx); + _Ret_notnull_ MESHBALL * getBall(_In_ nfUint32 nIdx); + _Ret_notnull_ PBEAMSET getBeamSet(_In_ nfUint32 nIdx); + _Ret_notnull_ MESHNODE * getOccupiedNode(_In_ nfUint32 nIdx); + + void setBeamLatticeMinLength(nfDouble dMinLength); + nfDouble getBeamLatticeMinLength(); + + // TODO: make these return sensible values + void setDefaultBeamRadius(nfDouble dRadius); + nfDouble getDefaultBeamRadius(); + void setDefaultBallRadius(nfDouble dBallRadius); + nfDouble getDefaultBallRadius(); + void setBeamLatticeAccuracy(nfDouble dAccuracy); + nfBool getBeamLatticeAccuracy(nfDouble& dAccuracy); + void setBeamLatticeBallMode(eModelBeamLatticeBallMode eBallMode); + eModelBeamLatticeBallMode getBeamLatticeBallMode(); + void setBeamLatticeCapMode(eModelBeamLatticeCapMode eCapMode); + eModelBeamLatticeCapMode getBeamLatticeCapMode(); + + nfBool checkSanity(); + + void clear(); + void clearBeamLattice(); + void clearBeamLatticeBeams(); + void clearBeamLatticeBalls(); + void scanOccupiedNodes(); + void validateBeamLatticeBalls(); + + _Ret_maybenull_ CMeshInformationHandler * getMeshInformationHandler(); + _Ret_notnull_ CMeshInformationHandler * createMeshInformationHandler(); + void clearMeshInformationHandler(); + void patchMeshInformationResources(_In_ std::map &oldToNewMapping); + void extendOutbox(_Out_ NOUTBOX3& vOutBox, _In_ const NMATRIX3 mAccumulatedMatrix); + }; + + typedef std::shared_ptr PMesh; + +} + +#endif // __NMR_MESH diff --git a/Include/Common/Mesh/NMR_MeshBuilder.h b/Include/Common/Mesh/NMR_MeshBuilder.h new file mode 100644 index 0000000..3c63f28 --- /dev/null +++ b/Include/Common/Mesh/NMR_MeshBuilder.h @@ -0,0 +1,66 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_MeshBuilder.h defines the class CMeshBuilder. + +The class CMeshBuilder is auxiliary class, which construct a valid mesh by adding single faces and nodes. +In addition already existing meshes can be added. + +--*/ + +#ifndef __NMR_MESHBUILDER +#define __NMR_MESHBUILDER + +#include "Common/Mesh/NMR_Mesh.h" +#include "Common/MeshInformation/NMR_MeshInformationHandler.h" +#include "Common/Math/NMR_VectorTree.h" + +namespace NMR { + + class CMeshBuilder { + private: + CVectorTree m_VectorTree; + CPagedVector m_Nodes; + CPagedVector m_Faces; + + public: + CMeshBuilder(); + CMeshBuilder(_In_ nfFloat fUnits); + + nfUint32 addNode(_In_ const NVEC3 vPoint); + nfUint32 addFace(_In_ const NVEC3 vPoint1, _In_ const NVEC3 vPoint2, _In_ const NVEC3 vPoint3); + + PMesh createMesh(_In_ nfBool bIgnoreInvalidFaces); + void addToMesh(_In_ CMesh * pMesh, _In_ nfBool bIgnoreInvalidFaces); + }; + + typedef std::shared_ptr PMeshBuilder; + +} + +#endif // __NMR_MESHBUILDER diff --git a/Include/Common/Mesh/NMR_MeshTypes.h b/Include/Common/Mesh/NMR_MeshTypes.h new file mode 100644 index 0000000..5dbe043 --- /dev/null +++ b/Include/Common/Mesh/NMR_MeshTypes.h @@ -0,0 +1,112 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_MeshTypes.h defines the basic datastructures for the mesh CMesh. + +The mesh has nodes and faces, which are defined in this file. +In addition, some constants are defined here. +--*/ + +#ifndef __NMR_MESHTYPES +#define __NMR_MESHTYPES + +#include "Common/NMR_Types.h" +#include "Common/NMR_Local.h" +#include "Common/Math/NMR_Geometry.h" +#include "Common/NMR_PagedVector.h" +#include + +// The maximum allowed number of certain entities (2^31-1) +#define NMR_MESH_MAXNODECOUNT 2147483647 +#define NMR_MESH_MAXEDGECOUNT 2147483647 +#define NMR_MESH_MAXFACECOUNT 2147483647 +#define NMR_MESH_MAXBEAMCOUNT 2147483647 +#define NMR_MESH_MAXBALLCOUNT 2147483647 + +#define NMR_MESH_MAXCOORDINATE 1000000000.0f + +#define NMR_MESH_NODEBLOCKCOUNT 256 +#define NMR_MESH_EDGEBLOCKCOUNT 256 +#define NMR_MESH_FACEBLOCKCOUNT 256 +#define NMR_MESH_BEAMBLOCKCOUNT 256 +#define NMR_MESH_BALLBLOCKCOUNT 256 +#define NMR_MESH_NODEEDGELINKBLOCKCOUNT 256 + +namespace NMR { + + typedef struct { + nfInt32 m_index; + NVEC3 m_position; + } MESHNODE; + typedef CPagedVector MESHNODES; + + typedef struct { + nfInt32 m_index; + nfInt32 m_nodeindices[3]; + } MESHFACE; + typedef CPagedVector MESHFACES; + + typedef struct BEAMSET { + std::vector m_Refs; + std::vector m_BallRefs; + std::string m_sName; // "" for no name + std::string m_sIdentifier; // "" for no identifier + BEAMSET() { + m_sName = ""; + m_sIdentifier = ""; + } + } BEAMSET; + typedef std::shared_ptr PBEAMSET; + + typedef struct MESHBEAM { + nfInt32 m_index; + nfInt32 m_nodeindices[2]; + nfDouble m_radius[2]; + nfInt32 m_capMode[2]; + // eModelBeamLatticeCapMode m_capMode[2]; + MESHBEAM() { + }; + } MESHBEAM; + typedef CPagedVector MESHBEAMS; + + typedef struct MESHBALL { + nfInt32 m_index; + nfInt32 m_nodeindex; + nfDouble m_radius; + MESHBALL() { + }; + } MESHBALL; + typedef CPagedVector MESHBALLS; + + typedef struct { + nfInt32 m_index; + NVEC2 m_position; + } SLICENODE; +} + +#endif // __NMR_MESHTYPES diff --git a/Include/Common/MeshExport/NMR_MeshExportEdgeMap.h b/Include/Common/MeshExport/NMR_MeshExportEdgeMap.h new file mode 100644 index 0000000..0da35e3 --- /dev/null +++ b/Include/Common/MeshExport/NMR_MeshExportEdgeMap.h @@ -0,0 +1,63 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_MeshExportEdgeMap.h defines the Mesh Export Edge Map Class. +This class acts as a container for additional topology information. + +--*/ + +#ifndef __NMR_MESHEXPORTEDGEMAP +#define __NMR_MESHEXPORTEDGEMAP + +#include "Common/NMR_Types.h" +#include "Common/Math/NMR_Geometry.h" + +#include + +namespace NMR { + + typedef union { + nfInt32 m_edgeindices[3]; + } NMESHEXPORTFACE; + + class CMeshExportEdgeMap { + private: + std::vector m_FaceInfos; + public: + CMeshExportEdgeMap() = delete; + CMeshExportEdgeMap(nfUint32 nFaceCount); + + NMESHEXPORTFACE getFaceData(_In_ nfInt32 nIdx); + void setFaceData(_In_ nfInt32 nIdx, _In_ NMESHEXPORTFACE ExportFace); + }; + + typedef std::shared_ptr PMeshExportEdgeMap; + +} + +#endif // __NMR_MESHEXPORTEDGEMAP diff --git a/Include/Common/MeshExport/NMR_MeshExporter.h b/Include/Common/MeshExport/NMR_MeshExporter.h new file mode 100644 index 0000000..045261f --- /dev/null +++ b/Include/Common/MeshExport/NMR_MeshExporter.h @@ -0,0 +1,67 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_MeshExporter.h defines the Mesh Exporter Class. +This is an abstract base class for exporting different Mesh Formats. + +--*/ + +#ifndef __NMR_MESHEXPORTER +#define __NMR_MESHEXPORTER + +#include "Common/NMR_Types.h" +#include "Common/Math/NMR_Geometry.h" +#include "Common/Mesh/NMR_Mesh.h" +#include "Common/MeshExport/NMR_MeshExportEdgeMap.h" +#include "Common/Platform/NMR_ExportStream.h" + +#include + +namespace NMR { + + class CMeshExporter { + private: + PExportStream m_stream; + public: + CMeshExporter(); + CMeshExporter(_In_ PExportStream pStream); + virtual ~CMeshExporter() = default; + + void setStream(_In_ PExportStream pStream); + CExportStream * getStream(); + + virtual void exportMeshEx(_In_ CMesh * pMesh, _In_opt_ NMATRIX3 * pmMatrix, _In_opt_ CMeshExportEdgeMap * pExportEdgeMap) = 0; + + void exportMesh(_In_ CMesh * pMesh, _In_opt_ NMATRIX3 * pmMatrix); + }; + + typedef std::shared_ptr PMeshExporter; + +} + +#endif // __NMR_MESHEXPORTER diff --git a/Include/Common/MeshExport/NMR_MeshExporter_STL.h b/Include/Common/MeshExport/NMR_MeshExporter_STL.h new file mode 100644 index 0000000..719aaae --- /dev/null +++ b/Include/Common/MeshExport/NMR_MeshExporter_STL.h @@ -0,0 +1,58 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_MeshExporter_STL.h defines the Mesh Exporter Class. +This is a derived class for Exporting the binary STL and color STL Mesh Format. + +--*/ + +#ifndef __NMR_MESHEXPORTER_STL +#define __NMR_MESHEXPORTER_STL + +#include "Common/NMR_Types.h" +#include "Common/Math/NMR_Geometry.h" +#include "Common/Mesh/NMR_Mesh.h" +#include "Common/MeshExport/NMR_MeshExporter.h" + +#include + +namespace NMR { + + class CMeshExporter_STL : public CMeshExporter { + private: + + public: + CMeshExporter_STL(); + CMeshExporter_STL(PExportStream pStream); + + virtual void exportMeshEx(_In_ CMesh * pMesh, _In_opt_ NMATRIX3 * pmMatrix, _In_opt_ CMeshExportEdgeMap * pExportEdgeMap); + }; + +} + +#endif // __NMR_MESHEXPORTER_STL diff --git a/Include/Common/MeshImport/NMR_MeshImporter.h b/Include/Common/MeshImport/NMR_MeshImporter.h new file mode 100644 index 0000000..cc963ea --- /dev/null +++ b/Include/Common/MeshImport/NMR_MeshImporter.h @@ -0,0 +1,64 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_MeshImporter.h defines the Mesh Importer Class. +This is an abstract base class for Importing different Mesh Formats. + +--*/ + +#ifndef __NMR_MESHIMPORTER +#define __NMR_MESHIMPORTER + +#include "Common/NMR_Types.h" +#include "Common/Math/NMR_Geometry.h" +#include "Common/Mesh/NMR_Mesh.h" +#include "Common/Platform/NMR_ImportStream.h" + +#include + +namespace NMR { + + class CMeshImporter { + private: + PImportStream m_pStream; + public: + CMeshImporter(); + CMeshImporter(_In_ PImportStream pStream); + virtual ~CMeshImporter() = default; + + void setStream(_In_ PImportStream pStream); + CImportStream * getStream(); + + virtual void loadMesh(_In_ CMesh * pMesh, _In_opt_ NMATRIX3 * pMatrix) = 0; + }; + + typedef std::shared_ptr PMeshImporter; + +} + +#endif // __NMR_MESHIMPORTER diff --git a/Include/Common/MeshImport/NMR_MeshImporter_STL.h b/Include/Common/MeshImport/NMR_MeshImporter_STL.h new file mode 100644 index 0000000..31bbe9a --- /dev/null +++ b/Include/Common/MeshImport/NMR_MeshImporter_STL.h @@ -0,0 +1,88 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_MeshImporter_STL.h defines the Mesh Importer Class. +This is a derived class for Importing the binary STL and color STL Mesh Format. + +--*/ + +#ifndef __NMR_MESHIMPORTER_STL +#define __NMR_MESHIMPORTER_STL + +#include "Common/NMR_Types.h" +#include "Common/Math/NMR_Geometry.h" +#include "Common/Mesh/NMR_Mesh.h" +#include "Common/MeshImport/NMR_MeshImporter.h" +#include "Common/NMR_Architecture_Utils.h" + +#include + +namespace NMR { + +#pragma pack (1) + typedef struct MESHFORMAT_STL_FACET { + NVEC3 m_normal; + NVEC3 m_vertices[3]; + nfUint16 m_attribute; + void swapByteOrder() { + m_attribute = swapBytes(m_attribute); + for (nfUint32 i = 0; i < 3; i++) { + m_normal.m_fields[i] = swapBytes(m_normal.m_fields[i]); + for (nfUint32 j = 0; j < 3; j++) { + m_vertices[i].m_fields[j] = swapBytes(m_vertices[i].m_fields[j]); + } + } + } + } MESHFORMAT_STL_FACET; +#pragma pack() + + class CMeshImporter_STL : public CMeshImporter { + private: + nfFloat m_fUnits; + nfBool m_bIgnoreInvalidFaces; + nfBool m_bImportColors; + + public: + CMeshImporter_STL(); + CMeshImporter_STL(_In_ PImportStream pStream); + CMeshImporter_STL(_In_ PImportStream pStream, _In_ nfFloat fUnits); + CMeshImporter_STL(_In_ PImportStream pStream, _In_ nfFloat fUnits, _In_ nfBool bImportColors); + + void setUnits(_In_ nfFloat fUnits); + nfFloat getUnits(); + void setIgnoreInvalidFaces(_In_ nfBool bIgnoreInvalidFaces); + nfBool getIgnoreInvalidFaces(); + void setImportColors(_In_ nfBool bImportColors); + nfBool getImportColors(); + + virtual void loadMesh(_In_ CMesh * pMesh, _In_opt_ NMATRIX3 * pmMatrix); + }; + +} + +#endif // __NMR_MESHIMPORTER_STL diff --git a/Include/Common/MeshInformation/NMR_MeshInformation.h b/Include/Common/MeshInformation/NMR_MeshInformation.h new file mode 100644 index 0000000..aea9514 --- /dev/null +++ b/Include/Common/MeshInformation/NMR_MeshInformation.h @@ -0,0 +1,83 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_MeshInformation.h defines the Mesh Information Class. +This is a base class for handling all the mesh-related linear information (like face colors, +textures, etc...). It provides abstract functions to interpolate and reconstruct informations while +the mesh topology is changing. + +--*/ + +#ifndef __NMR_MESHINFORMATION +#define __NMR_MESHINFORMATION + +#include "Common/MeshInformation/NMR_MeshInformationContainer.h" +#include "Common/MeshInformation/NMR_MeshInformationTypes.h" +#include "Common/Math/NMR_Vector.h" + +namespace NMR { + + class CMeshInformation; + + typedef std::shared_ptr PMeshInformation; + + class CMeshInformation { + protected: + PMeshInformationContainer m_pContainer; + nfUint64 m_nInternalID; + + public: + CMeshInformation(); + virtual ~CMeshInformation() = default; + + _Ret_notnull_ MESHINFORMATIONFACEDATA * getFaceData(nfUint32 nFaceIndex); + _Ret_notnull_ MESHINFORMATIONFACEDATA * addFaceData(_In_ nfUint32 nNewFaceCount); + void resetFaceInformation(_In_ nfUint32 nFaceIndex); + void resetAllFaceInformation(); + + virtual void invalidateFace(_In_ MESHINFORMATIONFACEDATA * pData) = 0; + + virtual eMeshInformationType getType() = 0; + virtual void cloneDefaultInfosFrom(_In_ CMeshInformation * pOtherInformation) = 0; + virtual void cloneFaceInfosFrom(_In_ nfUint32 nFaceIndex, _In_ CMeshInformation * pOtherInformation, _In_ nfUint32 nOtherFaceIndex) = 0; + virtual PMeshInformation cloneInstance(_In_ nfUint32 nCurrentFaceCount) = 0; + virtual void permuteNodeInformation(_In_ nfUint32 nFaceIndex, _In_ nfUint32 nNodeIndex1, _In_ nfUint32 nNodeIndex2, _In_ nfUint32 nNodeIndex3) = 0; + virtual void mergeInformationFrom (_In_ CMeshInformation * pInformation) = 0; + virtual nfUint32 getBackupSize() = 0; + virtual nfBool faceHasData(_In_ nfUint32 nFaceIndex) = 0; + + virtual void setInternalID(nfUint64 nInternalID); + virtual nfUint64 getInternalID(); + + virtual void setDefaultData(MESHINFORMATIONFACEDATA* pData) = 0; + virtual MESHINFORMATIONFACEDATA* getDefaultData() = 0; + }; + +} + +#endif // __NMR_MESHINFORMATION diff --git a/Include/Common/MeshInformation/NMR_MeshInformationContainer.h b/Include/Common/MeshInformation/NMR_MeshInformationContainer.h new file mode 100644 index 0000000..65d7230 --- /dev/null +++ b/Include/Common/MeshInformation/NMR_MeshInformationContainer.h @@ -0,0 +1,69 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_MeshInformationContainer.h defines the Mesh Information Container Class. +This class provides a memory container for holding the texture information state of a complete mesh structure. + +--*/ + +#ifndef __NMR_MESHINFORMATIONCONTAINER +#define __NMR_MESHINFORMATIONCONTAINER + +#include "Common/MeshInformation/NMR_MeshInformationTypes.h" +#include "Common/NMR_Types.h" +#include "Common/NMR_Local.h" + +#include +#include + +#define MESHINFORMATIONCOUNTER_BUFFERSIZE 256 + +namespace NMR { + + class CMeshInformationContainer { + private: + nfUint32 m_nFaceCount; + nfUint32 m_nRecordSize; + std::vector m_DataBlocks; + MESHINFORMATIONFACEDATA * m_CurrentDataBlock; + + public: + CMeshInformationContainer(); + CMeshInformationContainer(nfUint32 nCurrentFaceCount, nfUint32 nRecordSize); + ~CMeshInformationContainer(); + _Ret_notnull_ MESHINFORMATIONFACEDATA * addFaceData(nfUint32 nNewFaceCount); + _Ret_notnull_ MESHINFORMATIONFACEDATA * getFaceData(nfUint32 nIdx); + + nfUint32 getCurrentFaceCount(); + void clear(); + }; + + typedef std::shared_ptr PMeshInformationContainer; +} + +#endif // __NMR_MESHINFORMATIONCONTAINER diff --git a/Include/Common/MeshInformation/NMR_MeshInformationFactory.h b/Include/Common/MeshInformation/NMR_MeshInformationFactory.h new file mode 100644 index 0000000..6e79ed9 --- /dev/null +++ b/Include/Common/MeshInformation/NMR_MeshInformationFactory.h @@ -0,0 +1,50 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_MeshInformationFactory.h defines the Mesh Information Factory Class. +It allows a dynamic creation of different Classes of Information. + +--*/ + +#ifndef __NMR_MESHINFORMATIONFACTORY +#define __NMR_MESHINFORMATIONFACTORY + +#include "Common/MeshInformation/NMR_MeshInformation_Properties.h" + +namespace NMR { + + class CMeshInformationFactory { + private: + public: + CMeshInformationFactory(); + PMeshInformation createMeshInformation(eMeshInformationType eType, nfUint32 nCurrentFaceCount); + }; + +} + +#endif // __NMR_MESHINFORMATIONFACTORY diff --git a/Include/Common/MeshInformation/NMR_MeshInformationHandler.h b/Include/Common/MeshInformation/NMR_MeshInformationHandler.h new file mode 100644 index 0000000..c363162 --- /dev/null +++ b/Include/Common/MeshInformation/NMR_MeshInformationHandler.h @@ -0,0 +1,75 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_MeshInformationHandler.h defines the Mesh Information Handler Class. +It allows to include different kinds of information in one mesh (like Textures AND colors). + +--*/ + +#ifndef __NMR_MESHINFORMATIONHANDLER +#define __NMR_MESHINFORMATIONHANDLER + +#include "Common/MeshInformation/NMR_MeshInformation.h" +#include +#include + +namespace NMR { + + class CMeshInformationHandler { + protected: + std::vector m_pInformations; + std::array m_pLookup; + + nfUint64 m_nInternalIDCounter; + + public: + CMeshInformationHandler(); + + void addInformation(_In_ PMeshInformation pInformation); + void addFace(_In_ nfUint32 nNewFaceCount); + + CMeshInformation * getInformationIndexed(_In_ nfUint32 nIdx); + PMeshInformation getPInformationIndexed(_In_ nfUint32 nIdx); + CMeshInformation * getInformationByType(_In_ nfUint32 nChannel, _In_ eMeshInformationType eType); + nfUint32 getInformationCount(); + + void addInfoTableFrom(_In_ CMeshInformationHandler * pOtherInfoHandler, _In_ nfUint32 nCurrentFaceCount); + void cloneDefaultInfosFrom(_In_ CMeshInformationHandler * pOtherInfoHandler); + void cloneFaceInfosFrom(_In_ nfUint32 nFaceIdx, _In_ CMeshInformationHandler * pOtherInfoHandler, _In_ nfUint32 nOtherFaceIndex); + void permuteNodeInformation(_In_ nfUint32 nFaceIdx, _In_ nfUint32 nNodeIndex1, _In_ nfUint32 nNodeIndex2, _In_ nfUint32 nNodeIndex3); + void resetFaceInformation(_In_ nfUint32 nFaceIdx); + + void removeInformation(_In_ eMeshInformationType eType); + void removeInformationIndexed(_In_ nfUint32 nIndex); + }; + + typedef std::shared_ptr PMeshInformationHandler; + +} + +#endif // __NMR_MESHINFORMATIONHANDLER diff --git a/Include/Common/MeshInformation/NMR_MeshInformationTypes.h b/Include/Common/MeshInformation/NMR_MeshInformationTypes.h new file mode 100644 index 0000000..c61513a --- /dev/null +++ b/Include/Common/MeshInformation/NMR_MeshInformationTypes.h @@ -0,0 +1,63 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_MeshInformationTypes.h defines the basic structs and constants +to contain mesh surface information. + +--*/ + +#ifndef __NMR_MESHINFORMATIONTYPES +#define __NMR_MESHINFORMATIONTYPES + +#include "Common/NMR_Types.h" +#include "Common/Math/NMR_Vector.h" + +namespace NMR { + +#define MESHINFORMATION_MAXINTERNALID 9223372036854775808ULL + + typedef enum _eMeshInformationType { + emiAbstract = 0x0000, + emiProperties = 0x0001, + emiLastType + } eMeshInformationType; + + typedef nfByte MESHINFORMATIONFACEDATA; + +#pragma pack (1) + typedef struct { + nfUint32 m_nUniqueResourceID; + nfUint32 m_nPropertyIDs[3]; + } MESHINFORMATION_PROPERTIES; + + +#pragma pack() + +} + +#endif // __NMR_MESHINFORMATIONTYPES diff --git a/Include/Common/MeshInformation/NMR_MeshInformation_Properties.h b/Include/Common/MeshInformation/NMR_MeshInformation_Properties.h new file mode 100644 index 0000000..ce8a62e --- /dev/null +++ b/Include/Common/MeshInformation/NMR_MeshInformation_Properties.h @@ -0,0 +1,89 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_MeshInformation_Properties.h defines the Property Information Class. + +--*/ + +#ifndef __NMR_MESHINFORMATION_PROPERTIES +#define __NMR_MESHINFORMATION_PROPERTIES + +#include "Common/MeshInformation/NMR_MeshInformation.h" +#include "Model/Classes/NMR_ModelTypes.h" +#include +#include + +namespace NMR { + + class CMeshInformation_PropertyIndexMapping { + private: + std::map, nfUint32> m_IDMap; + public: + CMeshInformation_PropertyIndexMapping(); + + nfUint32 mapPropertyIDToIndex(UniqueResourceID nUniqueResourceID, ModelPropertyID nPropertyID); + + UniqueResourceID getDefaultResourceID(); + nfUint32 getDefaultResourceIndex(); + + nfUint32 registerPropertyID(UniqueResourceID nUniqueResourceID, ModelPropertyID nPropertyID, nfUint32 nResourceIndex); + + }; + + typedef std::shared_ptr PMeshInformation_PropertyIndexMapping; + + + class CMeshInformation_Properties : public CMeshInformation { + private: + std::shared_ptr m_pDefaultProperty; + protected: + public: + CMeshInformation_Properties(); + CMeshInformation_Properties(nfUint32 nCurrentFaceCount); + + void invalidateFace(_In_ MESHINFORMATIONFACEDATA * pData) override; + + eMeshInformationType getType() override; + void cloneDefaultInfosFrom(_In_ CMeshInformation * pOtherInformation) override; + void cloneFaceInfosFrom(_In_ nfUint32 nFaceIndex, _In_ CMeshInformation * pOtherInformation, _In_ nfUint32 nOtherFaceIndex) override; + PMeshInformation cloneInstance(_In_ nfUint32 nCurrentFaceCount) override; + void permuteNodeInformation(_In_ nfUint32 nFaceIndex, _In_ nfUint32 nNodeIndex1, _In_ nfUint32 nNodeIndex2, _In_ nfUint32 nNodeIndex3) override; + nfUint32 getBackupSize() override; + void mergeInformationFrom(_In_ CMeshInformation * pInformation) override; + nfBool faceHasData(_In_ nfUint32 nFaceIndex) override; + + void setDefaultData(MESHINFORMATIONFACEDATA* pData) override; + MESHINFORMATIONFACEDATA* getDefaultData() override; + }; + + typedef std::shared_ptr PMeshInformation_Properties; + +} + +#endif // __NMR_MESHINFORMATION_PROPERTIES + diff --git a/Include/Common/NMR_Architecture_Utils.h b/Include/Common/NMR_Architecture_Utils.h new file mode 100644 index 0000000..a6d7685 --- /dev/null +++ b/Include/Common/NMR_Architecture_Utils.h @@ -0,0 +1,66 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_Architecture_Utils.h defines helper functions for working on big-endian architecture + +--*/ + +#ifndef __NMR_ARCHITECTURE_UTILS +#define __NMR_ARCHITECTURE_UTILS + +#include "NMR_Types.h" + +namespace NMR { + + template + void swapBytesArray(unsigned char(&bytes)[N]) { + // Optimize this with a platform-specific API as desired. + for (unsigned char *p = bytes, *end = bytes + N - 1; p < end; ++p, --end) { + unsigned char tmp = *p; + *p = *end; + *end = tmp; + } + } + template + T swapBytes(T value) { + swapBytesArray(*reinterpret_cast(&value)); + return value; + } + + inline bool isBigEndian(void) + { + union { + nfUint32 i; + char c[4]; + } bint = { 0x01020304 }; + + return bint.c[0] == 1; + } +} + +#endif // __NMR_ARCHITECTURE_UTILS diff --git a/Include/Common/NMR_Assertion.h b/Include/Common/NMR_Assertion.h new file mode 100644 index 0000000..30ccfa9 --- /dev/null +++ b/Include/Common/NMR_Assertion.h @@ -0,0 +1,50 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_Assertion.h defines portable Assertion commands for the +Native Model Repair algorithms and modules. + +--*/ + +#ifndef __NMR_ASSERTION +#define __NMR_ASSERTION + +#ifdef NMR_USEASSERTIONS +#ifdef NMR_UNITTESTS +#include "CppUnitTest.h" +#define __NMRASSERT(value) Microsoft::VisualStudio::CppUnitTestFramework::Assert::IsTrue (((uintptr_t) (value)) != 0); + +#else +#include +#define __NMRASSERT(value) assert(value); +#endif +#else +#define __NMRASSERT(value) +#endif + +#endif // __NMR_ASSERTION diff --git a/Include/Common/NMR_ErrorConst.h b/Include/Common/NMR_ErrorConst.h new file mode 100644 index 0000000..598880d --- /dev/null +++ b/Include/Common/NMR_ErrorConst.h @@ -0,0 +1,1340 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ErrorConst.h defines all error code constants. + +--*/ + +#ifndef __NMR_ERRORCONST +#define __NMR_ERRORCONST + +// This is the output value of a "uncatched exception" +#define NMR_GENERICEXCEPTIONSTRING "uncatched exception" + +/*------------------------------------------------------------------- + Success / user interaction (0x0XXX) +-------------------------------------------------------------------*/ + +// Function has suceeded, there has been no error +#define NMR_SUCCESS 0x0 + +// Function was aborted by user +#define NMR_USERABORTED 0x0001 + +/*------------------------------------------------------------------- + General error codes (0x1XXX) +-------------------------------------------------------------------*/ + +// The called function is not fully implemented +#define NMR_ERROR_NOTIMPLEMENTED 0x1000 + +// The call parameter to the function was invalid +#define NMR_ERROR_INVALIDPARAM 0x1001 + +// The Calculation has to be canceled +#define NMR_ERROR_CALCULATIONTERMINATED 0x1002 + +// The DLL Library of the DLL Filters could not be loaded +#define NMR_ERROR_COULDNOTLOADLIBRARY 0x1003 + +// The DLL Library of the DLL Filters is invalid +#define NMR_ERROR_GETPROCFAILED 0x1004 + +// The DLL Library has not been loaded or could not be loaded +#define NMR_ERROR_DLLNOTLOADED 0x1005 + +// The DLL Library of the DLL Filters is invalid +#define NMR_ERROR_DLLFUNCTIONNOTFOUND 0x1006 + +// The DLL Library has got an invalid parameter +#define NMR_ERROR_DLLINVALIDPARAM 0x1007 + +// No Instance of the DLL has been created +#define NMR_ERROR_DLLNOINSTANCE 0x1008 + +// The DLL returns this, if it does not support the suspected filters +#define NMR_ERROR_DLLINVALIDFILTERNAME 0x1009 + +// The DLL returns this, if not all parameters are provided +#define NMR_ERROR_DLLMISSINGPARAMETER 0x100A + +// The provided Blocksize is invalid (like in CPagedVector) +#define NMR_ERROR_INVALIDBLOCKSIZE 0x100B + +// The provided Index is invalid (like in CPagedVector, Node Index) +#define NMR_ERROR_INVALIDINDEX 0x100C + +// A Matrix could not be inverted in the Matrix functions (as it is singular) +#define NMR_ERROR_SINGULARMATRIX 0x100D + +// The Model Object does not match the model which is it added to +#define NMR_ERROR_MODELMISMATCH 0x100E + +// The function called is abstract and should not have been called +#define NMR_ERROR_ABSTRACT 0x100F + +// The current block is not assigned +#define NMR_ERROR_INVALIDHEADBLOCK 0x1010 + +// COM CoInitialize failed +#define NMR_ERROR_COMINITIALIZATIONFAILED 0x1011 + +// A Standard C++ Exception occurred +#define NMR_ERROR_STANDARDCPPEXCEPTION 0x1012 + +// No mesh has been given +#define NMR_ERROR_INVALIDMESH 0x1013 + +// Context could not be created +#define NMR_ERROR_COULDNOTCREATECONTEXT 0x1014 + +// Wanted to convert empty string to integer +#define NMR_ERROR_EMPTYSTRINGTOINTCONVERSION 0x1015 + +// Wanted to convert string with non-numeric characters to integer +#define NMR_ERROR_INVALIDSTRINGTOINTCONVERSION 0x1016 + +// Wanted to convert too large number string to integer +#define NMR_ERROR_STRINGTOINTCONVERSIONOUTOFRANGE 0x1017 + +// Wanted to convert empty string to double +#define NMR_ERROR_EMPTYSTRINGTODOUBLECONVERSION 0x1018 + +// Wanted to convert string with non-numeric characters to double +#define NMR_ERROR_INVALIDSTRINGTODOUBLECONVERSION 0x1019 + +// Wanted to convert too large number string to double +#define NMR_ERROR_STRINGTODOUBLECONVERSIONOUTOFRANGE 0x101A + +// Too many values (>12) have been found in a matrix string +#define NMR_ERROR_TOOMANYVALUESINMATRIXSTRING 0x101B + +// Not enough values (<12) have been found in a matrix string +#define NMR_ERROR_NOTENOUGHVALUESINMATRIXSTRING 0x101C + +// Invalid buffer size +#define NMR_ERROR_INVALIDBUFFERSIZE 0x101D + +// Insufficient buffer size +#define NMR_ERROR_INSUFFICIENTBUFFERSIZE 0x101E + +// No component has been given +#define NMR_ERROR_INVALIDCOMPONENT 0x101F + +// Invalid hex value +#define NMR_ERROR_INVALIDHEXVALUE 0x1020 + +// Range error +#define NMR_ERROR_RANGEERROR 0x1021 + +// Generic Exception +#define NMR_ERROR_GENERICEXCEPTION 0x1022 + +// Passed an invalid null pointer +#define NMR_ERROR_INVALIDPOINTER 0x1023 + +// XML Element not open +#define NMR_ERROR_XMLELEMENTNOTOPEN 0x1024 + +// Invalid XML Name +#define NMR_ERROR_INVALIDXMLNAME 0x1025 + +// Invalid Integer Triplet String +#define NMR_ERROR_INVALIDINTEGERTRIPLET 0x1026 + +// Invalid ZIP Entry key +#define NMR_ERROR_INVALIDZIPENTRYKEY 0x1027 + +// Invalid ZIP Name +#define NMR_ERRORINVALIDZIPNAME 0x1028 + +// ZIP Stream cannot seek +#define NMR_ERROR_ZIPSTREAMCANNOTSEEK 0x1029 + +// Could not convert to UTF8 +#define NMR_ERROR_COULDNOTCONVERTTOUTF8 0x102A + +// Could not convert to UTF16 +#define NMR_ERROR_COULDNOTCONVERTTOUTF16 0x102B + +// ZIP Entry overflow +#define NMR_ERROR_ZIPENTRYOVERFLOW 0x102C + +// Invalid ZIP Entry +#define NMR_ERROR_INVALIDZIPENTRY 0x102D + +// Export Stream not empty +#define NMR_ERROR_EXPORTSTREAMNOTEMPTY 0x102E + +// Zip already finished +#define NMR_ERROR_ZIPALREADYFINISHED 0x102F + +// Deflate init failed +#define NMR_ERROR_DEFLATEINITFAILED 0x1030 + +// Could not deflate data +#define NMR_ERROR_COULDNOTDEFLATE 0x1031 + +// Could not close written XML node +#define NMR_ERROR_XMLWRITER_CLOSENODEERROR 0x1032 + +// Invalid OPC Part URI +#define NMR_ERROR_INVALIDOPCPARTURI 0x1033 + +// Could not convert number +#define NMR_ERROR_COULDNOTCONVERTNUMBER 0x1034 + +// Could not read ZIP file +#define NMR_ERROR_COULDNOTREADZIPFILE 0x1035 + +// Could not seek in ZIP file +#define NMR_ERROR_COULDNOTSEEKINZIP 0x1036 + +// Could not stat ZIP entry +#define NMR_ERROR_COULDNOTSTATZIPENTRY 0x1037 + +// Could not open ZIP entry +#define NMR_ERROR_COULDNOTOPENZIPENTRY 0x1038 + +// Invalid XML Depth +#define NMR_ERROR_INVALIDXMLDEPTH 0x1039 + +// XML Element not empty +#define NMR_ERROR_XMLELEMENTNOTEMPTY 0x103A + +// Could not initialize COM +#define NMR_ERROR_COULDNOTINITITALIZECOM 0x103B + +// Callback stream cannot seek +#define NMR_ERROR_CALLBACKSTREAMCANNOTSEEK 0x103C + +// Could not write to callback stream +#define NMR_ERROR_COULDNOTWRITETOCALLBACKSTREAM 0x103D + +// Invalid Type Case +#define NMR_ERROR_INVALIDCAST 0x103E + +// Buffer is full +#define NMR_ERROR_BUFFERISFULL 0x103F + +// Could not read from callback stream +#define NMR_ERROR_COULDNOTREADFROMCALLBACKSTREAM 0x1040 + +// Content Types does not contain etension for relatioship +#define NMR_ERROR_OPC_MISSING_EXTENSION_FOR_RELATIONSHIP 0x1041 + +// Content Types does not contain extension or partname for model +#define NMR_ERROR_OPC_MISSING_EXTENSION_FOR_MODEL 0x1042 + +// Invalid XML encoding +#define NMR_ERROR_INVALIDXMLENCODING 0x1043 + +// Invalid XML attribute +#define NMR_ERROR_FORBIDDENXMLATTRITIBUTE 0x1044 + +// Duplicate print ticket +#define NMR_ERROR_DUPLICATE_PRINTTICKET 0x1045 + +// Duplicate ID of a relationship +#define NMR_ERROR_OPC_DUPLICATE_RELATIONSHIP_ID 0x1046 + +// Attachment has invalid relationship for texture +#define NMR_ERROR_INVALIDRELATIONSHIPTYPEFORTEXTURE 0x1047 + +// Attachment has an empty stream +#define NMR_ERROR_IMPORTSTREAMISEMPTY 0x1048 + +// UUID generation failed +#define NMR_ERROR_UUIDGENERATIONFAILED 0x1049 + +// ZIP Entry too large for non zip64 zip-file +#define NMR_ERROR_ZIPENTRYNON64_TOOLARGE 0x104A + +// An individual custom attachment is too large +#define NMR_ERROR_ATTACHMENTTOOLARGE 0x104B + +// Error in zip-callback +#define NMR_ERROR_ZIPCALLBACK 0x104C + +// ZIP contains inconsistencies +#define NMR_ERROR_ZIPCONTAINSINCONSISTENCIES 0x104D + +// XML namespace is already registered. +#define NMR_ERROR_XMLNAMESPACEALREADYREGISTERED 0x104E + +// XML prefix is already registered. +#define NMR_ERROR_XMLPREFIXALREADYREGISTERED 0x104F + +// Failed to initialize a zlib buffer +#define NMR_ERROR_COULDNOTINITINFLATE 0x1050 + +// Failed to decompress part +#define NMR_ERROR_COULDNOTINFLATE 0x1051 + +// Failed to initialize a zlib buffer +#define NMR_ERROR_COULDNOTINITDEFLATE 0x1052 + +/*------------------------------------------------------------------- +Core framework error codes (0x2XXX) +-------------------------------------------------------------------*/ + +// No Progress Interval has been specified in the progress handler +#define NMR_ERROR_NOPROGRESSINTERVAL 0x2001 + +// An Edge with two identical nodes has been tried to added to a mesh +#define NMR_ERROR_DUPLICATENODE 0x2002 + +// The mesh exceeds more than NMR_MESH_MAXNODECOUNT (2^31-1, around two billion) nodes +#define NMR_ERROR_TOOMANYNODES 0x2003 + +// The mesh exceeds more than NMR_MESH_MAXFACECOUNT (2^31-1, around two billion) faces +#define NMR_ERROR_TOOMANYFACES 0x2004 + +// The index provided for the node is invalid +#define NMR_ERROR_INVALIDNODEINDEX 0x2005 + +// The index provided for the face is invalid +#define NMR_ERROR_INVALIDFACEINDEX 0x2006 + +// The mesh topology structure is corrupt +#define NMR_ERROR_INVALIDMESHTOPOLOGY 0x2007 + +// The coordinates exceed NMR_MESH_MAXCOORDINATE (= 1 billion mm) +#define NMR_ERROR_INVALIDCOORDINATES 0x2008 + +// A zero Vector has been tried to normalized, which is impossible +#define NMR_ERROR_NORMALIZEDZEROVECTOR 0x2009 + +// The specified file could not be opened +#define NMR_ERROR_COULDNOTOPENFILE 0x200A + +// The specified file could not be created +#define NMR_ERROR_COULDNOTCREATEFILE 0x200B + +// Seeking in a stream was not possible +#define NMR_ERROR_COULDNOTSEEKSTREAM 0x200C + +// Reading from a stream was not possible +#define NMR_ERROR_COULDNOTREADSTREAM 0x200D + +// Writing to a stream was not possible +#define NMR_ERROR_COULDNOTWRITESTREAM 0x200E + +// Reading from a stream was only possible partially +#define NMR_ERROR_COULDNOTREADFULLDATA 0x200F + +// Writing to a stream was only possible partially +#define NMR_ERROR_COULDNOTWRITEFULLDATA 0x2010 + +// No Import Stream was provided to the importer +#define NMR_ERROR_NOIMPORTSTREAM 0x2011 + +// The specified facecount in the file was not valid +#define NMR_ERROR_INVALIDFACECOUNT 0x2012 + +// The specified units of the file was not valid +#define NMR_ERROR_INVALIDUNITS 0x2013 + +// The specified units could not be set (for example, the CVectorTree already had some entries) +#define NMR_ERROR_COULDNOTSETUNITS 0x2014 + +// The mesh exceeds more than NMR_MESH_MAXEDGECOUNT (2^31-1, around two billion) edges +#define NMR_ERROR_TOOMANYEDGES 0x2015 + +// The index provided for the edge is invalid +#define NMR_ERROR_INVALIDEDGEINDEX 0x2016 + +// The mesh has an face with two identical edges +#define NMR_ERROR_DUPLICATEEDGE 0x2017 + +// Could not add face to an edge, because it was already two-manifold +#define NMR_ERROR_MANIFOLDEDGES 0x2018 + +// Could not delete edge, because it had attached faces +#define NMR_ERROR_COULDNOTDELETEEDGE 0x2019 + +// Mesh Merging has failed, because the mesh structure was currupted +#define NMR_ERROR_INTERNALMERGEERROR 0x201A + +// The internal triangle structure is corrupted +#define NMR_ERROR_EDGESARENOTFORMINGTRIANGLE 0x201B + +// No Export Stream was provided to the exporter +#define NMR_ERROR_NOEXPORTSTREAM 0x201C + +// Could not set parameter, because the queue was not empty +#define NMR_ERROR_COULDNOTSETPARAMETER 0x201D + +// Mesh Information records size is invalid +#define NMR_ERROR_INVALIDRECORDSIZE 0x201E + +// Mesh Information Face Count dies not match with mesh face count +#define NMR_ERROR_MESHINFORMATIONCOUNTMISMATCH 0x201F + +// Could not access mesh information +#define NMR_ERROR_INVALIDMESHINFORMATIONINDEX 0x2020 + +// Mesh Information Backup could not be created +#define NMR_ERROR_MESHINFORMATIONBUFFER_FULL 0x2021 + +// No Mesh Information Container has been assigned +#define NMR_ERROR_NOMESHINFORMATIONCONTAINER 0x2022 + +// Internal Mesh Merge Error because of corrupt mesh structure +#define NMR_ERROR_DISCRETEMERGEERROR 0x2023 + +// Discrete Edges may only have a max length of 30000. +#define NMR_ERROR_DISCRETEEDGELENGTHVIOLATION 0x2024 + +// OctTree Node is out of the OctTree Structure +#define NMR_ERROR_OCTTREE_OUTOFBOUNDS 0x2025 + +// Could not delete mesh node, because it still had some edges connected to it +#define NMR_ERROR_COULDNOTDELETENODE 0x2026 + +// Mesh Information has not been found +#define NMR_ERROR_INVALIDINFORMATIONTYPE 0x2027 + +// Mesh Information could not be copied +#define NMR_ERROR_FACESARENOTIDENTICAL 0x2028 + +// Texture is already existing +#define NMR_ERROR_DUPLICATETEXTURE 0x2029 + +// Texture ID is already existing +#define NMR_ERROR_DUPLICATETEXTUREID 0x202A + +// Part is too large +#define NMR_ERROR_PARTTOOLARGE 0x202B + +// Texture getPath is already existing +#define NMR_ERROR_DUPLICATETEXTUREPATH 0x202C + +// Texture width is already existing +#define NMR_ERROR_DUPLICATETEXTUREWIDTH 0x202D + +// Texture height is already existing +#define NMR_ERROR_DUPLICATETEXTUREHEIGHT 0x202E + +// Texture depth is already existing +#define NMR_ERROR_DUPLICATETEXTUREDEPTH 0x202F + +// Texture content type is already existing +#define NMR_ERROR_DUPLICATETEXTURECONTENTTYPE 0x2030 + +// Texture U coordinate is already existing +#define NMR_ERROR_DUPLICATETEXTUREU 0x2031 + +// Texture V coordinate is already existing +#define NMR_ERROR_DUPLICATETEXTUREV 0x2032 + +// Texture W coordinate is already existing +#define NMR_ERROR_DUPLICATETEXTUREW 0x2033 + +// Texture scale is already existing +#define NMR_ERROR_DUPLICATETEXTURESCALE 0x2034 + +// Texture rotation is already existing +#define NMR_ERROR_DUPLICATETEXTUREROTATION 0x2035 + +// Texture tilestyle U is already existing +#define NMR_ERROR_DUPLICATETILESTYLEU 0x2036 + +// Texture tilestyle V is already existing +#define NMR_ERROR_DUPLICATETILESTYLEV 0x2037 + +// Texture tilestyle W is already existing +#define NMR_ERROR_DUPLICATETILESTYLEW 0x2038 + +// Color ID is already existing +#define NMR_ERROR_DUPLICATECOLORID 0x2039 + +// Mesh Information Block was not assigned +#define NMR_ERROR_INVALIDMESHINFORMATIONDATA 0x203A + +// Could not get stream position +#define NMR_ERROR_COULDNOTGETSTREAMPOSITION 0x203B + +// Mesh Information Object was not assigned +#define NMR_ERROR_INVALIDMESHINFORMATION 0x203C + +// Too many beams +#define NMR_ERROR_TOOMANYBEAMS 0x203D + +// Too many balls +#define NMR_ERROR_TOOMANYBALLS 0x203E + +// Invalid slice polygon index +#define NMR_ERROR_INVALIDSLICEPOLYGON 0x2040 + +// Invalid slice vertex index +#define NMR_ERROR_INVALIDSLICEVERTEX 0x2041 + +/*------------------------------------------------------------------- +Model error codes (0x8XXX) +-------------------------------------------------------------------*/ + +// 3MF Loading - OPC could not be loaded +#define NMR_ERROR_OPCREADFAILED 0x8001 + +// No model stream in OPC Container +#define NMR_ERROR_NOMODELSTREAM 0x8002 + +// Model XML could not be parsed +#define NMR_ERROR_MODELREADFAILED 0x8003 + +// No 3MF Object in OPC Container +#define NMR_ERROR_NO3MFOBJECT 0x8004 + +// Could not write Model Stream to OPC Container +#define NMR_ERROR_COULDNOTWRITEMODELSTREAM 0x8005 + +// Could not create OPC Factory +#define NMR_ERROR_OPCFACTORYCREATEFAILED 0x8006 + +// Could not read OPC Part Set +#define NMR_ERROR_OPCPARTSETREADFAILED 0x8007 + +// Could not read OPC Relationship Set +#define NMR_ERROR_OPCRELATIONSHIPSETREADFAILED 0x8008 + +// Could not get Relationship Source URI +#define NMR_ERROR_OPCRELATIONSHIPSOURCEURIFAILED 0x8009 + +// Could not get Relationship Target URI +#define NMR_ERROR_OPCRELATIONSHIPTARGETURIFAILED 0x800A + +// Could not Combine Relationship URIs +#define NMR_ERROR_OPCRELATIONSHIPCOMBINEURIFAILED 0x800B + +// Could not get Relationship Part +#define NMR_ERROR_OPCRELATIONSHIPGETPARTFAILED 0x800C + +// Could not retrieve content type +#define NMR_ERROR_OPCGETCONTENTTYPEFAILED 0x800D + +// Content type mismatch +#define NMR_ERROR_OPCCONTENTTYPEMISMATCH 0x800E + +// Could not enumerate relationships +#define NMR_ERROR_OPCRELATIONSHIPENUMERATIONFAILED 0x800F + +// Could not find relationship type +#define NMR_ERROR_OPCRELATIONSHIPNOTFOUND 0x8010 + +// Ambiguous relationship type +#define NMR_ERROR_OPCRELATIONSHIPNOTUNIQUE 0x8011 + +// Could not get OPC Model Stream +#define NMR_ERROR_OPCCOULDNOTGETMODELSTREAM 0x8012 + +// Could not create XML Reader +#define NMR_ERROR_CREATEXMLREADERFAILED 0x8013 + +// Could not set XML reader input +#define NMR_ERROR_SETXMLREADERINPUTFAILED 0x8014 + +// Could not seek in XML Model Stream +#define NMR_ERROR_COULDNOTSEEKMODELSTREAM 0x8015 + +// Could not set XML reader properties +#define NMR_ERROR_SETXMLPROPERTIESFAILED 0x8016 + +// Could not read XML node +#define NMR_ERROR_READXMLNODEFAILED 0x8017 + +// Could not retrieve local xml node name +#define NMR_ERROR_COULDNOTGETLOCALXMLNAME 0x8018 + +// Could not parse XML Node content +#define NMR_ERROR_COULDPARSEXMLCONTENT 0x8019 + +// Could not get XML Node value +#define NMR_ERROR_COULDNOTGETXMLTEXT 0x801A + +// Could not retrieve XML Node attributes +#define NMR_ERROR_COULDNOTGETXMLATTRIBUTES 0x801B + +// Could not get XML attribute value +#define NMR_ERROR_COULDNOTGETXMLVALUE 0x801C + +// XML Node has already been parsed +#define NMR_ERROR_ALREADYPARSEDXMLNODE 0x801D + +// Invalid Model Unit +#define NMR_ERROR_INVALIDMODELUNIT 0x801E + +// Invalid Model Object ID +#define NMR_ERROR_INVALIDMODELOBJECTID 0x801F + +// No Model Object ID has been given +#define NMR_ERROR_MISSINGMODELOBJECTID 0x8020 + +// Model Object is already existing +#define NMR_ERROR_DUPLICATEMODELOBJECT 0x8021 + +// Model Object ID was given twice +#define NMR_ERROR_DUPLICATEOBJECTID 0x8022 + +// Model Object Content was ambiguous +#define NMR_ERROR_AMBIGUOUSOBJECTDEFINITON 0x8023 + +// Model Vertex is missing a coordinate +#define NMR_ERROR_MODELCOORDINATEMISSING 0x8024 + +// Invalid Model Coordinates +#define NMR_ERROR_INVALIDMODELCOORDINATES 0x8025 + +// Invalid Model Coordinate Indices +#define NMR_ERROR_INVALIDMODELCOORDINATEINDICES 0x8026 + +// XML Node Name is empty +#define NMR_ERROR_NODENAMEISEMPTY 0x8027 + +// Invalid model node index +#define NMR_ERROR_INVALIDMODELNODEINDEX 0x8028 + +// Could not create OPC Package +#define NMR_ERROR_OPCPACKAGECREATEFAILED 0x8029 + +// Could not write OPC Package to Stream +#define NMR_ERROR_COULDNOTWRITEOPCPACKAGETOSTREAM 0x802A + +// Could not create OPC Part URI +#define NMR_ERROR_COULDNOTCREATEOPCPARTURI 0x802B + +// Could not create OPC Part +#define NMR_ERROR_COULDNOTCREATEOPCPART 0x802C + +// Could not get OPC Content Stream +#define NMR_ERROR_OPCCOULDNOTGETCONTENTSTREAM 0x802D + +// Could not resize OPC Stream +#define NMR_ERROR_OPCCOULDNOTRESIZESTREAM 0x802E + +// Could not seek in OPC Stream +#define NMR_ERROR_OPCCOULDNOTSEEKSTREAM 0x802F + +// Could not copy OPC Stream +#define NMR_ERROR_OPCCOULDNOTCOPYSTREAM 0x8030 + +// Could not retrieve OPC Part name +#define NMR_ERROR_COULDNOTRETRIEVEOPCPARTNAME 0x8031 + +// Could not create OPC Relationship +#define NMR_ERROR_COULDNOTCREATEOPCRELATIONSHIP 0x8032 + +// Could not create XML Writer +#define NMR_ERROR_COULDNOTCREATEXMLWRITER 0x8033 + +// Could not set XML Output stream +#define NMR_ERROR_COULDNOTSETXMLOUTPUT 0x8034 + +// Could not set XML Property +#define NMR_ERROR_COULDNOTSETXMLPROPERTY 0x8035 + +// Could not write XML Start Document +#define NMR_ERROR_COULDNOTWRITEXMLSTARTDOCUMENT 0x8036 + +// Could not write XML End Document +#define NMR_ERROR_COULDNOTWRITEXMLENDDOCUMENT 0x8037 + +// Could not flush XML Writer +#define NMR_ERROR_COULDNOTFLUSHXMLWRITER 0x8038 + +// Could not write XML Start Element +#define NMR_ERROR_COULDNOTWRITEXMLSTARTELEMENT 0x8039 + +// Could not write XML End Element +#define NMR_ERROR_COULDNOTWRITEXMLENDELEMENT 0x803A + +// Could not write XML Attribute String +#define NMR_ERROR_COULDNOTWRITEXMLATTRIBUTE 0x803B + +// Build item Object ID was not specified +#define NMR_ERROR_MISSINGBUILDITEMOBJECTID 0x803C + +// Build item Object ID is ambiguous +#define NMR_ERROR_DUPLICATEBUILDITEMOBJECTID 0x803D + +// Build item Object ID is invalid +#define NMR_ERROR_INVALIDBUILDITEMOBJECTID 0x803E + +// Could not find Object associated to the Build item +#define NMR_ERROR_COULDNOTFINDBUILDITEMOBJECT 0x803F + +// Could not find Object associated to Component +#define NMR_ERROR_COULDNOTFINDCOMPONENTOBJECT 0x8040 + +// Component Object ID is ambiguous +#define NMR_ERROR_DUPLICATECOMPONENTOBJECTID 0x8041 + +// Texture ID was not specified +#define NMR_ERROR_MISSINGMODELTEXTUREID 0x8042 + +// An object has no supported content type +#define NMR_ERROR_MISSINGOBJECTCONTENT 0x8043 + +// Invalid model reader object +#define NMR_ERROR_INVALIDREADEROBJECT 0x8044 + +// Invalid model writer object +#define NMR_ERROR_INVALIDWRITEROBJECT 0x8045 + +// Unknown model resource +#define NMR_ERROR_UNKNOWNMODELRESOURCE 0x8046 + +// Invalid stream type +#define NMR_ERROR_INVALIDSTREAMTYPE 0x8047 + +// Duplicate Material ID +#define NMR_ERROR_DUPLICATEMATERIALID 0x8048 + +// Duplicate Wallthickness +#define NMR_ERROR_DUPLICATEWALLTHICKNESS 0x8049 + +// Duplicate Fit +#define NMR_ERROR_DUPLICATEFIT 0x804A + +// Duplicate Object Type +#define NMR_ERROR_DUPLICATEOBJECTTYPE 0x804B + +// Invalid model texture coordinates +#define NMR_ERROR_INVALIDMODELTEXTURECOORDINATES 0x804C + +// Texture coordinates missing +#define NMR_ERROR_MODELTEXTURECOORDINATEMISSING 0x804D + +// Too many values in color string +#define NMR_ERROR_TOOMANYVALUESINCOLORSTRING 0x804E + +// Invalid value in color string +#define NMR_ERROR_INVALIDVALUEINCOLORSTRING 0x804F + +// Duplicate node color value +#define NMR_ERROR_DUPLICATECOLORVALUE 0x8050 + +// Missing model color ID +#define NMR_ERROR_MISSINGMODELCOLORID 0x8051 + +// Missing model material ID +#define NMR_ERROR_MISSINGMODELMATERIALID 0x8052 + +// Duplicate model resource +#define NMR_ERROR_DUPLICATEMODELRESOURCE 0x8053 + +// Metadata exceeds 2^31 elements +#define NMR_ERROR_INVALIDMETADATACOUNT 0x8054 + +// Resource type has wrong class +#define NMR_ERROR_RESOURCETYPEMISMATCH 0x8055 + +// Resources exceed 2^31 elements +#define NMR_ERROR_INVALIDRESOURCECOUNT 0x8056 + +// Build items exceed 2^31 elements +#define NMR_ERROR_INVALIDBUILDITEMCOUNT 0x8057 + +// No Build Item has been given +#define NMR_ERROR_INVALIDBUILDITEM 0x8058 + +// No Object has been given +#define NMR_ERROR_INVALIDOBJECT 0x8059 + +// No Model has been given +#define NMR_ERROR_INVALIDMODEL 0x805A + +// No Model Resource has been given +#define NMR_ERROR_INVALIDMODELRESOURCE 0x805B + +// Duplicate Model Metadata +#define NMR_ERROR_DUPLICATEMETADATA 0x805C + +// Invalid Model Metadata +#define NMR_ERROR_INVALIDMETADATA 0x805D + +// Invalid Model Component +#define NMR_ERROR_INVALIDMODELCOMPONENT 0x805E + +// Invalid Model Object Type +#define NMR_ERROR_INVALIDMODELOBJECTTYPE 0x805F + +// Missing Model Resource ID +#define NMR_ERROR_MISSINGMODELRESOURCEID 0x8060 + +// Duplicate Resource ID +#define NMR_ERROR_DUPLICATERESOURCEID 0x8061 + +// Could not write XML Content +#define NMR_ERROR_COULDNOTWRITEXMLCONTENT 0x8062 + +// Could not get XML Namespace +#define NMR_ERROR_COULDNOTGETNAMESPACE 0x8063 + +// Handle overflow +#define NMR_ERROR_HANDLEOVERFLOW 0x8064 + +// No resources in model file +#define NMR_ERROR_NORESOURCES 0x8065 + +// No build section in model file +#define NMR_ERROR_NOBUILD 0x8066 + +// Duplicate resources section in model file +#define NMR_ERROR_DUPLICATERESOURCES 0x8067 + +// Duplicate build section in model file +#define NMR_ERROR_DUPLICATEBUILDSECTION 0x8068 + +// Duplicate model node in XML Stream +#define NMR_ERROR_DUPLICATEMODELNODE 0x8069 + +// No model node in XML Stream +#define NMR_ERROR_NOMODELNODE 0x806A + +// Resource not found +#define NMR_ERROR_RESOURCENOTFOUND 0x806B + +// Unknown reader class +#define NMR_ERROR_UNKNOWNREADERCLASS 0x806C + +// Unknown writer class +#define NMR_ERROR_UNKNOWNWRITERCLASS 0x806D + +// Texture not found +#define NMR_ERROR_MODELTEXTURENOTFOUND 0x806E + +// Invalid Content Type +#define NMR_ERROR_INVALIDCONTENTTYPE 0x806F + +// Invalid Base Material +#define NMR_ERROR_INVALIDBASEMATERIAL 0x8070 + +// Too many materials +#define NMR_ERROR_TOOMANYMATERIALS 0x8071 + +// Invalid texture +#define NMR_ERROR_INVALIDTEXTURE 0x8072 + +// Could not get handle +#define NMR_ERROR_COULDNOTGETHANDLE 0x8073 + +// Build item not found +#define NMR_ERROR_BUILDITEMNOTFOUND 0x8074 + +// Could not get texture URI +#define NMR_ERROR_OPCCOULDNOTGETTEXTUREURI 0x8075 + +// Model Relationship read failed +#define NMR_ERROR_MODELRELATIONSHIPSETREADFAILED 0x8077 + +// No texture stream available +#define NMR_ERROR_NOTEXTURESTREAM 0x8078 + +// Could not create stream +#define NMR_ERROR_COULDNOTCREATESTREAM 0x8079 + +// Not supporting legacy CMYK color +#define NMR_ERROR_NOTSUPPORTINGLEGACYCMYK 0x807A + +// Invalid Texture Reference +#define NMR_ERROR_INVALIDTEXTUREREFERENCE 0x807B + +// Invalid Texture ID +#define NMR_ERROR_INVALIDTEXTUREID 0x807C + +// No model to write +#define NMR_ERROR_NOMODELTOWRITE 0x807D + +// Failed to get OPC Relationship type +#define NMR_ERROR_OPCRELATIONSHIPGETTYPEFAILED 0x807E + +// Could not get attachment URI +#define NMR_ERROR_OPCCOULDNOTGETATTACHMENTURI 0x807F + +// Duplicate Attachment Path +#define NMR_ERROR_DUPLICATEATTACHMENTPATH 0x8080 + +// Invalid Model Attachment +#define NMR_ERROR_INVALIDMODELATTACHMENT 0x8081 + +// Could not find Model Attachment +#define NMR_ERROR_ATTACHMENTNOTFOUND 0x8082 + +// Invalid required extension prefix +#define NMR_ERROR_INVALIDREQUIREDEXTENSIONPREFIX 0x8091 + +// Required extension not supported +#define NMR_ERROR_REQUIREDEXTENSIONNOTSUPPORTED 0x8092 + +// Clipping resource for beam lattice not found +#define NMR_ERROR_BEAMLATTICECLIPPINGRESOURCENOTDEFINED 0x8093 + +// Attribute of beam lattice is invalid +#define NMR_ERROR_BEAMLATTICEINVALIDATTRIBUTE 0x8094 + +// Could not get sliceref URI +#define NMR_ERROR_OPCCOULDNOTGETSLICEREFURI 0x8096 + +// Could not get sliceref stream +#define NMR_ERROR_OPCCOULDNOTGETSLICEREFSTREAM 0x8097 + +// Could not get attachment stream +#define NMR_ERROR_OPCCOULDNOTGETATTACHMENTSTREAM 0x8098 + +// Object has duplicate Slicestack ID +#define NMR_ERROR_DUPLICATE_SLICESTACKID 0x8099 + +// Slicestack Resource not found +#define NMR_ERROR_SLICESTACKRESOURCE_NOT_FOUND 0x809A + +// Slicestack contains slices and sliceref +#define NMR_ERROR_SLICESTACK_SLICESANDSLICEREF 0x809B + +// a UUID is ill formatted +#define NMR_ERROR_ILLFORMATUUID 0x809C + +// a slice stack resource is invalid +#define NMR_ERROR_INVALIDSLICESTACK 0x809D + +// Duplicate getPath +#define NMR_ERROR_DUPLICATEPATH 0x809E + +// Duplicate UUID +#define NMR_ERROR_DUPLICATEUUID 0x80A0 + +// References in production extension too deep +#define NMR_ERROR_REFERENCESTOODEEP 0x80A1 + +// References in sliceextensions extension too deep +#define NMR_ERROR_SLICEREFSTOODEEP 0x80A2 + +// z-position of slices is not increasing +#define NMR_ERROR_SLICES_Z_NOTINCREASING 0x80A3 + +// a slice polygon of a model- or solidsupport-object is not closed +#define NMR_ERROR_SLICEPOLYGONNOTCLOSED 0x80A4 + +// a closed slice polygon is a line +#define NMR_ERROR_CLOSED_SLICE_POLYGON_IS_LINE 0x80A5 + +// Invalid XML element in namespace +#define NMR_ERROR_NAMESPACE_INVALID_ELEMENT 0x80A6 + +// Invalid XML attribute in namespace +#define NMR_ERROR_NAMESPACE_INVALID_ATTRIBUTE 0x80A7 + +// Duplicate Z-top-value in slice +#define NMR_ERROR_DUPLICATETEZTOP 0x80A8 + +// Missing Z-top-value in slice +#define NMR_ERROR_MISSINGTEZTOP 0x80A9 + +// Invalid attribute in slice extension +#define NMR_ERROR_SLICE_INVALIDATTRIBUTE 0x80AA + +// Transformation matrix to a slice stack is not planar +#define NMR_ERROR_SLICETRANSFORMATIONPLANAR 0x80AC + +// a UUID is not unique within a package +#define NMR_ERROR_UUID_NOT_UNIQUE 0x80AD + +// Could not get XML Namespace for a metadatum +#define NMR_ERROR_METADATA_COULDNOTGETNAMESPACE 0x80AE + +// Invalid index for slice segment index +#define NMR_ERROR_INVALID_SLICESEGMENT_VERTEXINDEX 0x80AF + +// Missing UUID +#define NMR_ERROR_MISSINGUUID 0x80B0 + +// A slicepath is invalid +#define NMR_ERROR_INVALID_SLICEPATH 0x80B1 + +// Unknown Model Metadata +#define NMR_ERROR_UNKNOWNMETADATA 0x80B2 + +// Object has duplicate meshresolution attribute +#define NMR_ERROR_DUPLICATE_MESHRESOLUTION 0x80B3 + +// Object has invalid meshresolution attribute +#define NMR_ERROR_INVALID_MESHRESOLUTION 0x80B4 + +// Invalid model reader warnings object +#define NMR_ERROR_INVALIDREADERWARNINGSOBJECT 0x80B5 + +// Could not get OPC Thumbnail Stream +#define NMR_ERROR_OPCCOULDNOTGETTHUMBNAILSTREAM 0x80B6 + +// Duplicate Object Thumbnail +#define NMR_ERROR_DUPLICATEOBJECTTHUMBNAIL 0x80B7 + +// Duplicate Thumbnail +#define NMR_ERROR_DUPLICATETHUMBNAIL 0x80B8 + +// Duplicate Property ID +#define NMR_ERROR_DUPLICATEPID 0x80B9 + +// Duplicate Property Index +#define NMR_ERROR_DUPLICATEPINDEX 0x80BA + +// Missing Object-Level Property ID +#define NMR_ERROR_MISSINGOBJECTLEVELPID 0x80BB + +// Invalid Object-Level Property +#define NMR_ERROR_INVALIDOBJECTLEVELPID 0x80BC + +// Build-item must not point to object of type MODELOBJECTTYPE_OTHER +#define NMR_ERROR_BUILDITEMOBJECT_MUSTNOTBE_OTHER 0x80BD + +// Components-object must not have an Object-Level PID +#define NMR_ERROR_OBJECTLEVELPID_ON_COMPONENTSOBJECT 0x80BE + +// Nodes used for a beam are too close +#define NMR_ERROR_BEAMLATTICENODESTOOCLOSE 0x80BF + +// Representation resource for beam lattice is invalid +#define NMR_ERROR_BEAMLATTICE_INVALID_REPRESENTATIONRESOURCE 0x80C0 + +// Beamlattice is defined on wrong object type +#define NMR_ERROR_BEAMLATTICE_INVALID_OBJECTTYPE 0x80C1 + +// Slice only contains one vertex +#define NMR_ERROR_SLICE_ONEVERTEX 0x80C2 + +// Slice contains only one point within a polygon +#define NMR_ERROR_SLICE_ONEPOINT 0x80C3 + +// Invalid Tile Style +#define NMR_ERROR_INVALIDTILESTYLE 0x80C4 + +// Invalid Filter Style +#define NMR_ERROR_INVALIDFILTER 0x80C5 + +// Duplicate MetaDataGroup +#define NMR_ERROR_DUPLICATEMETADATAGROUP 0x80C6 + +// SliceStack must not contain slices and slicerefs +#define NMR_ERROR_SLICES_MIXING_SLICES_WITH_SLICEREFS 0x80C7 + +// SliceStack references must not be circular +#define NMR_ERROR_SLICES_SLICEREF_CIRCULAR 0x80CD + +// z-position of slicerefs is not increasing +#define NMR_ERROR_SLICES_REFS_Z_NOTINCREASING 0x80CE + +// level of slicereferences is too deep +#define NMR_ERROR_SLICES_REFS_LEVELTOODEEP 0x80CF + +// Property already registered +#define NMR_ERROR_PROPERTYIDALREADYREGISTERED 0x80D0 + +// Invalid Property Resource ID +#define NMR_ERROR_INVALIDPROPERTYRESOURCEID 0x80D1 + +// Property ID not found +#define NMR_ERROR_PROPERTYIDNOTFOUND 0x80D2 + +// Too many colors +#define NMR_ERROR_TOOMANYCOLORS 0x80D3 + +// Too many composites +#define NMR_ERROR_TOOMANYCOMPOSITES 0x80D4 + +// Composite mixing ratio out of range +#define NMR_ERROR_MIXINGRATIO_OUTOFRANGE 0x80D5 + +// A composite mixing ratio is missing +#define NMR_ERROR_MIXINGRATIO_MISSING 0x80D6 + +// Too many composite mixing ratio in the list of values +#define NMR_ERROR_MIXINGRATIO_TOOMANY 0x80D7 + +// A multiproperties must not contain another multiproperties +#define NMR_ERROR_MULTIPROPERTIES_MUST_NOT_CONTAIN_MULTIPROPERTIES 0x80D8 + +// A multiproperties must not contain multiple materials +#define NMR_ERROR_MULTIPROPERTIES_MUST_NOT_CONTAIN_MULTIPLE_MATERIALS 0x80DA + +// A multiproperties must not contain multiple colorgroups +#define NMR_ERROR_MULTIPROPERTIES_MUST_NOT_CONTAIN_MULTIPLE_COLORGOURPS 0x80DB + +// A resource of invalid type was passed to a MultiPropertyGroup +#define NMR_ERROR_MULTIPROPERTIES_INVALID_RESOURCE 0x80DC + +// A MultiMaterial does not define enough PropertyIDs +#define NMR_ERROR_MULTIPROPERTIES_NOT_ENOUGH_PROPERTYIDS_SPECIFIED 0x80DD + +// PIDs-attribute is missing +#define NMR_ERROR_MULTIPROPERTIES_MISSING_PIDS 0x80DE + +// The number of blendmethods and pids does not match +#define NMR_ERROR_MULTIPROPERTIES_DIFFERNT_NUMBER_OF_BLENDMETHODS_AND_PIDS 0x80E1 + +// Multiproperties element has duplicate pids attribute +#define NMR_ERROR_DUPLICATE_PIDS 0x80E2 + +// Multiproperties element has duplicate blendmethods attribute +#define NMR_ERROR_DUPLICATE_BLENDMETHOS 0x80E3 + +// A blendmethods attribute is invalid +#define NMR_ERROR_INVALID_BLENDMETHOD_ATTRIBUTE 0x80E4 + +// multi-element is invalid +#define NMR_ERROR_MULTIPROPERTIES_INVALID_MULTI_ELEMENT 0x80E5 + +// Invalid resource index +#define NMR_ERROR_INVALID_RESOURCE_INDEX 0x80E6 + +// Version 093 of the core-specification is not fully supported +#define NMR_ERROR_VERSION093_NOT_SUPPORTED 0x80E7 + +// Attachment Model Mismatch +#define NMR_ERROR_ATTACHMENTMODELMISMATCH 0x80E8 + +// Duplicate PackagePath +#define NMR_ERROR_DUPLICATEPACKAGEPATH 0x80E9 + +// Serialization of this Model requires the production extension +#define NMR_ERROR_PRODUCTIONEXTENSION_REQUIRED 0x80EA + +// Referenced model resource must not be in a different model +#define NMR_ERROR_MODELRESOURCE_IN_DIFFERENT_MODEL 0x80EB + +// Path attribute is not absolute +#define NMR_ERROR_PATH_NOT_ABSOLUTE 0x80EC + +// Encrypted stream header signature mismatch +#define NMR_ERROR_COULDNOTREADENCRYPTEDSTREAM 0x80ED + +// Header version mismatch +#define NMR_ERROR_ENCRYPTEDCONTENTVERSIONUNSUPPORTED 0x80EE + +// Could not get OPC KeyStore Stream +#define NMR_ERROR_KEYSTOREOPCCOULDNOTGETSTREAM 0x80F0 + +// Duplicate KeyStore Consumer id attribute on xml +#define NMR_ERROR_KEYSTOREDUPLICATECONSUMERID 0x80F1 + +// Duplicate KeyStore Consumer keyId attribute on xml +#define NMR_ERROR_KEYSTOREDUPLICATECONSUMERKEYID 0x80F2 + +// Missing KeyStore Consumer id +#define NMR_ERROR_KEYSTOREMISSINGCONSUMERID 0x80F3 + +// Duplicate KeyStore ResourceData path +#define NMR_ERROR_KEYSTOREDUPLICATERESOURCEDATAPATH 0x80F4 + +// Duplicate KeyStore DecryptRight consumerindex +#define NMR_ERROR_KEYSTOREDUPLICATECONSUMERINDEX 0x80F5 + +// Invalid KeyStore Consumer Index +#define NMR_ERROR_KEYSTOREINVALIDCONSUMERINDEX 0x80F6 + +// Invalid KeyStore encryption algorithm +#define NMR_ERROR_KEYSTOREINVALIDALGORITHM 0x80F7 + +// Invalid KeyStore compression +#define NMR_ERROR_KEYSTOREINVALIDCOMPRESSION 0x80F8 + +// Invlaid KeyStore CipherValue +#define NMR_ERROR_KEYSTOREINVALIDCIPHERVALUE 0x80F9 + +//Missing decrypt right +#define NMR_ERROR_KEYSTOREMISSINGCIPHERDATA 0x80FA + +// Duplicate KeyStore consumer +#define NMR_ERROR_KEYSTOREDUPLICATECONSUMER 0x80FB + +// Duplicate KeyStore ResourceData object +#define NMR_ERROR_KEYSTOREDUPLICATERESOURCEDATA 0x80FC + +// Duplicate KeyStore DecryptRight object +#define NMR_ERROR_KEYSTOREDUPLICATEACCESSRIGHT 0x80FD + +// Invalid KEK Param +#define NMR_ERROR_KEYSTOREMISSINGCEKPARAMS 0x80FE + +// Invalid key uuid param +#define NMR_ERROR_KEYSTOREINVALIDKEYUUID 0x80FF + +// Unsupported algorithm +#define NMR_ERROR_KEYSTOREUNSUPPORTEDALGORITHM 0x8100 + +// Dupliaced KeySore ResourceDataGroup +#define NMR_ERROR_KEYSTOREDUPLICATERESOURCEDATAGROUP 0x8101 + +// Invalid KeyStore Mask Generation Function +#define NMR_ERROR_KEYSTOREINVALIDMGF 0x8102 + +// Invalid KeyStore Digest Method +#define NMR_ERROR_KEYSTOREINVALIDDIGEST 0x8103 + +// Invalid Keystore kekparams configuration +#define NMR_ERROR_KEYSTOREINCONSISTENTKEKPARAMS 0x8104 + +// No Consumer Index +#define NMR_ERROR_KEYSTOREMISSINGCONSUMERINDEX 0x8105 + +// No kekparams +#define NMR_ERROR_KEYSTOREMISSINGKEKPARAMS 0x8106 + +// No keyuuid +#define NMR_ERROR_KEYSTOREMISSINGKEYUUID 0x8107 + +// Too many elements in a keystore xml tree +#define NMR_ERROR_KEYSTORETOOMANYELEMENTS 0x8108 + +// No path defined on resourcedata +#define NMR_ERROR_KEYSTOREMISSINGPATH 0x8109 + +// No algorithm defined +#define NMR_ERROR_KEYSTOREMISSINGALGORTHM 0x810A + +// A beamset identifier is not unique +#define NMR_ERROR_BEAMSET_IDENTIFIER_NOT_UNIQUE 0x810B + + + + + +/*------------------------------------------------------------------- +XML Parser Error Constants (0x9XXX) +-------------------------------------------------------------------*/ + +// Invalid XML attribute value +#define NMR_ERROR_XMLPARSER_INVALIDATTRIBVALUE 0x9001 + +// Invalid XML parse result +#define NMR_ERROR_XMLPARSER_INVALIDPARSERESULT 0x9002 + +// Too many XML characters used +#define NMR_ERROR_XMLPARSER_TOOMANYUSEDCHARS 0x9003 + +// Invalid XML end delimiter +#define NMR_ERROR_XMLPARSER_INVALIDENDDELIMITER 0x9004 + +// Invalid XML namespace prefix +#define NMR_ERROR_XMLPARSER_INVALIDNAMESPACEPREFIX 0x9005 + +// Could not parse XML entity +#define NMR_ERROR_XMLPARSER_COULDNOTPARSEENTITY 0x9006 + +// Empty XML element name +#define NMR_ERROR_XMLPARSER_EMPTYELEMENTNAME 0x9007 + +// Invalid characters in XML element name +#define NMR_ERROR_XMLPARSER_INVALIDCHARACTERINELEMENTNAME 0x9008 + +// Empty XML instruction name +#define NMR_ERROR_XMLPARSER_EMPTYINSTRUCTIONNAME 0x9009 + +// Invlaid XML instruction name +#define NMR_ERROR_XMLPARSER_INVALIDINSTRUCTIONNAME 0x900A + +// Could not close XML instruction +#define NMR_ERROR_XMLPARSER_COULDNOTCLOSEINSTRUCTION 0x900B + +// Could not end XML element +#define NMR_ERROR_XMLPARSER_COULDNOTENDELEMENT 0x900C + +// Empty XML end element +#define NMR_ERROR_XMLPARSER_EMPTYENDELEMENT 0x900D + +// Could not close XML element +#define NMR_ERROR_XMLPARSER_COULDNOTCLOSEELEMENT 0x900E + +// Invalid XML attribute name +#define NMR_ERROR_XMLPARSER_INVALIDATTRIBUTENAME 0x900F + +// Space in XML attribute name +#define NMR_ERROR_XMLPARSER_SPACEINATTRIBUTENAME 0x9010 + +// No quotes around XML attribute +#define NMR_ERROR_XMLPARSER_NOQUOTESAROUNDATTRIBUTE 0x9011 + +// A relationship is duplicated +#define NMR_ERROR_DUPLICATE_RELATIONSHIP 0x9012 + +// A content type is duplicated +#define NMR_ERROR_DUPLICATE_CONTENTTYPE 0x9013 + +// A content type does not have a extension +#define NMR_ERROR_CONTENTTYPE_EMPTY_EXTENSION 0x9014 + +// A content type does not have a contenttype +#define NMR_ERROR_CONTENTTYPE_EMPTY_CONTENTTYPE 0x9015 + +// An override content type does not have a partname +#define NMR_ERROR_CONTENTTYPE_EMPTY_PARTNAME 0x9016 + +// XML contains an invalid escape character +#define NMR_ERROR_XMLPARSER_INVALID_ESCAPESTRING 0x9017 + +// A box attribute is duplicated +#define NMR_ERROR_DUPLICATE_BOX_ATTRIBUTE 0x9018 + +// A matindices attribute is duplicated +#define NMR_ERROR_DUPLICATE_MATINDICES_ATTRIBUTE 0x9019 + +// + + +/*------------------------------------------------------------------- +Library errors (0xAXXX) +-------------------------------------------------------------------*/ + +// Could not get interface version +#define NMR_ERROR_COULDNOTGETINTERFACEVERSION 0xA001 + +// Invalid interface version +#define NMR_ERROR_INVALIDINTERFACEVERSION 0xA002 + +// Invalid stream size +#define NMR_ERROR_INVALIDSTREAMSIZE 0xA003 + +// Invalid name length +#define NMR_ERROR_INVALIDNAMELENGTH 0xA004 + +// Could not create model +#define NMR_ERROR_COULDNOTCREATEMODEL 0xA005 + +// Invalid Texture type +#define NMR_ERROR_INVALIDTEXTURETYPE 0xA006 + +// Key Encryption Descriptor not found +#define NMR_ERROR_KEKDESCRIPTORNOTFOUND 0xA00A + +// Content encryption descritor not found +#define NMR_ERROR_DEKDESCRIPTORNOTFOUND 0xA00B + +// Using cryptographically weak random number generator +#define NMR_ERROR_RNGCALLBACKNOTCRYPTOSTRONG 0XA00C + + +#endif // __NMR_ERRORCONST diff --git a/Include/Common/NMR_Exception.h b/Include/Common/NMR_Exception.h new file mode 100644 index 0000000..00271b1 --- /dev/null +++ b/Include/Common/NMR_Exception.h @@ -0,0 +1,56 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_Exception.h defines the generic Exception Class. +Each exception is identified via a global ErrorCode +(to be looked up in NMR_ErrorConst.h) + +--*/ + +#ifndef __NMR_EXCEPTION +#define __NMR_EXCEPTION + +#include "Common/NMR_ErrorConst.h" +#include "Common/NMR_Types.h" +#include "Common/NMR_Local.h" +#include + +namespace NMR { + + class CNMRException : public std::exception { + private: + nfError m_errorcode; + public: + CNMRException(_In_ nfError errorcode); + virtual const char * what() const throw (); + nfError getErrorCode() const; + }; + +} + +#endif // __NMR_EXCEPTION diff --git a/Include/Common/NMR_Exception_Windows.h b/Include/Common/NMR_Exception_Windows.h new file mode 100644 index 0000000..17bdf61 --- /dev/null +++ b/Include/Common/NMR_Exception_Windows.h @@ -0,0 +1,59 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_Exception_Windows.h defines the Windows Exception Class. +Each exception is identified via a global ErrorCode, and saves a Win32 HRESULT Error Code +for further information +(ErrorCodes to be looked up in NMR_ErrorConst.h) + +--*/ + +#ifndef __NMR_EXCEPTION_WINDOWS +#define __NMR_EXCEPTION_WINDOWS + +#include "Common/NMR_Exception.h" + +#ifndef __GNUC__ +#include +#else +#include "Common/Platform/NMR_WinTypes.h" +#endif + +namespace NMR { + + class CNMRException_Windows : public CNMRException { + private: + HRESULT m_hResult; + public: + CNMRException_Windows(_In_ nfError errorcode, _In_ HRESULT hResult); + HRESULT getHResult(); + }; + +} + +#endif // __NMR_EXCEPTION_WINDOWS diff --git a/Include/Common/NMR_Local.h b/Include/Common/NMR_Local.h new file mode 100644 index 0000000..5277fef --- /dev/null +++ b/Include/Common/NMR_Local.h @@ -0,0 +1,54 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_Local.h includes compiler specific settings and includes. +It should be used in every header file of the project. + +--*/ + +#ifndef __NMR_LOCAL +#define __NMR_LOCAL + +#include +#include "NMR_Assertion.h" +#include "Common/Platform/NMR_SAL.h" + +#define __NMR_INLINE __inline + +#ifndef __GNUC__ +#pragma warning (3:4706) +#endif + + +#ifndef __GNUC__ +#define LIB3MF_CDECL __cdecl +#else +#define LIB3MF_CDECL +#endif + +#endif // __NMR_LOCAL diff --git a/Include/Common/NMR_ModelWarnings.h b/Include/Common/NMR_ModelWarnings.h new file mode 100644 index 0000000..3a376f8 --- /dev/null +++ b/Include/Common/NMR_ModelWarnings.h @@ -0,0 +1,92 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderWarnings.h defines the Model Reader Warnings Class. +This class collects all import warnings with certain severity levels - in order to allow +a relaxed import policy on the file format. + +--*/ + +#ifndef __NMR_MODELREADERWARNINGS +#define __NMR_MODELREADERWARNINGS + +#include "Common/NMR_Types.h" +#include "Common/NMR_Exception.h" +#include +#include +#include + +#define NMR_MAXWARNINGCOUNT 1000000000 + +namespace NMR { + + typedef enum _eModelWarningLevel { + mrwFatal, + mrwInvalidMandatoryValue, + mrwMissingMandatoryValue, + mrwInvalidOptionalValue + } eModelWarningLevel; + + class CModelWarning { + private: + std::string m_sMessage; + eModelWarningLevel m_WarningLevel; + nfError m_nErrorCode; + public: + CModelWarning() = delete; + CModelWarning(std::string sMessage, eModelWarningLevel WarningLevel, nfError nErrorCode); + + std::string getMessage(); + eModelWarningLevel getWarningLevel(); + nfError getErrorCode(); + }; + + typedef std::shared_ptr PModelReaderWarning; + + class CModelWarnings { + private: + std::vector m_Warnings; + eModelWarningLevel m_CriticalWarningLevel; + public: + CModelWarnings(); + + eModelWarningLevel getCriticalWarningLevel (); + void setCriticalWarningLevel(_In_ eModelWarningLevel WarningLevel); + + void addWarning(_In_ nfError nErrorCode, _In_ eModelWarningLevel WarningLevel); + void addException(const _In_ CNMRException & Exception, _In_ eModelWarningLevel WarningLevel); + + nfUint32 getWarningCount(); + PModelReaderWarning getWarning(_In_ nfUint32 nIndex); + }; + + typedef std::shared_ptr PModelWarnings; + +} + +#endif // __NMR_MODELREADERWARNINGS diff --git a/Include/Common/NMR_PagedVector.h b/Include/Common/NMR_PagedVector.h new file mode 100644 index 0000000..0ffdfb9 --- /dev/null +++ b/Include/Common/NMR_PagedVector.h @@ -0,0 +1,148 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_PagedVector.h defines a vector class which allocates its memory block-wise, leading to +significant performance improvements against a standard template library vector. + +--*/ + +#ifndef __NMR_PAGEDVECTOR +#define __NMR_PAGEDVECTOR + +#include "Common/NMR_Local.h" +#include "Common/NMR_Types.h" +#include "Common/NMR_Exception.h" +#include + +#include + +namespace NMR { + + template + class CPagedVector { + nfUint32 m_nBlockSize; + nfUint32 m_nCount; + T * m_pHeadBlock; + std::vector m_pBlocks; + public: + + CPagedVector() { + m_nCount = 0; + m_pHeadBlock = NULL; + m_nBlockSize = DEFAULTBLOCKSIZE; + if (m_nBlockSize == 0) + throw CNMRException(NMR_ERROR_INVALIDBLOCKSIZE); + } + + CPagedVector(_In_ nfUint32 nBlockSize) { + m_nCount = 0; + m_pHeadBlock = NULL; + m_nBlockSize = nBlockSize; + if (m_nBlockSize == 0) + throw CNMRException(NMR_ERROR_INVALIDBLOCKSIZE); + } + + ~CPagedVector() { + clearAllData(); + } + + nfUint32 getCount() { + return m_nCount; + } + + _Ret_notnull_ T * allocData() { + nfUint32 nIdx = (m_nCount % m_nBlockSize); + + // Allocate new node block if necessary + if (nIdx == 0) { + m_pHeadBlock = new T[m_nBlockSize]; + m_pBlocks.push_back(m_pHeadBlock); + } + + T * pResult = &m_pHeadBlock[nIdx]; + m_nCount++; + + return pResult; + } + + _Ret_notnull_ T * allocData(_Out_ nfUint32 & nNewIndex) { + nNewIndex = m_nCount; + return allocData(); + } + + T& allocDataRef(_Out_ nfUint32& nNewIndex) { + nfUint32 nIdx = (m_nCount % m_nBlockSize); + + // Allocate new node block if necessary + if (nIdx == 0) { + m_pHeadBlock = new T[m_nBlockSize]; + m_pBlocks.push_back(m_pHeadBlock); + } + + nNewIndex = m_nCount; + m_nCount++; + + return m_pHeadBlock[nIdx]; + } + + _Ret_notnull_ T * getData(_In_ nfUint32 nIdx) { + if (nIdx >= m_nCount) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + + T * block = m_pBlocks[nIdx / m_nBlockSize]; + return &block[nIdx % m_nBlockSize]; + } + + T& getDataRef(_In_ nfUint32 nIdx) { + if (nIdx >= m_nCount) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + + T* block = m_pBlocks[nIdx / m_nBlockSize]; + return block[nIdx % m_nBlockSize]; + } + + void clearAllData() { + for (auto iIterator = m_pBlocks.begin(); iIterator != m_pBlocks.end(); iIterator++) + { + T * pBlock = *iIterator; + delete[] pBlock; + } + + m_pBlocks.clear(); + m_nCount = 0; + m_pHeadBlock = NULL; + } + + nfUint32 getBlockSize() { + return m_nBlockSize; + } + }; + +} + +#endif // __NMR_PAGEDVECTOR diff --git a/Include/Common/NMR_SecureContentTypes.h b/Include/Common/NMR_SecureContentTypes.h new file mode 100644 index 0000000..4d43c40 --- /dev/null +++ b/Include/Common/NMR_SecureContentTypes.h @@ -0,0 +1,118 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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 NMR_SECURECONTENTTYPES +#define NMR_SECURECONTENTTYPES + +#define KEYSTORE_TYPES_MODULUSBUFFERSIZE 257 +#define KEYSTORE_TYPES_EXPONENTBUFFERSIZE 5 +#define KEYSTORE_TYPES_IVSIZE 12 +#define KEYSTORE_TYPES_TAGSIZE 16 + +#include "Common/NMR_Types.h" +#include "Common/NMR_Local.h" + +#include +#include +namespace NMR { + + enum eKeyStoreWrapAlgorithm { + RSA_OAEP = 0, // http://www.w3.org/2009/xmlenc11#rsa-oaep, http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p + }; + + enum eKeyStoreMaskGenerationFunction { + MGF1_SHA1 = 160, // http://www.w3.org/2009/xmlenc11#mgf1sha1 + MGF1_SHA224 = 224, // http://www.w3.org/2009/xmlenc11#mgf1sha224 + MGF1_SHA256 = 256, // http://www.w3.org/2009/xmlenc11#mgf1sha256 + MGF1_SHA384 = 384, // http://www.w3.org/2009/xmlenc11#mgf1sha384 + MGF1_SHA512 = 512 // http://www.w3.org/2009/xmlenc11#mgf1sha512 + }; + + enum eKeyStoreMessageDigest { + SHA1 = 160, // http://www.w3.org/2000/09/xmldsig#sha1 + SHA256 = 256, // http://www.w3.org/2001/04/xmlenc#sha256 + SHA384 = 384, // http://www.w3.org/2001/04/xmlenc#sha384 + SHA512 = 512, // http://www.w3.org/2001/04/xmlenc#sha512 + }; + + enum eKeyStoreEncryptAlgorithm { + AES256_GCM = 1 // http://www.w3.org/2009/xmlenc11#aes256-gcm + }; + + class CKeyStoreContentEncryptionParams; + using PKeyStoreContentEncryptionParams = std::shared_ptr; + + struct ContentEncryptionContext { + void * m_pUserData; + PKeyStoreContentEncryptionParams m_sParams; + }; + using ContentEncryptionCbType = std::function; + + struct ContentEncryptionDescriptor { + ContentEncryptionCbType m_fnCrypt; + ContentEncryptionContext m_sDekDecryptData; + }; + + class CKeyStoreAccessRight; + using PKeyStoreAccessRight = std::shared_ptr; + + struct KeyWrappingContext { + void * m_pUserData; + PKeyStoreAccessRight m_pAccessRight; + }; + + using KeyWrappingCbType = std::function const &, std::vector &, KeyWrappingContext &)>; + + struct KeyWrappingDescriptor { + KeyWrappingCbType m_fnWrap; + KeyWrappingContext m_sKekDecryptData; + }; + + using CryptoRandCbType = std::function; + + struct CryptoRandGenDescriptor { + CryptoRandCbType m_fnRNG; + void * m_pUserData; + }; + + inline nfUint64 fnGetAlgorithmInitVectorSize(eKeyStoreEncryptAlgorithm ea) { + return 12; + } + + inline nfUint64 fnGetAlgorithmKeySize(eKeyStoreEncryptAlgorithm ea) { + return 32; + } + + inline nfUint64 fnGetAlgorithmAuthTagSize(eKeyStoreEncryptAlgorithm ea) { + return 16; + } +} + +#endif // !NMR_SECURECONTENTTYPES diff --git a/Include/Common/NMR_SecureContext.h b/Include/Common/NMR_SecureContext.h new file mode 100644 index 0000000..90dcde2 --- /dev/null +++ b/Include/Common/NMR_SecureContext.h @@ -0,0 +1,34 @@ + + + +#ifndef NMR_SECURECONTEXT +#define NMR_SECURECONTEXT + +#include +#include +#include "Common/NMR_SecureContentTypes.h" + +namespace NMR { + + using ClientConsumerMap = std::map; + class CSecureContext { + private: + ClientConsumerMap m_ConsumerMap; + ContentEncryptionDescriptor m_sDekDescriptor; + bool m_bHasDek = false; + public: + bool hasDekCtx() const; + ContentEncryptionDescriptor getDekCtx() const; + void setDekCtx(ContentEncryptionDescriptor const & descriptor); + + ClientConsumerMap::const_iterator kekCtxBegin() const; + ClientConsumerMap::const_iterator kekCtxEnd() const; + void addKekCtx(std::string const & consumerId, KeyWrappingDescriptor const & descriptor); + KeyWrappingDescriptor getKekCtx(std::string const & consumerId) const; + bool emptyKekCtx() const; + }; + + +} + +#endif // !NMR_SECURECONTEXT diff --git a/Include/Common/NMR_StringUtils.h b/Include/Common/NMR_StringUtils.h new file mode 100644 index 0000000..99eb316 --- /dev/null +++ b/Include/Common/NMR_StringUtils.h @@ -0,0 +1,150 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_StringUtils.h defines a few string helper functions that handle strings correctly +and Exception-safe + +--*/ + +#ifndef __NMR_STRINGUTILS +#define __NMR_STRINGUTILS + +#include "Common/NMR_Types.h" +#include "Common/NMR_Local.h" +#include +#include +#include + +#define NMR_MAXSTRINGBUFFERSIZE 1073741823 // (2^30-1) + +namespace NMR { + + template + T fnStringToType(_In_z_ const nfChar * pszValue); + + + template<> float fnStringToType(_In_z_ const nfChar * pszValue); + template<> double fnStringToType(_In_z_ const nfChar * pszValue); + template<> nfInt32 fnStringToType(_In_z_ const nfChar * pszValue); + template<> nfUint32 fnStringToType(_In_z_ const nfChar * pszValue); + template<> unsigned long fnStringToType(_In_z_ const nfChar * pszValue); + template<> std::string fnStringToType(_In_z_ const nfChar * pszValue); + + nfInt32 fnStringToInt32(_In_z_ const nfChar * pszValue); + nfUint32 fnStringToUint32(_In_z_ const nfChar * pszValue); + nfFloat fnStringToFloat(_In_z_ const nfChar * pszValue); + nfDouble fnStringToDouble(_In_z_ const nfChar * pszValue); + nfBool fnStringToSRGBColor(_In_z_ const nfChar * pszValue, _Out_ nfColor & cResult); + nfUint32 fnHexStringToUint32(_In_z_ const nfChar * pszValue); + + std::string fnInt32ToString(_In_ nfInt32 nValue); + std::string fnUint32ToString(_In_ nfUint32 nValue); + std::string fnFloatToString(_In_ nfFloat fValue, _In_ nfUint32 precision); + std::string fnDoubleToString(_In_ nfFloat dValue, _In_ nfUint32 precision); + std::string fnColorToString(_In_ nfColor cColor); + + void fnStringToCommaSeparatedIntegerTriplet(_In_z_ const nfChar * pszValue, _Out_ nfInt32 & nValue1, _Out_ nfInt32 & nValue2, _Out_ nfInt32 & nValue3); + + template + std::string fnVectorToSpaceDelimitedString(_In_ const std::vector v) { + std::string result = ""; + for (auto i = v.begin(); i != v.end(); i++) { + if (i != v.begin()) + result += " "; + result += std::to_string(*i); + } + return result; + }; + template<> std::string fnVectorToSpaceDelimitedString(_In_ const std::vector v); + + void fnStringToBufferSafe(_In_ const std::string sString, _Out_opt_ nfChar * pszBuffer, nfUint32 cbBufferSize, _Out_opt_ nfUint32 * pcbNeededChars); + void fnWStringToBufferSafe(_In_ const std::wstring sString, _Out_opt_ nfWChar * pwszBuffer, nfUint32 cbBufferSize, _Out_opt_ nfUint32 * pcbNeededChars); + + // UTF8 Functions + nfBool fnUTF16CharIsSurrogate(_In_ nfWChar cChar); + nfBool fnUTF16CharIsHighSurrogate(_In_ nfWChar cChar); + nfBool fnUTF16CharIsLowSurrogate(_In_ nfWChar cChar); + nfUint32 fnUTF16toCharacterID(_In_ nfUint16 nHighSurrogate, _In_ nfUint16 nLowSurrogate); + void fnCharacterIDToUTF16(_In_ nfUint32 nCharacterID, _Out_ nfUint16 & nHighSurrogate, _Out_ nfUint16 & nLowSurrogate); + + std::string fnUTF16toUTF8(_In_ const std::wstring sString); + std::wstring fnUTF8toUTF16(_In_ const std::string sString); + + // Returns number of converted WChars + // If the input data did contain not enough chars for the last multi-byte characters, pcbNeededCharacters is not equal 0. + // pszLastChar returns the last converted Multibyte character. + nfUint32 fnBufferedUTF8toUTF16(_In_ const nfChar * pszInBuffer, _Out_ nfWChar * pszwOutBuffer, _In_ nfUint32 cbBufferSize, _Out_ nfUint32 * pnLastChar, _Out_ nfUint32 * pcbNeededCharacters); + + // Path and File name functions + nfBool fnStartsWithPathDelimiter(_In_ const std::string sPath); + std::string fnRemoveLeadingPathDelimiter(_In_ const std::string sPath); + std::string fnIncludeLeadingPathDelimiter(_In_ const std::string sPath); + std::string fnExtractFileName(_In_ const std::string sFullPath); + std::string fnExtractFileDir(_In_ const std::string sFullPath); + + template + std::vector fnVctType_fromString(_In_ const std::string sInString) + { + std::string sString = sInString; + std::vector vctValues; + + nfChar * pszString = &(sString[0]); + nfChar * pCurrent = pszString; + + nfBool bFinished = false; + while (!bFinished) { + // Find next space + const nfChar * pBegin = pCurrent; + while ((*pCurrent != ' ') && (*pCurrent)) + pCurrent++; + + if (*pCurrent == ' ') { + *pCurrent = 0; + } + else { + bFinished = true; + } + + // If we have not found a space, convert value to T + if (pBegin != pCurrent) { + vctValues.push_back(fnStringToType(pBegin)); + } + + // If we are finished, break, otherwise skip space! + if (!bFinished) { + pCurrent++; + } + } + return vctValues; + } + + void decomposeKeyIntoNamespaceAndName(const std::string &sKey, std::string &sNameSpace, std::string &sName); + std::string composeNamespaceAndNameIntoKey(const std::string &sNameSpace, const std::string &sName); +} + +#endif // __NMR_STRINGUTILS diff --git a/Include/Common/NMR_Types.h b/Include/Common/NMR_Types.h new file mode 100644 index 0000000..df5ae9c --- /dev/null +++ b/Include/Common/NMR_Types.h @@ -0,0 +1,55 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_Types.h defines portable aliases for all standard data types. + +--*/ + +#ifndef __NMR_TYPES +#define __NMR_TYPES + +namespace NMR { + + typedef char nfChar; + typedef wchar_t nfWChar; + typedef unsigned char nfByte; + typedef unsigned short nfUint16; + typedef signed short nfInt16; + typedef int nfInt32; + typedef int nfError; + typedef bool nfBool; + typedef float nfFloat; + typedef double nfDouble; + typedef unsigned int nfUint32; + typedef unsigned int nfColor; + typedef long long nfInt64; + typedef unsigned long long nfUint64; + typedef nfUint64 nfTimeStamp; +} + +#endif // __NMR_TYPES diff --git a/Include/Common/NMR_UUID.h b/Include/Common/NMR_UUID.h new file mode 100644 index 0000000..a02ad2c --- /dev/null +++ b/Include/Common/NMR_UUID.h @@ -0,0 +1,72 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_UUID.h defines a datatype and functions to handle UUIDs + +--*/ + +#ifndef __NMR_UUID +#define __NMR_UUID + +#include "Common/NMR_Types.h" +#include "Common/NMR_Local.h" +#include + +#ifndef _WIN32 +#include +#include +#endif + + +namespace NMR +{ + class CUUID { + private: +#ifndef _WIN32 + static bool S_mtwister_initialised; + static std::mutex S_uuid_gen_mutex; + static std::random_device S_rand_dev; + static std::mt19937 S_mtwister; +#endif + std::string m_sUUID; + public: + CUUID(); + CUUID(const nfChar* pString); + CUUID(const std::string & string); + std::string toString() const; + + bool set(const nfChar* pString); + + CUUID& operator=(const CUUID& uuid); + bool operator==(const CUUID& uuid); + }; + + typedef std::shared_ptr PUUID; +} + +#endif // __NMR_UUID diff --git a/Include/Common/OPC/NMR_IOpcPackageReader.h b/Include/Common/OPC/NMR_IOpcPackageReader.h new file mode 100644 index 0000000..873d249 --- /dev/null +++ b/Include/Common/OPC/NMR_IOpcPackageReader.h @@ -0,0 +1,24 @@ +#ifndef NMR_IOPCPACKAGEREADER +#define NMR_IOPCPACKAGEREADER + +#include +#include +#include "Common/NMR_Types.h" +#include "Common/NMR_Local.h" + +namespace NMR { + class COpcPackageRelationship; + class COpcPackagePart; + using POpcPackagePart = std::shared_ptr; + + class IOpcPackageReader { + public: + virtual _Ret_maybenull_ COpcPackageRelationship * findRootRelation(_In_ std::string sRelationType, _In_ nfBool bMustBeUnique) = 0; + virtual POpcPackagePart createPart(_In_ std::string sPath) = 0; + virtual nfUint64 getPartSize(_In_ std::string sPath) = 0; + virtual void close() {} + }; + + using PIOpcPackageReader = std::shared_ptr; +} +#endif // !NMR_IOPCPACKAGEREADER diff --git a/Include/Common/OPC/NMR_IOpcPackageWriter.h b/Include/Common/OPC/NMR_IOpcPackageWriter.h new file mode 100644 index 0000000..838707a --- /dev/null +++ b/Include/Common/OPC/NMR_IOpcPackageWriter.h @@ -0,0 +1,29 @@ +#ifndef NMR_IOPCPACKAGEWRITER +#define NMR_IOPCPACKAGEWRITER + +#include +#include +#include +#include "Common/NMR_Types.h" +#include "Common/NMR_Local.h" + +namespace NMR { + class COpcPackageRelationship; + using POpcPackageRelationship = std::shared_ptr; + class COpcPackagePart; + using POpcPackagePart = std::shared_ptr; + + class IOpcPackageWriter { + public: + virtual POpcPackagePart addPart(_In_ std::string sPath) = 0; + virtual void addContentType(_In_ std::string sExtension, _In_ std::string sContentType) = 0; + virtual void addContentType(_In_ POpcPackagePart pOpcPackagePart, _In_ std::string sContentType) = 0; + virtual POpcPackageRelationship addRootRelationship(_In_ std::string sType, _In_ COpcPackagePart * pTargetPart) = 0; + virtual POpcPackageRelationship addPartRelationship(_In_ POpcPackagePart pOpcPackagePart, _In_ std::string sType, _In_ COpcPackagePart * pTargetPart) = 0; + virtual std::list addWriterSpecificRelationships(_In_ POpcPackagePart pOpcPackagePart, _In_ COpcPackagePart* pTargetPart) = 0; + virtual void close() {} + }; + + using PIOpcPackageWriter = std::shared_ptr; +} +#endif // !NMR_IOPCPACKAGEWRITER diff --git a/Include/Common/OPC/NMR_OpcPackageContentTypesReader.h b/Include/Common/OPC/NMR_OpcPackageContentTypesReader.h new file mode 100644 index 0000000..3a3a404 --- /dev/null +++ b/Include/Common/OPC/NMR_OpcPackageContentTypesReader.h @@ -0,0 +1,87 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_OpcPackageContentTypeReader.h defines a reader for the OPC Package Content Types + +--*/ + +#ifndef __NMR_OPCPACKAGECONTENTTYPESREADER +#define __NMR_OPCPACKAGECONTENTTYPESREADER + +#include "Common/3MF_ProgressMonitor.h" +#include "Common/Platform/NMR_ImportStream.h" +#include "Common/Platform/NMR_XmlReader.h" +#include +#include +#include + + +namespace NMR { + + struct COpcPackageContentType { + std::string m_extension; + std::string m_contentType; + COpcPackageContentType(std::string extension, std::string contentType) { + m_extension = extension; + m_contentType = contentType; + } + }; + struct COpcPackageContentType_Override { + std::string m_partName; + std::string m_contentType; + COpcPackageContentType_Override(std::string partName, std::string contentType) { + m_partName = partName; + m_contentType = contentType; + } + }; + typedef std::shared_ptr POpcPackageContentType; + typedef std::shared_ptr POpcPackageContentType_Override; + + class COpcPackageContentTypesReader { + private: + std::vector m_ContentTypes; + std::vector m_Overrides; + + void parseRootNode(_In_ CXmlReader * pXMLReader); + void parseChildNode(_In_ CXmlReader * pXMLReader, _In_ bool bOverride); + void parseAttributes(_In_ CXmlReader * pXMLReader); + public: + COpcPackageContentTypesReader(_In_ PImportStream pImportStream, PProgressMonitor pProgressMonitor); + ~COpcPackageContentTypesReader(); + + nfUint32 getCount(); + POpcPackageContentType getContentType(_In_ nfUint32 nIndex); + nfUint32 getOverrideCount(); + POpcPackageContentType_Override getOverrideContentType(_In_ nfUint32 nIndex); + }; + + typedef std::shared_ptr POpcPackageContentTypesReader; +} + +#endif // __NMR_OPCPACKAGECONTENTTYPESREADER + diff --git a/Include/Common/OPC/NMR_OpcPackagePart.h b/Include/Common/OPC/NMR_OpcPackagePart.h new file mode 100644 index 0000000..3c6ca8d --- /dev/null +++ b/Include/Common/OPC/NMR_OpcPackagePart.h @@ -0,0 +1,77 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_OpcPackagePart.h defines an OPC Package Part in a portable way. + +--*/ + +#ifndef __NMR_OPCPACKAGEPART +#define __NMR_OPCPACKAGEPART + +#include "Common/OPC/NMR_OpcPackageRelationship.h" +#include "Common/OPC/NMR_OpcPackageTypes.h" +#include "Common/Platform/NMR_ExportStream.h" +#include "Common/Platform/NMR_ImportStream.h" + +#include +#include + +namespace NMR { + + class COpcPackageRelationship; + typedef std::shared_ptr POpcPackageRelationship; + + class COpcPackagePart { + protected: + std::string m_sURI; + PExportStream m_pExportStream; + PImportStream m_pImportStream; + + std::multimap m_Relationships; + public: + COpcPackagePart(_In_ std::string sURI, _In_ PExportStream pExportStream); + COpcPackagePart(_In_ std::string sURI, _In_ PImportStream pImportStream); + COpcPackagePart(_In_ COpcPackagePart const & cp, _In_ PExportStream pExportStream); + COpcPackagePart(_In_ COpcPackagePart const & cp, _In_ PImportStream pImportStream); + + std::string getURI (); + PExportStream getExportStream (); + PImportStream getImportStream(); + + POpcPackageRelationship addRelationship(_In_ std::string sID, _In_ std::string sType, _In_ std::string sURI); + nfBool hasRelationships(); + std::multimap& getRelationShips(); + + void writeRelationships(_In_ PExportStream pExportStream); + }; + + typedef std::shared_ptr POpcPackagePart; + +} + +#endif // __NMR_OPCPACKAGEPART diff --git a/Include/Common/OPC/NMR_OpcPackageReader.h b/Include/Common/OPC/NMR_OpcPackageReader.h new file mode 100644 index 0000000..81f0a0e --- /dev/null +++ b/Include/Common/OPC/NMR_OpcPackageReader.h @@ -0,0 +1,89 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_OpcPackageReader.h defines an OPC Package reader in a portable way. + +--*/ + +#ifndef __NMR_OPCPACKAGEREADER +#define __NMR_OPCPACKAGEREADER + +#include "Common/OPC/NMR_IOpcPackageReader.h" +#include "Common/Platform/NMR_ImportStream.h" +#include "Common/OPC/NMR_OpcPackagePart.h" +#include "Common/OPC/NMR_OpcPackageTypes.h" +#include "Common/OPC/NMR_OpcPackageRelationship.h" +#include "Common/3MF_ProgressMonitor.h" +#include "Common/NMR_ModelWarnings.h" +#include "Libraries/libzip/zip.h" +#include +#include +#include +#include + +namespace NMR { + + class COpcPackageReader: public IOpcPackageReader { + protected: + PModelWarnings m_pWarnings; + PProgressMonitor m_pProgressMonitor; + + // ZIP Handling Variables + std::vector m_Buffer; + zip_error_t m_ZIPError; + zip_t * m_ZIParchive; + std::map m_ZIPEntries; + std::map m_Parts; + + std::string m_relationShipExtension; + + std::map m_ContentTypes; + std::list m_RootRelationships; + + void releaseZIP(); + + PImportStream openZIPEntry(_In_ std::string sName); + PImportStream openZIPEntryIndexed(_In_ nfUint64 nIndex); + + void readContentTypes(); + void readRootRelationships(); + + public: + COpcPackageReader(_In_ PImportStream pImportStream, _In_ PModelWarnings pWarnings, _In_ PProgressMonitor pProgressMonitor); + ~COpcPackageReader(); + + _Ret_maybenull_ COpcPackageRelationship * findRootRelation(_In_ std::string sRelationType, _In_ nfBool bMustBeUnique) override; + POpcPackagePart createPart(_In_ std::string sPath) override; + nfUint64 getPartSize(_In_ std::string sPath) override; + }; + + typedef std::shared_ptr POpcPackageReader; + +} + +#endif // __NMR_OPCPACKAGEREADER diff --git a/Include/Common/OPC/NMR_OpcPackageRelationship.h b/Include/Common/OPC/NMR_OpcPackageRelationship.h new file mode 100644 index 0000000..9f74e36 --- /dev/null +++ b/Include/Common/OPC/NMR_OpcPackageRelationship.h @@ -0,0 +1,67 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_OpcPackageRelationship.h defines an OPC Package Relationship Object. + +--*/ + +#ifndef __NMR_OPCPACKAGERELATIONSHIP +#define __NMR_OPCPACKAGERELATIONSHIP + +#include "Common/Platform/NMR_XmlWriter.h" +#include "Common/OPC/NMR_OpcPackagePart.h" +#include +#include +#include + +namespace NMR { + + class COpcPackagePart; + typedef std::shared_ptr POpcPackagePart; + + class COpcPackageRelationship { + private: + std::string m_sID; + std::string m_sType; + std::string m_sTargetPartURI; + + public: + COpcPackageRelationship(_In_ std::string sID, _In_ std::string sType, _In_ std::string sTargetPartURI); + std::string getID (); + std::string getType (); + std::string getTargetPartURI(); + + void writeToXML(_In_ CXmlWriter * pXMLWriter); + + }; + + typedef std::shared_ptr POpcPackageRelationship; +} + +#endif // __NMR_OPCPACKAGERELATIONSHIP + diff --git a/Include/Common/OPC/NMR_OpcPackageRelationshipReader.h b/Include/Common/OPC/NMR_OpcPackageRelationshipReader.h new file mode 100644 index 0000000..aaa9b63 --- /dev/null +++ b/Include/Common/OPC/NMR_OpcPackageRelationshipReader.h @@ -0,0 +1,66 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_OpcPackageRelationship.h defines an OPC Package Relationship Object. + +--*/ + +#ifndef __NMR_OPCPACKAGERELATIONSHIPREADER +#define __NMR_OPCPACKAGERELATIONSHIPREADER + +#include "Common/3MF_ProgressMonitor.h" +#include "Common/Platform/NMR_ImportStream.h" +#include "Common/Platform/NMR_XmlReader.h" +#include "Common/OPC/NMR_OpcPackageRelationship.h" +#include +#include +#include + + +namespace NMR { + + class COpcPackageRelationshipReader { + private: + std::map m_IDToRelationShips; + + void parseRootNode(_In_ CXmlReader * pXMLReader); + void parseChildNode(_In_ CXmlReader * pXMLReader); + void parseAttributes(_In_ CXmlReader * pXMLReader); + public: + COpcPackageRelationshipReader(_In_ PImportStream pImportStream, _In_ PProgressMonitor); + ~COpcPackageRelationshipReader(); + + nfUint32 getCount(); + POpcPackageRelationship getRelationShip(_In_ nfUint32 nIndex); + }; + + typedef std::shared_ptr POpcPackageRelationshipReader; +} + +#endif // __NMR_OPCPACKAGERELATIONSHIPREADER + diff --git a/Include/Common/OPC/NMR_OpcPackageTypes.h b/Include/Common/OPC/NMR_OpcPackageTypes.h new file mode 100644 index 0000000..bf75b93 --- /dev/null +++ b/Include/Common/OPC/NMR_OpcPackageTypes.h @@ -0,0 +1,56 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_OpcPackageTypes.h defines an OPC Package types. + +--*/ + +#ifndef __NMR_OPCPACKAGETYPES +#define __NMR_OPCPACKAGETYPES + +#define OPCPACKAGE_PATH_CONTENTTYPES "[Content_Types].xml" + +#define OPCPACKAGE_PATH_ROOTRELATIONSHIPS "_rels/.rels" +#define OPCPACKAGE_SCHEMA_CONTENTTYPES "http://schemas.openxmlformats.org/package/2006/content-types" +#define OPCPACKAGE_SCHEMA_RELATIONSHIPS "http://schemas.openxmlformats.org/package/2006/relationships" + +#define OPC_CONTENTTYPES_CONTAINER "Types" +#define OPC_CONTENTTYPES_NODE "Default" +#define OPC_CONTENTTYPES_NODE_OVERRIDE "Override" +#define OPC_CONTENTTYPES_ATTRIB_EXTENSION "Extension" +#define OPC_CONTENTTYPES_ATTRIB_CONTENTTYPE "ContentType" +#define OPC_CONTENTTYPES_ATTRIB_PARTNAME "PartName" + +#define OPC_RELS_RELATIONSHIP_CONTAINER "Relationships" +#define OPC_RELS_RELATIONSHIP_NODE "Relationship" + +#define OPC_RELS_ATTRIB_TARGET "Target" +#define OPC_RELS_ATTRIB_TYPE "Type" +#define OPC_RELS_ATTRIB_ID "Id" + +#endif // __NMR_OPCPACKAGETYPES diff --git a/Include/Common/OPC/NMR_OpcPackageWriter.h b/Include/Common/OPC/NMR_OpcPackageWriter.h new file mode 100644 index 0000000..5bbf3bf --- /dev/null +++ b/Include/Common/OPC/NMR_OpcPackageWriter.h @@ -0,0 +1,82 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_OpcPackageWriter.h defines an OPC Package writer in a portable way. + +--*/ + +#ifndef __NMR_OPCPACKAGEWRITER +#define __NMR_OPCPACKAGEWRITER + +#include "Common/Platform/NMR_ExportStream.h" +#include "Common/Platform/NMR_ExportStream_ZIP.h" +#include "Common/Platform/NMR_PortableZIPWriter.h" +#include "Common/OPC/NMR_IOpcPackageWriter.h" +#include "Common/OPC/NMR_OpcPackagePart.h" +#include "Common/OPC/NMR_OpcPackageTypes.h" +#include "Common/OPC/NMR_OpcPackageRelationship.h" +#include +#include + +namespace NMR { + + class COpcPackageWriter: public IOpcPackageWriter { + protected: + PExportStream m_pExportStream; + std::list m_Parts; + PPortableZIPWriter m_pZIPWriter; + nfInt32 m_nRelationIDCounter; + + // Extension -> ContentType + std::map m_DefaultContentTypes; + // PartName -> ContentType + std::map m_OverrideContentTypes; + std::list m_RootRelationships; + + void finishPackage(); + void writeContentTypes(); + void writeRootRelationships(); + std::string generateRelationShipID(); + public: + COpcPackageWriter(_In_ PExportStream pExportStream); + ~COpcPackageWriter(); + + POpcPackagePart addPart(_In_ std::string sPath) override; + + void addContentType(_In_ std::string sExtension, _In_ std::string sContentType) override; + void addContentType(_In_ POpcPackagePart pOpcPackagePart, _In_ std::string sContentType) override; + POpcPackageRelationship addRootRelationship(_In_ std::string sType, _In_ COpcPackagePart * pTargetPart) override; + POpcPackageRelationship addPartRelationship(_In_ POpcPackagePart pOpcPackagePart, _In_ std::string sType, _In_ COpcPackagePart * pTargetPart) override; + std::list addWriterSpecificRelationships(_In_ POpcPackagePart pOpcPackagePart, _In_ COpcPackagePart* pTargetPart) override; + }; + + typedef std::shared_ptr POpcPackageWriter; + +} + +#endif // __NMR_XMLWRITER diff --git a/Include/Common/Platform/NMR_CComPtr.h b/Include/Common/Platform/NMR_CComPtr.h new file mode 100644 index 0000000..cf2d609 --- /dev/null +++ b/Include/Common/Platform/NMR_CComPtr.h @@ -0,0 +1,38 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_CComPtr.h defines several COM Classes in a portable way. + +--*/ + +#ifndef __NMR_CCOMPTR +#define __NMR_CCOMPTR + +#include + +#endif // __NMR_CCOMPTR diff --git a/Include/Common/Platform/NMR_EncryptionHeader.h b/Include/Common/Platform/NMR_EncryptionHeader.h new file mode 100644 index 0000000..0242aee --- /dev/null +++ b/Include/Common/Platform/NMR_EncryptionHeader.h @@ -0,0 +1,44 @@ +#ifndef NMR_ENCRYPTIONHEADER +#define NMR_ENCRYPTIONHEADER + +#include +#include +#include "Common/NMR_Types.h" +#include "Common/NMR_Local.h" + +namespace NMR { + class CImportStream; + using PImportStream = std::shared_ptr; + class CExportStream; + using PExportStream = std::shared_ptr; + + union uEncryptedFileHeader { + nfByte bytes[12]; + struct sHeaderStructure { + union uMagic { + nfByte bytes[5]; + } Signature; + nfByte majorVersion; + nfByte minorVersion; + nfByte unused; + union uLength { + nfByte bytes[4]; + nfUint32 length; + } Length; + } Header; + }; + + class CEncryptionHeader { + std::vector m_rgAdditionalData; + nfUint64 m_nfHeaderSize; + public: + CEncryptionHeader(std::vector const & additionalData = std::vector()); + size_t readFrom(PImportStream from); + size_t writeTo(PExportStream to); + + std::vector const & additionalData() const; + nfUint64 headerSize() const; + }; +} + +#endif // !NMR_ENCRYPTIONHEADER diff --git a/Include/Common/Platform/NMR_ExportStream.h b/Include/Common/Platform/NMR_ExportStream.h new file mode 100644 index 0000000..15108a7 --- /dev/null +++ b/Include/Common/Platform/NMR_ExportStream.h @@ -0,0 +1,63 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ExportStream.h defines the ExportStream Class. +This is an abstract base stream class for exporting from various data sources. + +--*/ + +#ifndef __NMR_EXPORTSTREAM +#define __NMR_EXPORTSTREAM + +#include "Common/NMR_Types.h" +#include "Common/NMR_Local.h" +#include "Common/Platform/NMR_ImportStream.h" + +#define NMR_EXPORTSTREAM_WRITEBUFFERSIZE (128 * 1024) + +namespace NMR { + + class CExportStream { + private: + public: + virtual ~CExportStream() = default; + + virtual nfBool seekPosition(_In_ nfUint64 position, _In_ nfBool bHasToSucceed) = 0; + virtual nfBool seekForward(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed) = 0; + virtual nfBool seekFromEnd(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed) = 0; + virtual nfUint64 getPosition () = 0; + virtual nfUint64 writeBuffer(_In_ const void * pBuffer, _In_ nfUint64 cbTotalBytesToWrite) = 0; + virtual void close(); + void copyFrom(_In_ CImportStream * pImportStream, _In_ nfUint64 cbCount, _In_ nfUint32 cbBufferSize); + }; + + typedef std::shared_ptr PExportStream; + +} + +#endif // __NMR_EXPORTSTREAM diff --git a/Include/Common/Platform/NMR_ExportStream_Callback.h b/Include/Common/Platform/NMR_ExportStream_Callback.h new file mode 100644 index 0000000..6db300f --- /dev/null +++ b/Include/Common/Platform/NMR_ExportStream_Callback.h @@ -0,0 +1,73 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ExportStream_Callback.h defines the CExportStream_Callback Class. +This is an abstract base stream class for exporting with a callback to +custom data writer. + +--*/ + +#ifndef __NMR_EXPORTSTREAM_CALLBACK +#define __NMR_EXPORTSTREAM_CALLBACK + +#include "Common/Platform/NMR_ExportStream.h" +#include "Common/NMR_Types.h" +#include "Common/NMR_Local.h" + +#include +#include +#include + +#define EXPORTSTREAM_CALLBACK_BUFFERSIZE (1024*1024) + +namespace NMR { + + typedef std::function ExportStream_WriteCallbackType; + typedef std::function ExportStream_SeekCallbackType; + + class CExportStream_Callback : public CExportStream { + private: + ExportStream_WriteCallbackType m_pWriteCallback; + ExportStream_SeekCallbackType m_pSeekCallback; + void * m_pUserData; + nfUint64 m_nPosition; + nfUint64 m_nSize; + public: + CExportStream_Callback(); + CExportStream_Callback(_In_ ExportStream_WriteCallbackType pWriteCallback, _In_ ExportStream_SeekCallbackType pSeekCallback, void * pUserData); + + virtual nfBool seekPosition(_In_ nfUint64 position, _In_ nfBool bHasToSucceed); + virtual nfBool seekForward(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed); + virtual nfBool seekFromEnd(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed); + virtual nfUint64 getPosition(); + virtual nfUint64 writeBuffer(_In_ const void * pBuffer, _In_ nfUint64 cbTotalBytesToWrite); + }; + +} + +#endif // __NMR_EXPORTSTREAM_CALLBACK diff --git a/Include/Common/Platform/NMR_ExportStream_Compressed.h b/Include/Common/Platform/NMR_ExportStream_Compressed.h new file mode 100644 index 0000000..453bfcd --- /dev/null +++ b/Include/Common/Platform/NMR_ExportStream_Compressed.h @@ -0,0 +1,69 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ExportStream_Compressed.h defines a stream to write compressed files + +--*/ + +#ifndef __NMR_EXPORTSTREAM_COMPRESSED +#define __NMR_EXPORTSTREAM_COMPRESSED + +#include "Common/NMR_Types.h" +#include "Common/Platform/NMR_ExportStream.h" +#include "Common/Platform/NMR_PortableZIPWriter.h" +#include "Libraries/zlib/zlib.h" + +#define EXPORTSTREAM_WRITE_BUFFER_CHUNKSIZE 1024 + +namespace NMR { + + class CExportStream_Compressed: public CExportStream { + private: + z_stream m_strm; + PExportStream m_pUncompressedStream; + nfByte out[EXPORTSTREAM_WRITE_BUFFER_CHUNKSIZE]; + + nfInt32 compress(nfInt32 flush); + public: + CExportStream_Compressed() = delete; + CExportStream_Compressed(PExportStream pUncompressedStream); + ~CExportStream_Compressed(); + + virtual nfBool seekPosition(_In_ nfUint64 position, _In_ nfBool bHasToSucceed); + virtual nfBool seekForward(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed); + virtual nfBool seekFromEnd(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed); + virtual nfUint64 getPosition(); + virtual nfUint64 writeBuffer(_In_ const void * pBuffer, _In_ nfUint64 cbTotalBytesToWrite); + virtual void close(); + }; + + typedef std::shared_ptr PExportStream_Compressed; + +} + +#endif // __NMR_EXPORTSTREAM_COMPRESSED diff --git a/Include/Common/Platform/NMR_ExportStream_Dummy.h b/Include/Common/Platform/NMR_ExportStream_Dummy.h new file mode 100644 index 0000000..ea3be02 --- /dev/null +++ b/Include/Common/Platform/NMR_ExportStream_Dummy.h @@ -0,0 +1,67 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ExportStream_Dummy.h defines the ExportStream Dummy class. It will not +store any data written to it, but it will correctly track the seek position and +size of the data. It is designed to be used for measuring the size of the stream. + +--*/ + +#ifndef _NMR_EXPORT_STREAM_DUMMY +#define _NMR_EXPORT_STREAM_DUMMY + +#include "Common/Platform/NMR_ExportStream.h" + +#include "Common/NMR_Types.h" +#include "Common/NMR_Local.h" +#include "Common/Platform/NMR_ImportStream.h" + +namespace NMR { + + class CExportStreamDummy : public CExportStream { + private: + nfUint64 m_Size; + nfUint64 m_Position; + + public: + CExportStreamDummy(); + + virtual nfBool seekPosition(_In_ nfUint64 position, _In_ nfBool bHasToSucceed); + virtual nfBool seekForward(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed); + virtual nfBool seekFromEnd(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed); + virtual nfUint64 getPosition(); + virtual nfUint64 writeBuffer(_In_ const void * pBuffer, _In_ nfUint64 cbTotalBytesToWrite); + + nfUint64 getDataSize(); + }; + + typedef std::shared_ptr PExportStreamDummy; + +} + +#endif // _NMR_EXPORT_STREAM_DUMMY diff --git a/Include/Common/Platform/NMR_ExportStream_Encrypted.h b/Include/Common/Platform/NMR_ExportStream_Encrypted.h new file mode 100644 index 0000000..c6dc61e --- /dev/null +++ b/Include/Common/Platform/NMR_ExportStream_Encrypted.h @@ -0,0 +1,68 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ImportStream_Encrypted.h defines the CImportStream_Encrypted Class. +This is a stream class for importing encrypted resources from the underlying stream and handing them +to the proper callbacks that will decrypt the content before returning back to the consumer. + +--*/ + +#ifndef NMR_EXPORTSTREAM_ENCRYPTED +#define NMR_EXPORTSTREAM_ENCRYPTED + +#include "Common/NMR_Types.h" +#include "Common/NMR_SecureContentTypes.h" +#include "Common/Platform/NMR_ExportStream.h" +#include "Common/Platform/NMR_EncryptionHeader.h" + +namespace NMR { + + + + class CExportStream_Encrypted : public CExportStream { + PExportStream m_pEncryptedStream; + ContentEncryptionDescriptor m_pDecryptContext; + CEncryptionHeader m_header; + public: + CExportStream_Encrypted(PExportStream pEncryptedStream, ContentEncryptionDescriptor context); + + + // Inherited via CExportStream + virtual nfBool seekPosition(nfUint64 position, nfBool bHasToSucceed) override; + virtual nfBool seekForward(nfUint64 bytes, nfBool bHasToSucceed) override; + virtual nfBool seekFromEnd(nfUint64 bytes, nfBool bHasToSucceed) override; + virtual nfUint64 getPosition() override; + virtual nfUint64 writeBuffer(const void * pBuffer, nfUint64 cbTotalBytesToWrite) override; + + }; +} + + +#endif // !NMR_EXPORTSTREAM_ENCRYPTED + + diff --git a/Include/Common/Platform/NMR_ExportStream_Memory.h b/Include/Common/Platform/NMR_ExportStream_Memory.h new file mode 100644 index 0000000..331b531 --- /dev/null +++ b/Include/Common/Platform/NMR_ExportStream_Memory.h @@ -0,0 +1,67 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ExportStream_Memory.h defines the ExportStream to Memory Class. + +--*/ + +#ifndef _NMR_EXPORT_STREAM_MEMORY +#define _NMR_EXPORT_STREAM_MEMORY + +#include "Common/Platform/NMR_ExportStream.h" + +#include "Common/NMR_Types.h" +#include "Common/NMR_Local.h" +#include "Common/Platform/NMR_ImportStream.h" +#include + +namespace NMR { + + class CExportStreamMemory : public CExportStream { + private: + std::vector m_Buffer; + nfUint64 m_Position; + + public: + CExportStreamMemory(); + + virtual nfBool seekPosition(_In_ nfUint64 position, _In_ nfBool bHasToSucceed); + virtual nfBool seekForward(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed); + virtual nfBool seekFromEnd(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed); + virtual nfUint64 getPosition(); + virtual nfUint64 writeBuffer(_In_ const void * pBuffer, _In_ nfUint64 cbTotalBytesToWrite); + + nfUint64 getDataSize(); + const nfByte *getData(); + }; + + typedef std::shared_ptr PExportStreamMemory; + +} + +#endif // _NMR_EXPORT_STREAM_MEMORY diff --git a/Include/Common/Platform/NMR_ExportStream_Native.h b/Include/Common/Platform/NMR_ExportStream_Native.h new file mode 100644 index 0000000..bb75c51 --- /dev/null +++ b/Include/Common/Platform/NMR_ExportStream_Native.h @@ -0,0 +1,65 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ExportStream_Native.cpp defines the CExportStream_Native Class. +This is an abstract base stream class for exporting with std::streams + +Attention: Only use in UTF8-native environments! + +--*/ + +#ifndef __NMR_EXPORTSTREAM_NATIVE +#define __NMR_EXPORTSTREAM_NATIVE + +#include "Common/Platform/NMR_ExportStream.h" +#include "Common/NMR_Types.h" +#include "Common/NMR_Local.h" + +#include +#include + +namespace NMR { + + class CExportStream_Native : public CExportStream { + private: + std::ofstream m_Stream; + public: + CExportStream_Native(_In_ const nfWChar * pwszFileName); + ~CExportStream_Native(); + + virtual nfBool seekPosition(_In_ nfUint64 position, _In_ nfBool bHasToSucceed); + virtual nfBool seekForward(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed); + virtual nfBool seekFromEnd(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed); + virtual nfUint64 getPosition (); + virtual nfUint64 writeBuffer(_In_ const void * pBuffer, _In_ nfUint64 cbTotalBytesToWrite); + void copyFrom(_In_ CImportStream * pImportStream, _In_ nfUint64 cbCount, _In_ nfUint32 cbBufferSize); + }; + +} + +#endif // __NMR_EXPORTSTREAM_NATIVE diff --git a/Include/Common/Platform/NMR_ExportStream_ZIP.h b/Include/Common/Platform/NMR_ExportStream_ZIP.h new file mode 100644 index 0000000..cba4fed --- /dev/null +++ b/Include/Common/Platform/NMR_ExportStream_ZIP.h @@ -0,0 +1,77 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_PortableZIPWriter.h defines a portable stream to write into ZIP files + +--*/ + +#ifndef __NMR_EXPORTSTREAM_ZIP +#define __NMR_EXPORTSTREAM_ZIP + +#include "Common/NMR_Types.h" +#include "Common/Platform/NMR_ExportStream.h" +#include "Common/Platform/NMR_PortableZIPWriter.h" +#include "Libraries/zlib/zlib.h" + +#include + +#define ZIPEXPORTBUFFERSIZE 65536 +#define ZIPEXPORTWRITECHUNKSIZE 1048576 + +namespace NMR { + + class CExportStream_ZIP : public CExportStream { + private: + CPortableZIPWriter * m_pZIPWriter; + nfUint32 m_nEntryKey; + z_stream m_pStream; + std::array m_nOutBuffer; + + nfBool m_bIsInitialized; + + nfUint32 writeChunk(_In_ const nfByte * pData, nfUint32 cbCount); + void finishDeflate(); + public: + CExportStream_ZIP() = delete; + CExportStream_ZIP(_In_ CPortableZIPWriter * pZIPWriter, nfUint32 nEntryKey); + ~CExportStream_ZIP(); + + virtual nfBool seekPosition(_In_ nfUint64 position, _In_ nfBool bHasToSucceed); + virtual nfBool seekForward(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed); + virtual nfBool seekFromEnd(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed); + virtual nfUint64 getPosition(); + virtual nfUint64 writeBuffer(_In_ const void * pBuffer, _In_ nfUint64 cbTotalBytesToWrite); + + void flushZIPStream(); + }; + + typedef std::shared_ptr PExportStream_ZIP; + +} + +#endif // __NMR_EXPORTSTREAM_ZIP diff --git a/Include/Common/Platform/NMR_IStream.h b/Include/Common/Platform/NMR_IStream.h new file mode 100644 index 0000000..272e39b --- /dev/null +++ b/Include/Common/Platform/NMR_IStream.h @@ -0,0 +1,38 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_IStream.h defines several COM Classes in a portable way. + +--*/ + +#ifndef __NMR_ISTREAM +#define __NMR_ISTREAM + +#include + +#endif // __NMR_ISTREAM diff --git a/Include/Common/Platform/NMR_ImportStream.h b/Include/Common/Platform/NMR_ImportStream.h new file mode 100644 index 0000000..d75d8b0 --- /dev/null +++ b/Include/Common/Platform/NMR_ImportStream.h @@ -0,0 +1,65 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ImportStream.h defines the CImportStream Class. +This is an abstract base stream class for importing from various data sources. + +--*/ + +#ifndef __NMR_IMPORTSTREAM +#define __NMR_IMPORTSTREAM + +#include "Common/NMR_Types.h" +#include "Common/NMR_Local.h" + +#define NMR_IMPORTSTREAM_COPYBUFFERSIZE (128 * 1024) +#define NMR_IMPORTSTREAM_READBUFFERSIZE (128 * 1024) + +namespace NMR { + + class CImportStream; + typedef std::shared_ptr PImportStream; + + class CImportStream { + private: + public: + virtual ~CImportStream() = default; + + virtual nfBool seekPosition(_In_ nfUint64 position, _In_ nfBool bHasToSucceed) = 0; + virtual nfBool seekForward(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed) = 0; + virtual nfBool seekFromEnd(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed) = 0; + virtual nfUint64 readIntoBuffer(_In_ nfByte * pBuffer, _In_ nfUint64 cbTotalBytesToRead, nfBool bNeedsToReadAll) = 0; + virtual nfUint64 retrieveSize() = 0; + virtual void writeToFile(_In_ const nfWChar * pwszFileName) = 0; + virtual PImportStream copyToMemory() = 0; + virtual nfUint64 getPosition() = 0; + }; + +} + +#endif // __NMR_IMPORTSTREAM diff --git a/Include/Common/Platform/NMR_ImportStream_Callback.h b/Include/Common/Platform/NMR_ImportStream_Callback.h new file mode 100644 index 0000000..7f7dab0 --- /dev/null +++ b/Include/Common/Platform/NMR_ImportStream_Callback.h @@ -0,0 +1,76 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ImportStream_Callback.h defines the CImportStream_Callback Class. +This is an abstract base stream class for importing with a callback to +custom data reader. + +--*/ + +#ifndef __NMR_IMPORTSTREAM_CALLBACK +#define __NMR_IMPORTSTREAM_CALLBACK + +#include "Common/Platform/NMR_ImportStream.h" +#include "Common/NMR_Types.h" +#include "Common/NMR_Local.h" + +#include +#include +#include + +#define IMPORTSTREAM_CALLBACK_BUFFERSIZE (1024*1024) + +namespace NMR { + + typedef std::function ImportStream_ReadCallbackType; + typedef std::function ImportStream_SeekCallbackType; + + class CImportStream_Callback : public CImportStream { + private: + ImportStream_ReadCallbackType m_pReadCallback; + ImportStream_SeekCallbackType m_pSeekCallback; + void * m_pUserData; + nfUint64 m_nPosition; + nfUint64 m_nSize; + public: + CImportStream_Callback(); + CImportStream_Callback(_In_ ImportStream_ReadCallbackType pReadCallback, _In_ ImportStream_SeekCallbackType pSeekCallback, void * pUserData, _In_ nfUint64 nStreamSize); + + virtual nfBool seekPosition(_In_ nfUint64 position, _In_ nfBool bHasToSucceed); + virtual nfBool seekForward(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed); + virtual nfBool seekFromEnd(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed); + virtual nfUint64 getPosition(); + virtual nfUint64 readIntoBuffer(_In_ nfByte * pBuffer, _In_ nfUint64 cbTotalBytesToRead, nfBool bNeedsToReadAll); + virtual nfUint64 retrieveSize(); + virtual void writeToFile(_In_ const nfWChar * pwszFileName); + virtual PImportStream copyToMemory(); + }; + +} + +#endif // __NMR_IMPORTSTREAM_CALLBACK diff --git a/Include/Common/Platform/NMR_ImportStream_Compressed.h b/Include/Common/Platform/NMR_ImportStream_Compressed.h new file mode 100644 index 0000000..166aa01 --- /dev/null +++ b/Include/Common/Platform/NMR_ImportStream_Compressed.h @@ -0,0 +1,67 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ImportStream_Compressed.h defines the CImportStream_Compressed Class. +This is a stream class for importing from a compressed object. + +--*/ + +#ifndef __NMR_IMPORTSTREAM_COMPRESSED +#define __NMR_IMPORTSTREAM_COMPRESSED + +#include "Common/Platform/NMR_ImportStream.h" +#include "Libraries/zlib/zlib.h" + +#define IMPORTSTREAM_READ_BUFFER_CHUNKSIZE 1024 +#define IMPORTSTREAM_COMPRESSED_CHUNKSIZE 1024 + +namespace NMR { + + class CImportStream_Compressed : public CImportStream { + private: + PImportStream m_pCompressedStream; + z_stream m_strm; + std::vector m_decompressedBuffer; + nfByte in[IMPORTSTREAM_COMPRESSED_CHUNKSIZE]; + public: + CImportStream_Compressed(PImportStream pCompressedStream); + ~CImportStream_Compressed(); + + virtual nfBool seekPosition(_In_ nfUint64 position, _In_ nfBool bHasToSucceed); + virtual nfBool seekForward(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed); + virtual nfBool seekFromEnd(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed); + virtual nfUint64 readIntoBuffer(nfByte * pBuffer, nfUint64 cbTotalBytesToRead, nfBool bNeedsToReadAll); + virtual nfUint64 retrieveSize(); + virtual void writeToFile(_In_ const nfWChar * pwszFileName); + virtual PImportStream copyToMemory(); + virtual nfUint64 getPosition(); + }; + +} + +#endif // __NMR_IMPORTSTREAM_COMPRESSED diff --git a/Include/Common/Platform/NMR_ImportStream_Encrypted.h b/Include/Common/Platform/NMR_ImportStream_Encrypted.h new file mode 100644 index 0000000..58acd9d --- /dev/null +++ b/Include/Common/Platform/NMR_ImportStream_Encrypted.h @@ -0,0 +1,69 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ImportStream_Encrypted.h defines the CImportStream_Encrypted Class. +This is a stream class for importing encrypted resources from the underlying stream and handing them +to the proper callbacks that will decrypt the content before returning back to the consumer. + +--*/ + +#ifndef NMR_IMPORTSTREAM_ENCRYPTED +#define NMR_IMPORTSTREAM_ENCRYPTED + +#include "Common/NMR_Types.h" +#include "Common/NMR_SecureContentTypes.h" +#include "Common/Platform/NMR_ImportStream.h" +#include "Common/Platform/NMR_EncryptionHeader.h" + +#include + +namespace NMR { + + class CImportStream_Encrypted : public CImportStream { + PImportStream m_pEncryptedStream; + ContentEncryptionDescriptor m_pDecryptContext; + CEncryptionHeader m_header; + public: + CImportStream_Encrypted(PImportStream pEncryptedStream, ContentEncryptionDescriptor context); + + // Inherited via CImportStream + virtual nfBool seekPosition(nfUint64 position, nfBool bHasToSucceed) override; + virtual nfBool seekForward(nfUint64 bytes, nfBool bHasToSucceed) override; + virtual nfBool seekFromEnd(nfUint64 bytes, nfBool bHasToSucceed) override; + virtual nfUint64 readIntoBuffer(nfByte * pBuffer, nfUint64 cbTotalBytesToRead, nfBool bNeedsToReadAll) override; + virtual nfUint64 retrieveSize() override; + virtual void writeToFile(const nfWChar * pwszFileName) override; + virtual PImportStream copyToMemory() override; + virtual nfUint64 getPosition() override; + }; +} + + +#endif // !NMR_IMPORTSTREAM_ENCRYPTED + + diff --git a/Include/Common/Platform/NMR_ImportStream_Memory.h b/Include/Common/Platform/NMR_ImportStream_Memory.h new file mode 100644 index 0000000..c8b17f0 --- /dev/null +++ b/Include/Common/Platform/NMR_ImportStream_Memory.h @@ -0,0 +1,68 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ImportStream_Memory.h defines the CImportStream_Memory Class. +This is an abstract platform independent class for keeping data in a memory stream. + +--*/ + +#ifndef __NMR_IMPORTSTREAM_MEMORY +#define __NMR_IMPORTSTREAM_MEMORY + +#include "Common/Platform/NMR_ImportStream.h" +#include "Common/NMR_Types.h" +#include "Common/NMR_Local.h" + +#define NMR_IMPORTSTREAM_READCHUNKSIZE (1024*1024) + +#define NMR_IMPORTSTREAM_MAXMEMSTREAMSIZE (1024ULL*1024ULL*1024ULL*1024ULL) + +namespace NMR { + + class CImportStream_Memory : public CImportStream { + protected: + nfUint64 m_cbSize; + nfUint64 m_nPosition; + + virtual const nfByte * getAt(nfUint64 nPosition) = 0; + public: + virtual ~CImportStream_Memory(); + + virtual nfBool seekPosition(_In_ nfUint64 nPosition, _In_ nfBool bHasToSucceed); + virtual nfBool seekForward(_In_ nfUint64 cbBytes, _In_ nfBool bHasToSucceed); + virtual nfBool seekFromEnd(_In_ nfUint64 cbBytes, _In_ nfBool bHasToSucceed); + virtual nfUint64 getPosition(); + virtual nfUint64 readIntoBuffer(_In_ nfByte * pBuffer, _In_ nfUint64 cbTotalBytesToRead, nfBool bNeedsToReadAll); + virtual nfUint64 retrieveSize(); + virtual void writeToFile(_In_ const nfWChar * pwszFileName); + virtual PImportStream copyToMemory() = 0; + }; + +} + +#endif // __NMR_IMPORTSTREAM_MEMORY diff --git a/Include/Common/Platform/NMR_ImportStream_Native.h b/Include/Common/Platform/NMR_ImportStream_Native.h new file mode 100644 index 0000000..b47413c --- /dev/null +++ b/Include/Common/Platform/NMR_ImportStream_Native.h @@ -0,0 +1,65 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ImportStream_Native defines the CImportStream_Native Class. +This is a stream class for importing from streams with with std::streams. + +--*/ + +#ifndef __NMR_IMPORTSTREAM_NATIVE +#define __NMR_IMPORTSTREAM_NATIVE + +#include "Common/Platform/NMR_ImportStream.h" +#include "Common/NMR_Types.h" +#include "Common/NMR_Local.h" + +#include +#include + +namespace NMR { + + class CImportStream_Native : public CImportStream { + private: + std::ifstream m_Stream; + public: + CImportStream_Native(_In_ const nfWChar * pwszFileName); + ~CImportStream_Native(); + + virtual nfBool seekPosition(_In_ nfUint64 position, _In_ nfBool bHasToSucceed); + virtual nfBool seekForward(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed); + virtual nfBool seekFromEnd(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed); + virtual nfUint64 getPosition(); + virtual nfUint64 readIntoBuffer(_In_ nfByte * pBuffer, _In_ nfUint64 cbTotalBytesToRead, nfBool bNeedsToReadAll); + virtual nfUint64 retrieveSize(); + virtual void writeToFile(_In_ const nfWChar * pwszFileName); + virtual PImportStream copyToMemory(); + }; + +} + +#endif // __NMR_IMPORTSTREAM_NATIVE diff --git a/Include/Common/Platform/NMR_ImportStream_Shared_Memory.h b/Include/Common/Platform/NMR_ImportStream_Shared_Memory.h new file mode 100644 index 0000000..fbc158d --- /dev/null +++ b/Include/Common/Platform/NMR_ImportStream_Shared_Memory.h @@ -0,0 +1,57 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ImportStream_Shared_Memory.h implements the CImportStream_Memory Class. +This is a platform independent class for keeping data in a memory stream that doesn't own the wrapped buffer. + +--*/ + +#ifndef __NMR_IMPORTSTREAM_SHARED_MEMORY +#define __NMR_IMPORTSTREAM_SHARED_MEMORY + +#include "Common/Platform/NMR_ImportStream_Memory.h" +#include "Common/NMR_Types.h" +#include "Common/NMR_Local.h" + +#include + +namespace NMR { + + class CImportStream_Shared_Memory : public CImportStream_Memory { + private: + const nfByte * m_Buffer; + protected: + virtual const nfByte * getAt(nfUint64 nPosition); + public: + CImportStream_Shared_Memory(_In_ const nfByte * pBuffer, _In_ nfUint64 cbBytes); + virtual PImportStream copyToMemory(); + }; + +} // namespace NMR + +#endif // __NMR_IMPORTSTREAM_SHARED_MEMORY \ No newline at end of file diff --git a/Include/Common/Platform/NMR_ImportStream_Unique_Memory.h b/Include/Common/Platform/NMR_ImportStream_Unique_Memory.h new file mode 100644 index 0000000..5711f26 --- /dev/null +++ b/Include/Common/Platform/NMR_ImportStream_Unique_Memory.h @@ -0,0 +1,60 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ImportStream_Unique_Memory.h implements the CImportStream_Memory Class. +This is a platform independent class for keeping data in a memory stream that owns the wrapped buffer. + +--*/ + +#ifndef __NMR_IMPORTSTREAM_UNIQUE_MEMORY +#define __NMR_IMPORTSTREAM_UNIQUE_MEMORY + +#include "Common/Platform/NMR_ImportStream_Memory.h" +#include "Common/NMR_Types.h" +#include "Common/NMR_Local.h" + +#include + +namespace NMR { + + class CImportStream_Unique_Memory : public CImportStream_Memory { + private: + std::vector m_Buffer; + protected: + virtual const nfByte * getAt(nfUint64 nPosition); + public: + CImportStream_Unique_Memory(); + CImportStream_Unique_Memory(_In_ CImportStream * pStream, _In_ nfUint64 cbBytesToCopy, _In_ nfBool bNeedsToCopyAllBytes); + CImportStream_Unique_Memory(_In_ const nfByte * pBuffer, _In_ nfUint64 cbBytes); + + virtual PImportStream copyToMemory(); + }; + +} // namespace NMR + +#endif // __NMR_IMPORTSTREAM_UNIQUE_MEMORY \ No newline at end of file diff --git a/Include/Common/Platform/NMR_ImportStream_ZIP.h b/Include/Common/Platform/NMR_ImportStream_ZIP.h new file mode 100644 index 0000000..e834e24 --- /dev/null +++ b/Include/Common/Platform/NMR_ImportStream_ZIP.h @@ -0,0 +1,65 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ImportStream_ZIP.h defines the CImportStream_ZIP Class. +This is a stream class for importing from a libZIP object. + +--*/ + +#ifndef __NMR_IMPORTSTREAM_ZIP +#define __NMR_IMPORTSTREAM_ZIP + +#include "Common/Platform/NMR_ImportStream.h" +#include "Libraries/libzip/zip.h" + +#define IMPORTSTREAM_ZIP_CHUNKSIZE (1024 * 1024) + +namespace NMR { + + class CImportStream_ZIP : public CImportStream { + private: + zip_file_t * m_pFile; + nfUint64 m_nSize; + public: + CImportStream_ZIP() = delete; + CImportStream_ZIP(_In_ zip_file_t * pFile, _In_ nfUint64 nSize); + ~CImportStream_ZIP(); + + virtual nfBool seekPosition(_In_ nfUint64 position, _In_ nfBool bHasToSucceed); + virtual nfBool seekForward(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed); + virtual nfBool seekFromEnd(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed); + virtual nfUint64 readIntoBuffer(_In_ nfByte * pBuffer, _In_ nfUint64 cbTotalBytesToRead, nfBool bNeedsToReadAll); + virtual nfUint64 retrieveSize(); + virtual void writeToFile(_In_ const nfWChar * pwszFileName); + virtual PImportStream copyToMemory(); + virtual nfUint64 getPosition(); + }; + +} + +#endif // __NMR_IMPORTSTREAM_ZIP diff --git a/Include/Common/Platform/NMR_Platform.h b/Include/Common/Platform/NMR_Platform.h new file mode 100644 index 0000000..782106d --- /dev/null +++ b/Include/Common/Platform/NMR_Platform.h @@ -0,0 +1,52 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_Platform.h defines several factory functions which create platform specific +classes. + +--*/ + +#ifndef __NMR_PLATFORM +#define __NMR_PLATFORM + +#include "Common/Platform/NMR_ImportStream.h" +#include "Common/Platform/NMR_ExportStream.h" +#include "Common/Platform/NMR_XmlReader.h" +#include "Common/Platform/NMR_XmlWriter.h" +#include "Common/3MF_ProgressMonitor.h" + +namespace NMR { + + PImportStream fnCreateImportStreamInstance(_In_ const nfChar * pszFileName); + PExportStream fnCreateExportStreamInstance(_In_ const nfChar * pszFileName); + PXmlReader fnCreateXMLReaderInstance(_In_ PImportStream pImportStream, PProgressMonitor pProgressMonitor); + PXmlWriter fnCreateXMLWriterInstance(_In_ PExportStream pExportStream, PProgressMonitor pProgressMonitor); + +} + +#endif // __NMR_PLATFORM diff --git a/Include/Common/Platform/NMR_PortableZIPWriter.h b/Include/Common/Platform/NMR_PortableZIPWriter.h new file mode 100644 index 0000000..9465bcc --- /dev/null +++ b/Include/Common/Platform/NMR_PortableZIPWriter.h @@ -0,0 +1,79 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_PortableZIPWriter.h defines a portable and fast writer of ZIP files + +--*/ + +#ifndef __NMR_PORTABLEZIPWRITER +#define __NMR_PORTABLEZIPWRITER + +#include "Common/Platform/NMR_ExportStream.h" +#include "Common/Platform/NMR_PortableZIPWriterTypes.h" +#include "Common/Platform/NMR_PortableZIPWriterEntry.h" +#include "Common/NMR_Types.h" + +#include +#include + +namespace NMR { + + class CPortableZIPWriter { + private: + PExportStream m_pExportStream; + PPortableZIPWriterEntry m_pCurrentEntry; + nfUint32 m_nCurrentEntryKey; + nfUint32 m_nNextEntryKey; + nfBool m_bIsFinished; + + nfBool m_bWriteZIP64; + nfUint16 m_nVersionMade; + nfUint16 m_nVersionNeeded; + + std::list m_Entries; + PExportStream m_pCurrentStream; + public: + CPortableZIPWriter() = delete; + CPortableZIPWriter(_In_ PExportStream pExportStream, _In_ nfBool bWriteZIP64); + ~CPortableZIPWriter(); + + PExportStream createEntry(_In_ const std::string sName, _In_ nfTimeStamp nUnixTimeStamp); + void closeEntry(); + + void writeDeflatedBuffer(_In_ nfUint32 nEntryKey, _In_ const void * pBuffer, _In_ nfUint32 cbCompressedBytes); + void calculateChecksum(_In_ nfUint32 nEntryKey, _In_ const void * pBuffer, _In_ nfUint32 cbUncompressedBytes); + nfUint64 getCurrentSize(_In_ nfUint32 nEntryKey); + + void writeDirectory(); + }; + + typedef std::shared_ptr PPortableZIPWriter; + +} + +#endif //__NMR_PORTABLEZIPWRITER diff --git a/Include/Common/Platform/NMR_PortableZIPWriterEntry.h b/Include/Common/Platform/NMR_PortableZIPWriterEntry.h new file mode 100644 index 0000000..d504a74 --- /dev/null +++ b/Include/Common/Platform/NMR_PortableZIPWriterEntry.h @@ -0,0 +1,76 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_PortableZIPWriterEntry.h defines a portable and fast writer of ZIP files + +--*/ + +#ifndef __NMR_PORTABLEZIPWRITERENTRY +#define __NMR_PORTABLEZIPWRITERENTRY + +#include +#include +#include "Common/NMR_Types.h" +#include "Common/Platform/NMR_ExportStream.h" + +namespace NMR { + + class CPortableZIPWriterEntry { + private: + std::string m_sUTF8Name; + nfUint32 m_nCRC32; + nfUint64 m_nCompressedSize; + nfUint64 m_nUncompressedSize; + nfUint16 m_nLastModTime; + nfUint16 m_nLastModDate; + nfUint64 m_nFilePosition; + nfUint64 m_nExtInfoPosition; + nfUint64 m_nDataPosition; + public: + CPortableZIPWriterEntry(_In_ const std::string sUTF8Name, _In_ nfUint16 nLastModTime, _In_ nfUint16 nLastModDate, _In_ nfUint64 nFilePosition, _In_ nfUint64 nExtInfoPosition, _In_ nfUint64 nDataPosition); + std::string getUTF8Name(); + nfUint32 getCRC32(); + nfUint64 getCompressedSize(); + nfUint64 getUncompressedSize(); + nfUint16 getLastModTime(); + nfUint16 getLastModDate(); + nfUint64 getFilePosition(); + nfUint64 getExtInfoPosition(); + nfUint64 getDataPosition(); + void increaseCompressedSize(_In_ nfUint32 nCompressedSize); + void increaseUncompressedSize(_In_ nfUint32 nUncompressedSize); + void calculateChecksum(_In_ const void * pBuffer, _In_ nfUint32 cbCount); + + }; + + typedef std::shared_ptr PPortableZIPWriterEntry; + + +} + +#endif //__NMR_PORTABLEZIPWRITERENTRY diff --git a/Include/Common/Platform/NMR_PortableZIPWriterTypes.h b/Include/Common/Platform/NMR_PortableZIPWriterTypes.h new file mode 100644 index 0000000..496c998 --- /dev/null +++ b/Include/Common/Platform/NMR_PortableZIPWriterTypes.h @@ -0,0 +1,217 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_PortableZIPWriterTypes.h defines a portable and fast writer of ZIP files + +--*/ + +#ifndef __NMR_PORTABLEZIPWRITERTYPES +#define __NMR_PORTABLEZIPWRITERTYPES + +#include "Common/NMR_Types.h" +#include "Common/NMR_Architecture_Utils.h" + +#define ZIPFILEHEADERSIGNATURE 0x04034b50 +#define ZIPFILECENTRALHEADERSIGNATURE 0x02014b50 +#define ZIPFILEENDOFCENTRALDIRSIGNATURE 0x06054b50 +#define ZIPFILEDATADESCRIPTORSIGNATURE 0x08074b50 +#define ZIPFILEDESCRIPTOROFFSET 14 +#define ZIPFILEVERSIONNEEDED 0x0A +#define ZIPFILEVERSIONNEEDEDZIP64 0x2D +#define ZIP64FILEENDOFCENTRALDIRRECORDSIGNATURE 0x06064b50 +#define ZIP64FILEENDOFCENTRALDIRLOCATORSIGNATURE 0x07064b50 + +#define ZIPFILEEXTERNALFILEATTRIBUTES 0x80 // faArchive +#define ZIPFILEMAXENTRIES 2147483647 // 2^31 - 1 + +#define ZIPFILEDATAZIP64EXTENDEDINFORMATIONEXTRAFIELD 0x0001 + +#define ZIPFILECOMPRESSION_UNCOMPRESSED 0 +#define ZIPFILECOMPRESSION_DEFLATED 8 +#define ZIPFILEMAXFILENAMELENGTH 32000 + +#define ZIPFILEMAXIMUMSIZENON64 0xFFFFFFFF + +namespace NMR { + +#pragma pack (1) + typedef struct ZIPLOCALFILEHEADER { + nfUint32 m_nSignature; + nfUint16 m_nVersion; + nfUint16 m_nGeneralPurposeFlags; + nfUint16 m_nCompressionMethod; + nfUint16 m_nLastModTime; + nfUint16 m_nLastModDate; + nfUint32 m_nCRC32; + nfUint32 m_nCompressedSize; + nfUint32 m_nUnCompressedSize; + nfUint16 m_nFileNameLength; + nfUint16 m_nExtraFieldLength; + void swapByteOrder() { + m_nSignature = swapBytes(m_nSignature); + m_nVersion = swapBytes(m_nVersion); + m_nGeneralPurposeFlags = swapBytes(m_nGeneralPurposeFlags); + m_nCompressionMethod = swapBytes(m_nCompressionMethod); + m_nLastModTime = swapBytes(m_nLastModTime); + m_nLastModDate = swapBytes(m_nLastModDate); + m_nCRC32 = swapBytes(m_nCRC32); + m_nCompressedSize = swapBytes(m_nCompressedSize); + m_nUnCompressedSize = swapBytes(m_nUnCompressedSize); + m_nFileNameLength = swapBytes(m_nFileNameLength); + m_nExtraFieldLength = swapBytes(m_nExtraFieldLength); + } + } ZIPLOCALFILEHEADER; + + typedef struct ZIPLOCALFILEDESCRIPTOR { + nfUint32 m_nCRC32; + nfUint32 m_nCompressedSize; + nfUint32 m_nUnCompressedSize; + void swapByteOrder() { + m_nCRC32 = swapBytes(m_nCRC32); + m_nCompressedSize = swapBytes(m_nCompressedSize); + m_nUnCompressedSize = swapBytes(m_nUnCompressedSize); + } + } ZIPLOCALFILEDESCRIPTOR; + + typedef struct ZIP64EXTRAINFORMATIONFIELD { + nfUint16 m_nTag; + nfUint16 m_nFieldSize; + nfUint64 m_nUncompressedSize; + nfUint64 m_nCompressedSize; + void swapByteOrder() { + m_nTag = swapBytes(m_nTag); + m_nFieldSize = swapBytes(m_nFieldSize); + m_nUncompressedSize = swapBytes(m_nUncompressedSize); + m_nCompressedSize = swapBytes(m_nCompressedSize); + } + } ZIP64EXTRAINFORMATIONFIELD; + + typedef struct ZIPCENTRALDIRECTORYFILEHEADER { + nfUint32 m_nSignature; + nfUint16 m_nVersionMade; + nfUint16 m_nVersionNeeded; + nfUint16 m_nGeneralPurposeFlags; + nfUint16 m_nCompressionMethod; + nfUint16 m_nLastModTime; + nfUint16 m_nLastModDate; + nfUint32 m_nCRC32; + nfUint32 m_nCompressedSize; + nfUint32 m_nUnCompressedSize; + nfUint16 m_nFileNameLength; + nfUint16 m_nExtraFieldLength; + nfUint16 m_nFileCommentLength; + nfUint16 m_nDiskNumberStart; + nfUint16 m_nInternalFileAttributes; + nfUint32 m_nExternalFileAttributes; + nfUint32 m_nRelativeOffsetOfLocalHeader; + void swapByteOrder() { + m_nSignature = swapBytes(m_nSignature); + m_nVersionMade = swapBytes(m_nVersionMade); + m_nVersionNeeded = swapBytes(m_nVersionNeeded); + m_nGeneralPurposeFlags = swapBytes(m_nGeneralPurposeFlags); + m_nCompressionMethod = swapBytes(m_nCompressionMethod); + m_nLastModTime = swapBytes(m_nLastModTime); + m_nLastModDate = swapBytes(m_nLastModDate); + m_nCRC32 = swapBytes(m_nCRC32); + m_nCompressedSize = swapBytes(m_nCompressedSize); + m_nUnCompressedSize = swapBytes(m_nUnCompressedSize); + m_nFileNameLength = swapBytes(m_nFileNameLength); + m_nExtraFieldLength = swapBytes(m_nExtraFieldLength); + m_nFileCommentLength = swapBytes(m_nFileCommentLength); + m_nDiskNumberStart = swapBytes(m_nDiskNumberStart); + m_nInternalFileAttributes = swapBytes(m_nInternalFileAttributes); + m_nExternalFileAttributes = swapBytes(m_nExternalFileAttributes); + m_nRelativeOffsetOfLocalHeader = swapBytes(m_nRelativeOffsetOfLocalHeader); + } + } ZIPCENTRALDIRECTORYFILEHEADER; + + typedef struct ZIPENDOFCENTRALDIRHEADER { + nfUint32 m_nSignature; + nfUint16 m_nNumberOfDisk; + nfUint16 m_nRelativeNumberOfDisk; + nfUint16 m_nNumberOfEntriesOfDisk; + nfUint16 m_nNumberOfEntriesOfDirectory; + nfUint32 m_nSizeOfCentralDirectory; + nfUint32 m_nOffsetOfCentralDirectory; + nfUint16 m_nCommentLength; + void swapByteOrder() { + m_nSignature = swapBytes(m_nSignature); + m_nNumberOfDisk = swapBytes(m_nNumberOfDisk); + m_nRelativeNumberOfDisk = swapBytes(m_nRelativeNumberOfDisk); + m_nNumberOfEntriesOfDisk = swapBytes(m_nNumberOfEntriesOfDisk); + m_nNumberOfEntriesOfDirectory = swapBytes(m_nNumberOfEntriesOfDirectory); + m_nSizeOfCentralDirectory = swapBytes(m_nSizeOfCentralDirectory); + m_nOffsetOfCentralDirectory = swapBytes(m_nOffsetOfCentralDirectory); + m_nCommentLength = swapBytes(m_nCommentLength); + } + } ZIPENDOFCENTRALDIRHEADER; + + typedef struct ZIP64ENDOFCENTRALDIRHEADER { + nfUint32 m_nSignature; + nfUint64 m_nEndOfCentralDirHeaderRecord; + nfUint16 m_nVersionMade; + nfUint16 m_nVersionNeeded; + nfUint32 m_nNumberOfDisk; + nfUint32 m_nNumberOfDiskOfCentralDirectory; + nfUint64 m_nTotalNumberOfEntriesOnThisDisk; + nfUint64 m_nTotalNumberOfEntriesInCentralDirectory; + nfUint64 m_nSizeOfCentralDirectory; + nfUint64 m_nOffsetOfCentralDirectoryWithRespectToDisk; + // zip64 extensible data sector, variable size; not used + void swapByteOrder() { + m_nSignature = swapBytes(m_nSignature); + m_nEndOfCentralDirHeaderRecord = swapBytes(m_nEndOfCentralDirHeaderRecord); + m_nVersionMade = swapBytes(m_nVersionMade); + m_nVersionNeeded = swapBytes(m_nVersionNeeded); + m_nNumberOfDisk = swapBytes(m_nNumberOfDisk); + m_nNumberOfDiskOfCentralDirectory = swapBytes(m_nNumberOfDiskOfCentralDirectory); + m_nTotalNumberOfEntriesOnThisDisk = swapBytes(m_nTotalNumberOfEntriesOnThisDisk); + m_nTotalNumberOfEntriesInCentralDirectory = swapBytes(m_nTotalNumberOfEntriesInCentralDirectory); + m_nSizeOfCentralDirectory = swapBytes(m_nSizeOfCentralDirectory); + m_nOffsetOfCentralDirectoryWithRespectToDisk = swapBytes(m_nOffsetOfCentralDirectoryWithRespectToDisk); + } + } ZIP64ENDOFCENTRALDIRHEADER; + + typedef struct ZIP64ENDOFCENTRALDIRLOCATOR { + nfUint32 m_nSignature; + nfUint32 m_nNumberOfDiskWithStartOfZIP64EOCentralDir; + nfUint64 m_nRelativeOffset; + nfUint32 m_nTotalNumberOfDisk; + void swapByteOrder() { + m_nSignature = swapBytes(m_nSignature); + m_nNumberOfDiskWithStartOfZIP64EOCentralDir = swapBytes(m_nNumberOfDiskWithStartOfZIP64EOCentralDir); + m_nRelativeOffset = swapBytes(m_nRelativeOffset); + m_nTotalNumberOfDisk = swapBytes(m_nTotalNumberOfDisk); + } + } ZIP64ENDOFCENTRALDIRLOCATOR; + +#pragma pack() + +} + +#endif //__NMR_PORTABLEZIPWRITERTYPES diff --git a/Include/Common/Platform/NMR_SAL.h b/Include/Common/Platform/NMR_SAL.h new file mode 100644 index 0000000..67c5c31 --- /dev/null +++ b/Include/Common/Platform/NMR_SAL.h @@ -0,0 +1,58 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_SAL.h defines Security Annotations for Visual C++. For other compilers, +they are meaningless. + +--*/ + +#ifndef __NMR_SAL +#define __NMR_SAL + +#ifndef __GNUC__ + +#include + +#else + +#define _In_ +#define _In_z_ +#define _Out_ +#define _Out_opt_ +#define _Inout_ +#define _Outptr_ +#define _Ret_notnull_ +#define _In_opt_ +#define _Ret_maybenull_ +#define _Success_(ARG) +#define _Outptr_result_buffer_maybenull_(ARG) +#define _Outptr_opt_ + +#endif // __GNUC__ + +#endif // __NMR_SAL diff --git a/Include/Common/Platform/NMR_Time.h b/Include/Common/Platform/NMR_Time.h new file mode 100644 index 0000000..b9023a3 --- /dev/null +++ b/Include/Common/Platform/NMR_Time.h @@ -0,0 +1,42 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_Time.h defines platform dependent time functions + +--*/ + +#ifndef __NMR_TIME +#define __NMR_TIME + +#include "Common/NMR_Types.h" + +namespace NMR { + nfTimeStamp fnGetUnixTime(); +} + +#endif // __NMR_TIME diff --git a/Include/Common/Platform/NMR_WinTypes.h b/Include/Common/Platform/NMR_WinTypes.h new file mode 100644 index 0000000..07d017d --- /dev/null +++ b/Include/Common/Platform/NMR_WinTypes.h @@ -0,0 +1,61 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_WinTypes.h defines Standard Windows Types on Non-Windows Environments + +--*/ + +#ifndef __NMR_WINTYPES +#define __NMR_WINTYPES + +#ifdef __GNUC__ +typedef int BOOL; +typedef float FLOAT; +typedef double DOUBLE; +typedef unsigned char BYTE; +typedef unsigned int DWORD; +typedef signed int INT; +typedef float FLOAT; +typedef unsigned int ULONG; +typedef const wchar_t * LPCWSTR; +typedef char CHAR; +typedef wchar_t * LPWSTR; +typedef unsigned int UINT; +typedef unsigned int HRESULT; +typedef const char * LPCSTR; +typedef char * LPSTR; +typedef unsigned long long ULONG64; +typedef unsigned long long UINT64; + +#else + +#include + +#endif + +#endif // __NMR_WINTYPES diff --git a/Include/Common/Platform/NMR_XmlReader.h b/Include/Common/Platform/NMR_XmlReader.h new file mode 100644 index 0000000..d28c54d --- /dev/null +++ b/Include/Common/Platform/NMR_XmlReader.h @@ -0,0 +1,74 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_XMLReader.h defines a XML reader class in a portable way. + +--*/ + +#ifndef __NMR_XMLREADER +#define __NMR_XMLREADER + +#include "Common/Platform/NMR_ImportStream.h" +#include + +namespace NMR { + + enum eXmlReaderNodeType { + XMLREADERNODETYPE_UNKNOWN, + XMLREADERNODETYPE_STARTELEMENT, + XMLREADERNODETYPE_ENDELEMENT, + XMLREADERNODETYPE_TEXT + }; + + class CXmlReader { + protected: + PImportStream m_pImportStream; + public: + CXmlReader(_In_ PImportStream pImportStream); + virtual ~CXmlReader() = default; + + virtual void GetLocalName(_Outptr_result_buffer_maybenull_(*pcchLocalName + 1) const nfChar ** ppszLocalName, _Out_opt_ nfUint32 *pcchLocalName) = 0; + virtual void GetValue(_Outptr_result_buffer_maybenull_(*pcchValue + 1) const nfChar ** ppszValue, _Out_opt_ nfUint32 *pcwchValue) = 0; + virtual void GetNamespaceURI(_Outptr_result_buffer_maybenull_(*pcchValue + 1) const nfChar ** ppszValue, _Out_opt_ nfUint32 *pcchValue) = 0; + virtual bool GetNamespaceURI(const std::string &sNameSpacePrefix, std::string &sNameSpaceURI) = 0; + virtual bool NamespaceRegistered(const std::string &sNameSpaceURI) = 0; + + virtual nfBool Read(_Out_ eXmlReaderNodeType & NodeType) = 0; + virtual nfBool IsEOF() = 0; + virtual nfBool IsEmptyElement() = 0; + virtual nfBool MoveToFirstAttribute() = 0; + virtual nfBool MoveToNextAttribute() = 0; + virtual nfBool IsDefault() = 0; + virtual void CloseElement(); + }; + + typedef std::shared_ptr PXmlReader; + +} + +#endif // __NMR_XMLREADER diff --git a/Include/Common/Platform/NMR_XmlReader_Native.h b/Include/Common/Platform/NMR_XmlReader_Native.h new file mode 100644 index 0000000..e82d1df --- /dev/null +++ b/Include/Common/Platform/NMR_XmlReader_Native.h @@ -0,0 +1,179 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_XMLReader_Native.h defines a XML reader class with a native XML parsing implementation. + +--*/ + +#ifndef __NMR_XMLREADER_NATIVE +#define __NMR_XMLREADER_NATIVE + +#include "Common/Platform/NMR_XmlReader.h" +#include "Common/3MF_ProgressMonitor.h" + +#include +#include +#include +#include +#include +#include + + +#define NMR_MAXXMLNAMELENGTH 1000000 +#define NMR_MAXXMLSTRINGLENGTH 1000000 +#define NMR_MAXXMLDEPTH 1024 + +#define NMR_NATIVEXMLREADER_MINBUFFERCAPACITY 1024 +#define NMR_NATIVEXMLREADER_MAXBUFFERCAPACITY (1024 * 1024 * 1024) + +#define NMR_NATIVEXMLREADER_BUFFERMARGIN 8 + +#define NMR_NATIVEXMLTYPE_NONE 0 +#define NMR_NATIVEXMLTYPE_TEXT 1 +#define NMR_NATIVEXMLTYPE_ELEMENT 2 +#define NMR_NATIVEXMLTYPE_ELEMENTEND 3 +#define NMR_NATIVEXMLTYPE_CLOSEELEMENT 4 +#define NMR_NATIVEXMLTYPE_ATTRIBNAME 5 +#define NMR_NATIVEXMLTYPE_ATTRIBVALUE 6 +#define NMR_NATIVEXMLTYPE_COMMENT 7 +#define NMR_NATIVEXMLTYPE_CDATA 8 +#define NMR_NATIVEXMLTYPE_PROCESSINGINSTRUCTION 9 +#define NMR_NATIVEXMLTYPE_PROCESSINGINSTRUCTIONEND 10 + +#define NMR_NATIVEXMLNS_XML_PREFIX "xml" +#define NMR_NATIVEXMLNS_XML_URI "http://www.w3.org/XML/1998/namespace" + +#define NMR_NATIVEXMLNS_XMLNS_PREFIX "xmlns" +#define NMR_NATIVEXMLNS_XMLNS_URI "http://www.w3.org/2000/xmlns/" + +namespace NMR { + + class CXmlReader_Native : public CXmlReader { + private: + nfUint32 m_progressCounter; + PProgressMonitor m_pProgressMonitor; + + nfUint32 m_cbBufferCapacity; + // Allocated memory of current and next chunk + std::vector m_UTF8Buffer1; + std::vector m_UTF8Buffer2; + + // Double buffer pointers to UTF16BufferX + std::vector * m_pCurrentBuffer; + std::vector * m_pNextBuffer; + + // parsed entity list + std::vector m_CurrentEntityList; + std::vector m_CurrentEntityPrefixes; + std::vector m_CurrentEntityTypes; + + void performEscapeStringDecoding(); + + // Insert List for 0 characters + nfUint32 m_nZeroInsertIndex; + std::vector m_ZeroInsertArray; + void pushZeroInsert(_In_ nfChar * pChar); + void performZeroInserts(); + void clearZeroInserts(); + + // how large is the current buffer + nfUint32 m_nCurrentBufferSize; + nfUint32 m_nCurrentEntityCount; + nfUint32 m_nCurrentVerifiedEntityCount; + nfUint32 m_nCurrentFullEntityCount; + nfUint32 m_nCurrentEntityIndex; + nfChar * m_pCurrentEntityPointer; + + // Parsing Flag + nfBool m_bIsEOF; + + // How many characters have to be transferred into the next buffer? + nfUint32 m_cbCurrentOverflowSize; + nfChar * m_pCurrentName; + nfChar * m_pCurrentPrefix; + nfChar * m_pCurrentElementName; + nfChar * m_pCurrentElementPrefix; + nfChar * m_pCurrentValue; + nfChar m_cNullString; + + // NameSpace handling + std::string m_sDefaultNameSpace; + nfUint32 m_cbDefaultNameSpaceLength; + nfBool m_bNameSpaceIsAttribute; + std::map m_sNameSpaces; + void registerNameSpace(_In_ std::string sPrefix, _In_ std::string sURI); + + + // Fill next buffer chunk + nfBool ensureFilledBuffer(); + void readNextBufferFromStream(); + + // Parse Text Buffer + nfChar * parseUnknown(_In_ nfChar * pszStart, _In_ nfChar * pszEnd); + nfChar * parseText(_In_ nfChar * pszStart, _In_ nfChar * pszEnd); + nfChar * parseElement(_In_ nfChar * pszStart, _In_ nfChar * pszEnd); + nfChar * parseComment(_In_ nfChar * pszStart, _In_ nfChar * pszEnd); + nfChar * parseEndElement(_In_ nfChar * pszStart, _In_ nfChar * pszEnd); + nfChar * parseCloseElement(_In_ nfChar * pszStart, _In_ nfChar * pszEnd); + nfChar * parseAttributes(_In_ nfChar * pszStart, _In_ nfChar * pszEnd); + nfChar * skipSpaces(_In_ nfChar * pszStart, _In_ nfChar * pszEnd); + nfChar * parseAttributeName(_In_ nfChar * pszStart, _In_ nfChar * pszEnd); + nfChar * parseAttributeValue(_In_ nfChar * pszStart, _In_ nfChar * pszEnd); + nfChar * parseAttributeValueDoubleQuote(_In_ nfChar * pszStart, _In_ nfChar * pszEnd); + nfChar * parseAttributeValueSingleQuote(_In_ nfChar * pszStart, _In_ nfChar * pszEnd); + + nfChar * parseProcessingInstruction(_In_ nfChar * pszStart, _In_ nfChar * pszEnd); + nfChar * parseCloseProcessingInstruction(_In_ nfChar * pszStart, _In_ nfChar * pszEnd); + + void pushEntity(_In_ nfChar * pszwEntityStartChar, _In_ nfChar * pszwEntityEndDelimiter, _In_ nfChar * pszwNextEntityChar, _In_ nfByte nType, _In_ nfBool bParseForNamespaces, _In_ nfBool bEntityIsFinished); + + public: + CXmlReader_Native(_In_ PImportStream pImportStream, _In_ nfUint32 cbBufferCapacity, _In_ PProgressMonitor pProgressMonitor); + ~CXmlReader_Native(); + + virtual void GetValue(_Outptr_result_buffer_maybenull_(*pcwchValue + 1) const nfChar ** ppwszValue, _Out_opt_ nfUint32 *pcwchValue); + virtual void GetLocalName(_Outptr_result_buffer_maybenull_(*pcwchLocalName + 1) const nfChar ** ppwszLocalName, _Out_opt_ nfUint32 *pcwchLocalName); + virtual void GetNamespaceURI(_Outptr_result_buffer_maybenull_(*pcwchValue + 1) const nfChar ** ppwszValue, _Out_opt_ nfUint32 *pcwchValue); + virtual bool GetNamespaceURI(const std::string &sNameSpacePrefix, std::string &sNameSpaceURI); + virtual bool NamespaceRegistered(const std::string &sNameSpaceURI); + + virtual nfBool Read(_Out_ eXmlReaderNodeType & NodeType); + virtual nfBool IsEOF(); + virtual nfBool IsEmptyElement(); + virtual nfBool MoveToFirstAttribute(); + virtual nfBool MoveToNextAttribute(); + virtual nfBool IsDefault(); + virtual void CloseElement(); + + }; + + typedef std::shared_ptr PXmlReader_Native; + +} + +#endif // __NMR_XMLREADER_NATIVE diff --git a/Include/Common/Platform/NMR_XmlWriter.h b/Include/Common/Platform/NMR_XmlWriter.h new file mode 100644 index 0000000..e5b2e29 --- /dev/null +++ b/Include/Common/Platform/NMR_XmlWriter.h @@ -0,0 +1,71 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_XMLWriter.h defines the XML Writer Class in a portable way. + +--*/ + +#ifndef __NMR_XMLWRITER +#define __NMR_XMLWRITER + +#include "Common/Platform/NMR_ExportStream.h" +#include + +namespace NMR { + + class CXmlWriter { + protected: + PExportStream m_pExportStream; + public: + CXmlWriter(_In_ PExportStream pExportStream); + virtual ~CXmlWriter() = default; + + virtual void WriteStartDocument() = 0; + virtual void WriteEndDocument() = 0; + virtual void Flush() = 0; + + virtual void WriteAttributeString(_In_opt_ const nfChar * pszPrefix, _In_opt_ const nfChar * pszLocalName, _In_opt_ const nfChar * pszNamespaceUri, _In_opt_ const nfChar * pszValue) = 0; + virtual void WriteStartElement(_In_opt_ const nfChar * pszPrefix, _In_ const nfChar * pszLocalName, _In_opt_ const nfChar * pszNamespaceUri) = 0; + virtual void WriteEndElement() = 0; + virtual void WriteFullEndElement() = 0; + virtual void WriteRawLine(_In_ const nfChar * pszRawData, _In_ nfUint32 cbCount) = 0; + + virtual void WriteText(_In_ const nfChar * pszContent, _In_ const nfUint32 cbLength) = 0; + + virtual bool GetNamespacePrefix(const std::string &sNameSpaceURI, std::string &sNameSpacePrefix) = 0; + virtual void RegisterCustomNameSpace(const std::string &sNameSpace, const std::string &sNameSpacePrefix) = 0; + virtual nfUint32 GetNamespaceCount() = 0; + virtual std::string GetNamespacePrefix(nfUint32 nIndex) = 0; + virtual std::string GetNamespace(nfUint32 nIndex) = 0; + }; + + typedef std::shared_ptr PXmlWriter; + +} + +#endif // __NMR_XMLWRITER diff --git a/Include/Common/Platform/NMR_XmlWriter_Native.h b/Include/Common/Platform/NMR_XmlWriter_Native.h new file mode 100644 index 0000000..95284f3 --- /dev/null +++ b/Include/Common/Platform/NMR_XmlWriter_Native.h @@ -0,0 +1,108 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_XmlWriter_Native.h implements an XML Writer Class without dependencies. + +--*/ + +#ifndef __NMR_XMLWRITER_NATIVE +#define __NMR_XMLWRITER_NATIVE + +#include "Common/Platform/NMR_XmlWriter.h" +#include +#include +#include +#include + +#define NATIVEXMLSPACINGBUFFERSIZE 256 +#define NATIVEXMLSPACING 9 + +#define NATIVEXMLWRITEBUFFERSIZE 65536 +#define NATIVEXMLMAXSTRINGLENGTH 1048576 + +#define NATIVEXMLENCODING "" +#define NATIVEXMLFIXEDENCODINGLENGTH 2048 +#define NATIVEXMLENCODINGBUFFERSIZE ((NATIVEXMLFIXEDENCODINGLENGTH * 6) + 1) + + +namespace NMR { + + class CXmlWriter_Native : public CXmlWriter { + private: + std::array m_SpacingBuffer; + std::list m_NodeStack; + + std::array m_FixedEncodingBuffer; + + std::map m_sNameSpaces; + + nfBool m_bElementIsOpen; + nfBool m_bIsFreshLine; + + nfByte m_nLineEndingBuffer[2]; + nfUint32 m_nLineEndingCharCount; + nfUint32 m_nSpacesPerLayer; + nfUint32 m_nLayer; + + void writeSpaces(_In_ nfUint32 cbCount); + void writeData(_In_ const void * pData, _In_ nfUint32 cbLength); + void writeUTF8(_In_ const nfChar * pszString, _In_ nfBool bNewLine); + void writeUTF16(_In_ const nfWChar * pszString, _In_ nfBool bNewLine); + + void closeCurrentElement(_In_ nfBool bNewLine); + + // Buffer needs to be at least 6 times the length of pszwpszString + void escapeXMLString(_In_z_ const nfChar * pszString, _Out_ nfChar * pszBuffer); + + public: + CXmlWriter_Native(_In_ PExportStream pExportStream); + + virtual void WriteStartDocument(); + virtual void WriteEndDocument(); + virtual void Flush(); + + virtual void WriteAttributeString(_In_opt_ const nfChar * pszPrefix, _In_opt_ const nfChar * pszLocalName, _In_opt_ const nfChar * pszNamespaceUri, _In_opt_ const nfChar * pszValue); + virtual void WriteStartElement(_In_opt_ const nfChar * pszPrefix, _In_ const nfChar * pszLocalName, _In_opt_ const nfChar * pszNamespaceUri); + virtual void WriteEndElement(); + virtual void WriteFullEndElement(); + + virtual void WriteText(_In_ const nfChar * pszContent, _In_ const nfUint32 cbLength); + virtual void WriteRawLine(_In_ const nfChar * pszRawData, _In_ nfUint32 cbCount); + + virtual bool GetNamespacePrefix(const std::string &sNameSpaceURI, std::string &sNameSpacePrefix); + virtual void RegisterCustomNameSpace(const std::string &sNameSpace, const std::string &sNameSpacePrefix); + virtual nfUint32 GetNamespaceCount(); + virtual std::string GetNamespacePrefix(nfUint32 nIndex); + virtual std::string GetNamespace(nfUint32 nIndex); + }; + + typedef std::shared_ptr PXmlWriter_Native; + +} + +#endif // __NMR_XMLWRITER_NATIVE diff --git a/Include/Libraries/cpp-base64/base64.h b/Include/Libraries/cpp-base64/base64.h new file mode 100644 index 0000000..e8442ea --- /dev/null +++ b/Include/Libraries/cpp-base64/base64.h @@ -0,0 +1,15 @@ +// +// base64 encoding and decoding with C++. +// Version: 1.01.00 +// + +#ifndef BASE64_H_C0CE2A47_D10E_42C9_A27C_C883944E704A +#define BASE64_H_C0CE2A47_D10E_42C9_A27C_C883944E704A + +#include +#include + +std::string base64_encode(std::vector const & buffer); +std::vector base64_decode(std::string const& s); + +#endif /* BASE64_H_C0CE2A47_D10E_42C9_A27C_C883944E704A */ diff --git a/Include/Libraries/libzip/compat.h b/Include/Libraries/libzip/compat.h new file mode 100644 index 0000000..257e0ab --- /dev/null +++ b/Include/Libraries/libzip/compat.h @@ -0,0 +1,194 @@ +#ifndef _HAD_LIBZIP_COMPAT_H +#define _HAD_LIBZIP_COMPAT_H + +/* + compat.h -- compatibility defines. + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipconf.h" + +#include "config.h" + +/* to have *_MAX definitions for all types when compiling with g++ */ +#define __STDC_LIMIT_MACROS + +#ifdef _WIN32 +#ifndef ZIP_EXTERN +#ifndef ZIP_STATIC +#define ZIP_EXTERN __declspec(dllexport) +#endif +#endif +/* for dup(), close(), etc. */ +#include +#endif + +#ifdef HAVE_STDBOOL_H +#include +#else +typedef char bool; +#define true 1 +#define false 0 +#endif + +#include + +/* at least MinGW does not provide EOPNOTSUPP, see + * http://sourceforge.net/p/mingw/bugs/263/ + */ +#ifndef EOPNOTSUPP +#define EOPNOTSUPP EINVAL +#endif + +/* at least MinGW does not provide EOVERFLOW, see + * http://sourceforge.net/p/mingw/bugs/242/ + */ +#ifndef EOVERFLOW +#define EOVERFLOW EFBIG +#endif + +/* not supported on at least Windows */ +#ifndef O_CLOEXEC +#define O_CLOEXEC 0 +#endif + +#ifdef _WIN32 +#if defined(HAVE__CLOSE) +#define close _close +#endif +#if defined(HAVE__DUP) +#define dup _dup +#endif +/* crashes reported when using fdopen instead of _fdopen on Windows/Visual Studio 10/Win64 */ +#if defined(HAVE__FDOPEN) +#define fdopen _fdopen +#endif +#if !defined(HAVE_FILENO) && defined(HAVE__FILENO) +#define fileno _fileno +#endif +#if defined(HAVE__SNPRINTF) +#define snprintf _snprintf +#endif +#if defined(HAVE__STRDUP) +#if !defined(HAVE_STRDUP) || defined(_WIN32) +#undef strdup +#define strdup _strdup +#endif +#endif +#if !defined(HAVE__SETMODE) && defined(HAVE_SETMODE) +#define _setmode setmode +#endif +#if !defined(HAVE_STRTOLL) && defined(HAVE__STRTOI64) +#define strtoll _strtoi64 +#endif +#if !defined(HAVE_STRTOULL) && defined(HAVE__STRTOUI64) +#define strtoull _strtoui64 +#endif +#if defined(HAVE__UNLINK) +#define unlink _unlink +#endif +#endif + +#ifndef HAVE_FSEEKO +#define fseeko(s, o, w) (fseek((s), (long int)(o), (w))) +#endif + +#ifndef HAVE_FTELLO +#define ftello(s) ((long)ftell((s))) +#endif + +#if !defined(HAVE_STRCASECMP) +#if defined(HAVE__STRICMP) +#define strcasecmp _stricmp +#elif defined(HAVE_STRICMP) +#define strcasecmp stricmp +#endif +#endif + +#if SIZEOF_OFF_T == 8 +#define ZIP_OFF_MAX ZIP_INT64_MAX +#define ZIP_OFF_MIN ZIP_INT64_MIN +#elif SIZEOF_OFF_T == 4 +#define ZIP_OFF_MAX ZIP_INT32_MAX +#define ZIP_OFF_MIN ZIP_INT32_MIN +#elif SIZEOF_OFF_T == 2 +#define ZIP_OFF_MAX ZIP_INT16_MAX +#define ZIP_OFF_MIN ZIP_INT16_MIN +#else +#error unsupported size of off_t +#endif + +#if defined(HAVE_FTELLO) && defined(HAVE_FSEEKO) +#define ZIP_FSEEK_MAX ZIP_OFF_MAX +#define ZIP_FSEEK_MIN ZIP_OFF_MIN +#else +#include +#define ZIP_FSEEK_MAX LONG_MAX +#define ZIP_FSEEK_MIN LONG_MIN +#endif + +#ifndef SIZE_MAX +#if SIZEOF_SIZE_T == 8 +#define SIZE_MAX ZIP_INT64_MAX +#elif SIZEOF_SIZE_T == 4 +#define SIZE_MAX ZIP_INT32_MAX +#elif SIZEOF_SIZE_T == 2 +#define SIZE_MAX ZIP_INT16_MAX +#else +#error unsupported size of size_t +#endif +#endif + +#ifndef PRId64 +#ifdef _MSC_VER +#define PRId64 "I64d" +#else +#define PRId64 "lld" +#endif +#endif + +#ifndef PRIu64 +#ifdef _MSC_VER +#define PRIu64 "I64u" +#else +#define PRIu64 "llu" +#endif +#endif + +#ifndef S_ISDIR +#define S_ISDIR(mode) (((mode)&S_IFMT) == S_IFDIR) +#endif + +#ifndef S_ISREG +#define S_ISREG(mode) (((mode)&S_IFMT) == S_IFREG) +#endif + +#endif /* compat.h */ diff --git a/Include/Libraries/libzip/config.h b/Include/Libraries/libzip/config.h new file mode 100644 index 0000000..5112dd9 --- /dev/null +++ b/Include/Libraries/libzip/config.h @@ -0,0 +1,62 @@ +#ifndef HAD_CONFIG_H +#define HAD_CONFIG_H +#ifndef _HAD_ZIPCONF_H +#include "zipconf.h" +#endif +/* BEGIN DEFINES */ +/* #undef HAVE___PROGNAME */ +#define HAVE__CLOSE +#define HAVE__DUP +#define HAVE__FDOPEN +#define HAVE__FILENO +#define HAVE__SETMODE +/* #undef HAVE__SNPRINTF */ +#define HAVE__STRDUP +#define HAVE__STRICMP +#define HAVE__STRTOI64 +#define HAVE__STRTOUI64 +/* #undef HAVE__UMASK */ +#define HAVE__UNLINK +/* #undef HAVE_ARC4RANDOM */ +/* #undef HAVE_CLONEFILE */ +/* #undef HAVE_COMMONCRYPTO */ +/* #define HAVE_CRYPTO */ +/* #undef HAVE_FICLONERANGE */ +#define HAVE_FILENO +/* #undef HAVE_FSEEKO */ +/* #undef HAVE_FTELLO */ +/* #undef HAVE_GETPROGNAME */ +/* #undef HAVE_GNUTLS */ +/* #undef HAVE_LIBBZ2 */ +/* #undef HAVE_LIBLZMA */ +/* #undef HAVE_LIBZSTD */ +/* #undef HAVE_LOCALTIME_R */ +/* #undef HAVE_MBEDTLS */ +/* #undef HAVE_MKSTEMP */ +/* #undef HAVE_NULLABLE */ +/* #undef HAVE_OPENSSL */ +#define HAVE_SETMODE +/* #undef HAVE_STRCASECMP */ +#define HAVE_STRDUP +#define HAVE_STRICMP +#define HAVE_STRTOLL +#define HAVE_STRTOULL +/* #undef HAVE_STRUCT_TM_TM_ZONE */ +#define HAVE_STDBOOL_H +/* #undef HAVE_STRINGS_H */ +/* #undef HAVE_UNISTD_H */ +/* #define HAVE_WINDOWS_CRYPTO */ +#define SIZEOF_OFF_T 4 +#define SIZEOF_SIZE_T 8 +/* #undef HAVE_DIRENT_H */ +/* #undef HAVE_FTS_H */ +/* #undef HAVE_NDIR_H */ +/* #undef HAVE_SYS_DIR_H */ +/* #undef HAVE_SYS_NDIR_H */ +/* #undef WORDS_BIGENDIAN */ +#define HAVE_SHARED +/* END DEFINES */ +#define PACKAGE "libzip" +#define VERSION "1.7.3.1" + +#endif /* HAD_CONFIG_H */ diff --git a/Include/Libraries/libzip/zip.h b/Include/Libraries/libzip/zip.h new file mode 100644 index 0000000..4a1bf89 --- /dev/null +++ b/Include/Libraries/libzip/zip.h @@ -0,0 +1,481 @@ +#ifndef _HAD_ZIP_H +#define _HAD_ZIP_H + +/* + zip.h -- exported declarations. + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + + +#ifdef __cplusplus +extern "C" { +#if 0 +} /* fix autoindent */ +#endif +#endif + +#include + +#ifndef ZIP_EXTERN +#ifndef ZIP_STATIC +#ifdef _WIN32 +#define ZIP_EXTERN __declspec(dllimport) +#elif defined(__GNUC__) && __GNUC__ >= 4 +#define ZIP_EXTERN __attribute__((visibility("default"))) +#else +#define ZIP_EXTERN +#endif +#else +#define ZIP_EXTERN +#endif +#endif + +#include +#include +#include + +/* flags for zip_open */ + +#define ZIP_CREATE 1 +#define ZIP_EXCL 2 +#define ZIP_CHECKCONS 4 +#define ZIP_TRUNCATE 8 +#define ZIP_RDONLY 16 + + +/* flags for zip_name_locate, zip_fopen, zip_stat, ... */ + +#define ZIP_FL_NOCASE 1u /* ignore case on name lookup */ +#define ZIP_FL_NODIR 2u /* ignore directory component */ +#define ZIP_FL_COMPRESSED 4u /* read compressed data */ +#define ZIP_FL_UNCHANGED 8u /* use original data, ignoring changes */ +#define ZIP_FL_RECOMPRESS 16u /* force recompression of data */ +#define ZIP_FL_ENCRYPTED 32u /* read encrypted data (implies ZIP_FL_COMPRESSED) */ +#define ZIP_FL_ENC_GUESS 0u /* guess string encoding (is default) */ +#define ZIP_FL_ENC_RAW 64u /* get unmodified string */ +#define ZIP_FL_ENC_STRICT 128u /* follow specification strictly */ +#define ZIP_FL_LOCAL 256u /* in local header */ +#define ZIP_FL_CENTRAL 512u /* in central directory */ +/* 1024u reserved for internal use */ +#define ZIP_FL_ENC_UTF_8 2048u /* string is UTF-8 encoded */ +#define ZIP_FL_ENC_CP437 4096u /* string is CP437 encoded */ +#define ZIP_FL_OVERWRITE 8192u /* zip_file_add: if file with name exists, overwrite (replace) it */ + +/* archive global flags flags */ + +#define ZIP_AFL_RDONLY 2u /* read only -- cannot be cleared */ + + +/* create a new extra field */ + +#define ZIP_EXTRA_FIELD_ALL ZIP_UINT16_MAX +#define ZIP_EXTRA_FIELD_NEW ZIP_UINT16_MAX + + +/* libzip error codes */ + +#define ZIP_ER_OK 0 /* N No error */ +#define ZIP_ER_MULTIDISK 1 /* N Multi-disk zip archives not supported */ +#define ZIP_ER_RENAME 2 /* S Renaming temporary file failed */ +#define ZIP_ER_CLOSE 3 /* S Closing zip archive failed */ +#define ZIP_ER_SEEK 4 /* S Seek error */ +#define ZIP_ER_READ 5 /* S Read error */ +#define ZIP_ER_WRITE 6 /* S Write error */ +#define ZIP_ER_CRC 7 /* N CRC error */ +#define ZIP_ER_ZIPCLOSED 8 /* N Containing zip archive was closed */ +#define ZIP_ER_NOENT 9 /* N No such file */ +#define ZIP_ER_EXISTS 10 /* N File already exists */ +#define ZIP_ER_OPEN 11 /* S Can't open file */ +#define ZIP_ER_TMPOPEN 12 /* S Failure to create temporary file */ +#define ZIP_ER_ZLIB 13 /* Z Zlib error */ +#define ZIP_ER_MEMORY 14 /* N Malloc failure */ +#define ZIP_ER_CHANGED 15 /* N Entry has been changed */ +#define ZIP_ER_COMPNOTSUPP 16 /* N Compression method not supported */ +#define ZIP_ER_EOF 17 /* N Premature end of file */ +#define ZIP_ER_INVAL 18 /* N Invalid argument */ +#define ZIP_ER_NOZIP 19 /* N Not a zip archive */ +#define ZIP_ER_INTERNAL 20 /* N Internal error */ +#define ZIP_ER_INCONS 21 /* N Zip archive inconsistent */ +#define ZIP_ER_REMOVE 22 /* S Can't remove file */ +#define ZIP_ER_DELETED 23 /* N Entry has been deleted */ +#define ZIP_ER_ENCRNOTSUPP 24 /* N Encryption method not supported */ +#define ZIP_ER_RDONLY 25 /* N Read-only archive */ +#define ZIP_ER_NOPASSWD 26 /* N No password provided */ +#define ZIP_ER_WRONGPASSWD 27 /* N Wrong password provided */ +#define ZIP_ER_OPNOTSUPP 28 /* N Operation not supported */ +#define ZIP_ER_INUSE 29 /* N Resource still in use */ +#define ZIP_ER_TELL 30 /* S Tell error */ +#define ZIP_ER_COMPRESSED_DATA 31 /* N Compressed data invalid */ +#define ZIP_ER_CANCELLED 32 /* N Operation cancelled */ + +/* type of system error value */ + +#define ZIP_ET_NONE 0 /* sys_err unused */ +#define ZIP_ET_SYS 1 /* sys_err is errno */ +#define ZIP_ET_ZLIB 2 /* sys_err is zlib error code */ + +/* compression methods */ + +#define ZIP_CM_DEFAULT -1 /* better of deflate or store */ +#define ZIP_CM_STORE 0 /* stored (uncompressed) */ +#define ZIP_CM_SHRINK 1 /* shrunk */ +#define ZIP_CM_REDUCE_1 2 /* reduced with factor 1 */ +#define ZIP_CM_REDUCE_2 3 /* reduced with factor 2 */ +#define ZIP_CM_REDUCE_3 4 /* reduced with factor 3 */ +#define ZIP_CM_REDUCE_4 5 /* reduced with factor 4 */ +#define ZIP_CM_IMPLODE 6 /* imploded */ +/* 7 - Reserved for Tokenizing compression algorithm */ +#define ZIP_CM_DEFLATE 8 /* deflated */ +#define ZIP_CM_DEFLATE64 9 /* deflate64 */ +#define ZIP_CM_PKWARE_IMPLODE 10 /* PKWARE imploding */ +/* 11 - Reserved by PKWARE */ +#define ZIP_CM_BZIP2 12 /* compressed using BZIP2 algorithm */ +/* 13 - Reserved by PKWARE */ +#define ZIP_CM_LZMA 14 /* LZMA (EFS) */ +/* 15-17 - Reserved by PKWARE */ +#define ZIP_CM_TERSE 18 /* compressed using IBM TERSE (new) */ +#define ZIP_CM_LZ77 19 /* IBM LZ77 z Architecture (PFS) */ +/* 20 - old value for Zstandard */ +#define ZIP_CM_LZMA2 33 +#define ZIP_CM_ZSTD 93 /* Zstandard compressed data */ +#define ZIP_CM_XZ 95 /* XZ compressed data */ +#define ZIP_CM_JPEG 96 /* Compressed Jpeg data */ +#define ZIP_CM_WAVPACK 97 /* WavPack compressed data */ +#define ZIP_CM_PPMD 98 /* PPMd version I, Rev 1 */ + +/* encryption methods */ + +#define ZIP_EM_NONE 0 /* not encrypted */ +#define ZIP_EM_TRAD_PKWARE 1 /* traditional PKWARE encryption */ +#if 0 /* Strong Encryption Header not parsed yet */ +#define ZIP_EM_DES 0x6601 /* strong encryption: DES */ +#define ZIP_EM_RC2_OLD 0x6602 /* strong encryption: RC2, version < 5.2 */ +#define ZIP_EM_3DES_168 0x6603 +#define ZIP_EM_3DES_112 0x6609 +#define ZIP_EM_PKZIP_AES_128 0x660e +#define ZIP_EM_PKZIP_AES_192 0x660f +#define ZIP_EM_PKZIP_AES_256 0x6610 +#define ZIP_EM_RC2 0x6702 /* strong encryption: RC2, version >= 5.2 */ +#define ZIP_EM_RC4 0x6801 +#endif +#define ZIP_EM_AES_128 0x0101 /* Winzip AES encryption */ +#define ZIP_EM_AES_192 0x0102 +#define ZIP_EM_AES_256 0x0103 +#define ZIP_EM_UNKNOWN 0xffff /* unknown algorithm */ + +#define ZIP_OPSYS_DOS 0x00u +#define ZIP_OPSYS_AMIGA 0x01u +#define ZIP_OPSYS_OPENVMS 0x02u +#define ZIP_OPSYS_UNIX 0x03u +#define ZIP_OPSYS_VM_CMS 0x04u +#define ZIP_OPSYS_ATARI_ST 0x05u +#define ZIP_OPSYS_OS_2 0x06u +#define ZIP_OPSYS_MACINTOSH 0x07u +#define ZIP_OPSYS_Z_SYSTEM 0x08u +#define ZIP_OPSYS_CPM 0x09u +#define ZIP_OPSYS_WINDOWS_NTFS 0x0au +#define ZIP_OPSYS_MVS 0x0bu +#define ZIP_OPSYS_VSE 0x0cu +#define ZIP_OPSYS_ACORN_RISC 0x0du +#define ZIP_OPSYS_VFAT 0x0eu +#define ZIP_OPSYS_ALTERNATE_MVS 0x0fu +#define ZIP_OPSYS_BEOS 0x10u +#define ZIP_OPSYS_TANDEM 0x11u +#define ZIP_OPSYS_OS_400 0x12u +#define ZIP_OPSYS_OS_X 0x13u + +#define ZIP_OPSYS_DEFAULT ZIP_OPSYS_UNIX + + +enum zip_source_cmd { + ZIP_SOURCE_OPEN, /* prepare for reading */ + ZIP_SOURCE_READ, /* read data */ + ZIP_SOURCE_CLOSE, /* reading is done */ + ZIP_SOURCE_STAT, /* get meta information */ + ZIP_SOURCE_ERROR, /* get error information */ + ZIP_SOURCE_FREE, /* cleanup and free resources */ + ZIP_SOURCE_SEEK, /* set position for reading */ + ZIP_SOURCE_TELL, /* get read position */ + ZIP_SOURCE_BEGIN_WRITE, /* prepare for writing */ + ZIP_SOURCE_COMMIT_WRITE, /* writing is done */ + ZIP_SOURCE_ROLLBACK_WRITE, /* discard written changes */ + ZIP_SOURCE_WRITE, /* write data */ + ZIP_SOURCE_SEEK_WRITE, /* set position for writing */ + ZIP_SOURCE_TELL_WRITE, /* get write position */ + ZIP_SOURCE_SUPPORTS, /* check whether source supports command */ + ZIP_SOURCE_REMOVE, /* remove file */ + ZIP_SOURCE_RESERVED_1, /* previously used internally */ + ZIP_SOURCE_BEGIN_WRITE_CLONING, /* like ZIP_SOURCE_BEGIN_WRITE, but keep part of original file */ + ZIP_SOURCE_ACCEPT_EMPTY, /* whether empty files are valid archives */ + ZIP_SOURCE_GET_FILE_ATTRIBUTES /* get additional file attributes */ +}; +typedef enum zip_source_cmd zip_source_cmd_t; + +#define ZIP_SOURCE_MAKE_COMMAND_BITMASK(cmd) (((zip_int64_t)1) << (cmd)) + +/* clang-format off */ + +#define ZIP_SOURCE_SUPPORTS_READABLE (ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_OPEN) \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_READ) \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_CLOSE) \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_STAT) \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_ERROR) \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_FREE)) + +#define ZIP_SOURCE_SUPPORTS_SEEKABLE (ZIP_SOURCE_SUPPORTS_READABLE \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_SEEK) \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_TELL) \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_SUPPORTS)) + +#define ZIP_SOURCE_SUPPORTS_WRITABLE (ZIP_SOURCE_SUPPORTS_SEEKABLE \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_BEGIN_WRITE) \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_COMMIT_WRITE) \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_ROLLBACK_WRITE) \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_WRITE) \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_SEEK_WRITE) \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_TELL_WRITE) \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_REMOVE)) + +/* clang-format on */ + +/* for use by sources */ +struct zip_source_args_seek { + zip_int64_t offset; + int whence; +}; + +typedef struct zip_source_args_seek zip_source_args_seek_t; +#define ZIP_SOURCE_GET_ARGS(type, data, len, error) ((len) < sizeof(type) ? zip_error_set((error), ZIP_ER_INVAL, 0), (type *)NULL : (type *)(data)) + + +/* error information */ +/* use zip_error_*() to access */ +struct zip_error { + int zip_err; /* libzip error code (ZIP_ER_*) */ + int sys_err; /* copy of errno (E*) or zlib error code */ + char *_Nullable str; /* string representation or NULL */ +}; + +#define ZIP_STAT_NAME 0x0001u +#define ZIP_STAT_INDEX 0x0002u +#define ZIP_STAT_SIZE 0x0004u +#define ZIP_STAT_COMP_SIZE 0x0008u +#define ZIP_STAT_MTIME 0x0010u +#define ZIP_STAT_CRC 0x0020u +#define ZIP_STAT_COMP_METHOD 0x0040u +#define ZIP_STAT_ENCRYPTION_METHOD 0x0080u +#define ZIP_STAT_FLAGS 0x0100u + +struct zip_stat { + zip_uint64_t valid; /* which fields have valid values */ + const char *_Nullable name; /* name of the file */ + zip_uint64_t index; /* index within archive */ + zip_uint64_t size; /* size of file (uncompressed) */ + zip_uint64_t comp_size; /* size of file (compressed) */ + time_t mtime; /* modification time */ + zip_uint32_t crc; /* crc of file data */ + zip_uint16_t comp_method; /* compression method used */ + zip_uint16_t encryption_method; /* encryption method used */ + zip_uint32_t flags; /* reserved for future use */ +}; + +struct zip_buffer_fragment { + zip_uint8_t *_Nonnull data; + zip_uint64_t length; +}; + +struct zip_file_attributes { + zip_uint64_t valid; /* which fields have valid values */ + zip_uint8_t version; /* version of this struct, currently 1 */ + zip_uint8_t host_system; /* host system on which file was created */ + zip_uint8_t ascii; /* flag whether file is ASCII text */ + zip_uint8_t version_needed; /* minimum version needed to extract file */ + zip_uint32_t external_file_attributes; /* external file attributes (host-system specific) */ + zip_uint16_t general_purpose_bit_flags; /* general purpose big flags, only some bits are honored */ + zip_uint16_t general_purpose_bit_mask; /* which bits in general_purpose_bit_flags are valid */ +}; + +#define ZIP_FILE_ATTRIBUTES_HOST_SYSTEM 0x0001u +#define ZIP_FILE_ATTRIBUTES_ASCII 0x0002u +#define ZIP_FILE_ATTRIBUTES_VERSION_NEEDED 0x0004u +#define ZIP_FILE_ATTRIBUTES_EXTERNAL_FILE_ATTRIBUTES 0x0008u +#define ZIP_FILE_ATTRIBUTES_GENERAL_PURPOSE_BIT_FLAGS 0x0010u + +struct zip; +struct zip_file; +struct zip_source; + +typedef struct zip zip_t; +typedef struct zip_error zip_error_t; +typedef struct zip_file zip_file_t; +typedef struct zip_file_attributes zip_file_attributes_t; +typedef struct zip_source zip_source_t; +typedef struct zip_stat zip_stat_t; +typedef struct zip_buffer_fragment zip_buffer_fragment_t; + +typedef zip_uint32_t zip_flags_t; + +typedef zip_int64_t (*zip_source_callback)(void *_Nullable, void *_Nullable, zip_uint64_t, zip_source_cmd_t); +typedef void (*zip_progress_callback)(zip_t *_Nonnull, double, void *_Nullable); +typedef int (*zip_cancel_callback)(zip_t *_Nonnull, void *_Nullable); + +#ifndef ZIP_DISABLE_DEPRECATED +typedef void (*zip_progress_callback_t)(double); +ZIP_EXTERN void zip_register_progress_callback(zip_t *_Nonnull, zip_progress_callback_t _Nullable); /* use zip_register_progress_callback_with_state */ + +ZIP_EXTERN zip_int64_t zip_add(zip_t *_Nonnull, const char *_Nonnull, zip_source_t *_Nonnull); /* use zip_file_add */ +ZIP_EXTERN zip_int64_t zip_add_dir(zip_t *_Nonnull, const char *_Nonnull); /* use zip_dir_add */ +ZIP_EXTERN const char *_Nullable zip_get_file_comment(zip_t *_Nonnull, zip_uint64_t, int *_Nullable, int); /* use zip_file_get_comment */ +ZIP_EXTERN int zip_get_num_files(zip_t *_Nonnull); /* use zip_get_num_entries instead */ +ZIP_EXTERN int zip_rename(zip_t *_Nonnull, zip_uint64_t, const char *_Nonnull); /* use zip_file_rename */ +ZIP_EXTERN int zip_replace(zip_t *_Nonnull, zip_uint64_t, zip_source_t *_Nonnull); /* use zip_file_replace */ +ZIP_EXTERN int zip_set_file_comment(zip_t *_Nonnull, zip_uint64_t, const char *_Nullable, int); /* use zip_file_set_comment */ +ZIP_EXTERN int zip_error_get_sys_type(int); /* use zip_error_system_type */ +ZIP_EXTERN void zip_error_get(zip_t *_Nonnull, int *_Nullable, int *_Nullable); /* use zip_get_error, zip_error_code_zip / zip_error_code_system */ +ZIP_EXTERN int zip_error_to_str(char *_Nonnull, zip_uint64_t, int, int); /* use zip_error_init_with_code / zip_error_strerror */ +ZIP_EXTERN void zip_file_error_get(zip_file_t *_Nonnull, int *_Nullable, int *_Nullable); /* use zip_file_get_error, zip_error_code_zip / zip_error_code_system */ +#endif + +ZIP_EXTERN int zip_close(zip_t *_Nonnull); +ZIP_EXTERN int zip_delete(zip_t *_Nonnull, zip_uint64_t); +ZIP_EXTERN zip_int64_t zip_dir_add(zip_t *_Nonnull, const char *_Nonnull, zip_flags_t); +ZIP_EXTERN void zip_discard(zip_t *_Nonnull); + +ZIP_EXTERN zip_error_t *_Nonnull zip_get_error(zip_t *_Nonnull); +ZIP_EXTERN void zip_error_clear(zip_t *_Nonnull); +ZIP_EXTERN int zip_error_code_zip(const zip_error_t *_Nonnull); +ZIP_EXTERN int zip_error_code_system(const zip_error_t *_Nonnull); +ZIP_EXTERN void zip_error_fini(zip_error_t *_Nonnull); +ZIP_EXTERN void zip_error_init(zip_error_t *_Nonnull); +ZIP_EXTERN void zip_error_init_with_code(zip_error_t *_Nonnull, int); +ZIP_EXTERN void zip_error_set(zip_error_t *_Nullable, int, int); +ZIP_EXTERN const char *_Nonnull zip_error_strerror(zip_error_t *_Nonnull); +ZIP_EXTERN int zip_error_system_type(const zip_error_t *_Nonnull); +ZIP_EXTERN zip_int64_t zip_error_to_data(const zip_error_t *_Nonnull, void *_Nonnull, zip_uint64_t); + +ZIP_EXTERN int zip_fclose(zip_file_t *_Nonnull); +ZIP_EXTERN zip_t *_Nullable zip_fdopen(int, int, int *_Nullable); +ZIP_EXTERN zip_int64_t zip_file_add(zip_t *_Nonnull, const char *_Nonnull, zip_source_t *_Nonnull, zip_flags_t); +ZIP_EXTERN void zip_file_attributes_init(zip_file_attributes_t *_Nonnull); +ZIP_EXTERN void zip_file_error_clear(zip_file_t *_Nonnull); +ZIP_EXTERN int zip_file_extra_field_delete(zip_t *_Nonnull, zip_uint64_t, zip_uint16_t, zip_flags_t); +ZIP_EXTERN int zip_file_extra_field_delete_by_id(zip_t *_Nonnull, zip_uint64_t, zip_uint16_t, zip_uint16_t, zip_flags_t); +ZIP_EXTERN int zip_file_extra_field_set(zip_t *_Nonnull, zip_uint64_t, zip_uint16_t, zip_uint16_t, const zip_uint8_t *_Nullable, zip_uint16_t, zip_flags_t); +ZIP_EXTERN zip_int16_t zip_file_extra_fields_count(zip_t *_Nonnull, zip_uint64_t, zip_flags_t); +ZIP_EXTERN zip_int16_t zip_file_extra_fields_count_by_id(zip_t *_Nonnull, zip_uint64_t, zip_uint16_t, zip_flags_t); +ZIP_EXTERN const zip_uint8_t *_Nullable zip_file_extra_field_get(zip_t *_Nonnull, zip_uint64_t, zip_uint16_t, zip_uint16_t *_Nullable, zip_uint16_t *_Nullable, zip_flags_t); +ZIP_EXTERN const zip_uint8_t *_Nullable zip_file_extra_field_get_by_id(zip_t *_Nonnull, zip_uint64_t, zip_uint16_t, zip_uint16_t, zip_uint16_t *_Nullable, zip_flags_t); +ZIP_EXTERN const char *_Nullable zip_file_get_comment(zip_t *_Nonnull, zip_uint64_t, zip_uint32_t *_Nullable, zip_flags_t); +ZIP_EXTERN zip_error_t *_Nonnull zip_file_get_error(zip_file_t *_Nonnull); +ZIP_EXTERN int zip_file_get_external_attributes(zip_t *_Nonnull, zip_uint64_t, zip_flags_t, zip_uint8_t *_Nullable, zip_uint32_t *_Nullable); +ZIP_EXTERN int zip_file_rename(zip_t *_Nonnull, zip_uint64_t, const char *_Nonnull, zip_flags_t); +ZIP_EXTERN int zip_file_replace(zip_t *_Nonnull, zip_uint64_t, zip_source_t *_Nonnull, zip_flags_t); +ZIP_EXTERN int zip_file_set_comment(zip_t *_Nonnull, zip_uint64_t, const char *_Nullable, zip_uint16_t, zip_flags_t); +ZIP_EXTERN int zip_file_set_dostime(zip_t *_Nonnull, zip_uint64_t, zip_uint16_t, zip_uint16_t, zip_flags_t); +ZIP_EXTERN int zip_file_set_encryption(zip_t *_Nonnull, zip_uint64_t, zip_uint16_t, const char *_Nullable); +ZIP_EXTERN int zip_file_set_external_attributes(zip_t *_Nonnull, zip_uint64_t, zip_flags_t, zip_uint8_t, zip_uint32_t); +ZIP_EXTERN int zip_file_set_mtime(zip_t *_Nonnull, zip_uint64_t, time_t, zip_flags_t); +ZIP_EXTERN const char *_Nonnull zip_file_strerror(zip_file_t *_Nonnull); +ZIP_EXTERN zip_file_t *_Nullable zip_fopen(zip_t *_Nonnull, const char *_Nonnull, zip_flags_t); +ZIP_EXTERN zip_file_t *_Nullable zip_fopen_encrypted(zip_t *_Nonnull, const char *_Nonnull, zip_flags_t, const char *_Nullable); +ZIP_EXTERN zip_file_t *_Nullable zip_fopen_index(zip_t *_Nonnull, zip_uint64_t, zip_flags_t); +ZIP_EXTERN zip_file_t *_Nullable zip_fopen_index_encrypted(zip_t *_Nonnull, zip_uint64_t, zip_flags_t, const char *_Nullable); +ZIP_EXTERN zip_int64_t zip_fread(zip_file_t *_Nonnull, void *_Nonnull, zip_uint64_t); +ZIP_EXTERN zip_int8_t zip_fseek(zip_file_t *_Nonnull, zip_int64_t, int); +ZIP_EXTERN zip_int64_t zip_ftell(zip_file_t *_Nonnull); +ZIP_EXTERN const char *_Nullable zip_get_archive_comment(zip_t *_Nonnull, int *_Nullable, zip_flags_t); +ZIP_EXTERN int zip_get_archive_flag(zip_t *_Nonnull, zip_flags_t, zip_flags_t); +ZIP_EXTERN const char *_Nullable zip_get_name(zip_t *_Nonnull, zip_uint64_t, zip_flags_t); +ZIP_EXTERN zip_int64_t zip_get_num_entries(zip_t *_Nonnull, zip_flags_t); +ZIP_EXTERN const char *_Nonnull zip_libzip_version(void); +ZIP_EXTERN zip_int64_t zip_name_locate(zip_t *_Nonnull, const char *_Nonnull, zip_flags_t); +ZIP_EXTERN zip_t *_Nullable zip_open(const char *_Nonnull, int, int *_Nullable); +ZIP_EXTERN zip_t *_Nullable zip_open_from_source(zip_source_t *_Nonnull, int, zip_error_t *_Nullable); +ZIP_EXTERN int zip_register_progress_callback_with_state(zip_t *_Nonnull, double, zip_progress_callback _Nullable, void (*_Nullable)(void *_Nullable), void *_Nullable); +ZIP_EXTERN int zip_register_cancel_callback_with_state(zip_t *_Nonnull, zip_cancel_callback _Nullable, void (*_Nullable)(void *_Nullable), void *_Nullable); +ZIP_EXTERN int zip_set_archive_comment(zip_t *_Nonnull, const char *_Nullable, zip_uint16_t); +ZIP_EXTERN int zip_set_archive_flag(zip_t *_Nonnull, zip_flags_t, int); +ZIP_EXTERN int zip_set_default_password(zip_t *_Nonnull, const char *_Nullable); +ZIP_EXTERN int zip_set_file_compression(zip_t *_Nonnull, zip_uint64_t, zip_int32_t, zip_uint32_t); +ZIP_EXTERN int zip_source_begin_write(zip_source_t *_Nonnull); +ZIP_EXTERN int zip_source_begin_write_cloning(zip_source_t *_Nonnull, zip_uint64_t); +ZIP_EXTERN zip_source_t *_Nullable zip_source_buffer(zip_t *_Nonnull, const void *_Nullable, zip_uint64_t, int); +ZIP_EXTERN zip_source_t *_Nullable zip_source_buffer_create(const void *_Nullable, zip_uint64_t, int, zip_error_t *_Nullable); +ZIP_EXTERN zip_source_t *_Nullable zip_source_buffer_fragment(zip_t *_Nonnull, const zip_buffer_fragment_t *_Nonnull, zip_uint64_t, int); +ZIP_EXTERN zip_source_t *_Nullable zip_source_buffer_fragment_create(const zip_buffer_fragment_t *_Nullable, zip_uint64_t, int, zip_error_t *_Nullable); +ZIP_EXTERN int zip_source_close(zip_source_t *_Nonnull); +ZIP_EXTERN int zip_source_commit_write(zip_source_t *_Nonnull); +ZIP_EXTERN zip_error_t *_Nonnull zip_source_error(zip_source_t *_Nonnull); +ZIP_EXTERN zip_source_t *_Nullable zip_source_file(zip_t *_Nonnull, const char *_Nonnull, zip_uint64_t, zip_int64_t); +ZIP_EXTERN zip_source_t *_Nullable zip_source_file_create(const char *_Nonnull, zip_uint64_t, zip_int64_t, zip_error_t *_Nullable); +ZIP_EXTERN zip_source_t *_Nullable zip_source_filep(zip_t *_Nonnull, FILE *_Nonnull, zip_uint64_t, zip_int64_t); +ZIP_EXTERN zip_source_t *_Nullable zip_source_filep_create(FILE *_Nonnull, zip_uint64_t, zip_int64_t, zip_error_t *_Nullable); +ZIP_EXTERN void zip_source_free(zip_source_t *_Nullable); +ZIP_EXTERN zip_source_t *_Nullable zip_source_function(zip_t *_Nonnull, zip_source_callback _Nonnull, void *_Nullable); +ZIP_EXTERN zip_source_t *_Nullable zip_source_function_create(zip_source_callback _Nonnull, void *_Nullable, zip_error_t *_Nullable); +ZIP_EXTERN int zip_source_get_file_attributes(zip_source_t *_Nonnull, zip_file_attributes_t *_Nonnull); +ZIP_EXTERN int zip_source_is_deleted(zip_source_t *_Nonnull); +ZIP_EXTERN void zip_source_keep(zip_source_t *_Nonnull); +ZIP_EXTERN zip_int64_t zip_source_make_command_bitmap(zip_source_cmd_t, ...); +ZIP_EXTERN int zip_source_open(zip_source_t *_Nonnull); +ZIP_EXTERN zip_int64_t zip_source_read(zip_source_t *_Nonnull, void *_Nonnull, zip_uint64_t); +ZIP_EXTERN void zip_source_rollback_write(zip_source_t *_Nonnull); +ZIP_EXTERN int zip_source_seek(zip_source_t *_Nonnull, zip_int64_t, int); +ZIP_EXTERN zip_int64_t zip_source_seek_compute_offset(zip_uint64_t, zip_uint64_t, void *_Nonnull, zip_uint64_t, zip_error_t *_Nullable); +ZIP_EXTERN int zip_source_seek_write(zip_source_t *_Nonnull, zip_int64_t, int); +ZIP_EXTERN int zip_source_stat(zip_source_t *_Nonnull, zip_stat_t *_Nonnull); +ZIP_EXTERN zip_int64_t zip_source_tell(zip_source_t *_Nonnull); +ZIP_EXTERN zip_int64_t zip_source_tell_write(zip_source_t *_Nonnull); +#ifdef _WIN32 +ZIP_EXTERN zip_source_t *zip_source_win32a(zip_t *, const char *, zip_uint64_t, zip_int64_t); +ZIP_EXTERN zip_source_t *zip_source_win32a_create(const char *, zip_uint64_t, zip_int64_t, zip_error_t *); +ZIP_EXTERN zip_source_t *zip_source_win32handle(zip_t *, void *, zip_uint64_t, zip_int64_t); +ZIP_EXTERN zip_source_t *zip_source_win32handle_create(void *, zip_uint64_t, zip_int64_t, zip_error_t *); +ZIP_EXTERN zip_source_t *zip_source_win32w(zip_t *, const wchar_t *, zip_uint64_t, zip_int64_t); +ZIP_EXTERN zip_source_t *zip_source_win32w_create(const wchar_t *, zip_uint64_t, zip_int64_t, zip_error_t *); +#endif +ZIP_EXTERN zip_int64_t zip_source_write(zip_source_t *_Nonnull, const void *_Nullable, zip_uint64_t); +ZIP_EXTERN zip_source_t *_Nullable zip_source_zip(zip_t *_Nonnull, zip_t *_Nonnull, zip_uint64_t, zip_flags_t, zip_uint64_t, zip_int64_t); +ZIP_EXTERN int zip_stat(zip_t *_Nonnull, const char *_Nonnull, zip_flags_t, zip_stat_t *_Nonnull); +ZIP_EXTERN int zip_stat_index(zip_t *_Nonnull, zip_uint64_t, zip_flags_t, zip_stat_t *_Nonnull); +ZIP_EXTERN void zip_stat_init(zip_stat_t *_Nonnull); +ZIP_EXTERN const char *_Nonnull zip_strerror(zip_t *_Nonnull); +ZIP_EXTERN int zip_unchange(zip_t *_Nonnull, zip_uint64_t); +ZIP_EXTERN int zip_unchange_all(zip_t *_Nonnull); +ZIP_EXTERN int zip_unchange_archive(zip_t *_Nonnull); +ZIP_EXTERN int zip_compression_method_supported(zip_int32_t method, int compress); +ZIP_EXTERN int zip_encryption_method_supported(zip_uint16_t method, int encode); + +#ifdef __cplusplus +} +#endif + +#endif /* _HAD_ZIP_H */ diff --git a/Include/Libraries/libzip/zip_source_file.h b/Include/Libraries/libzip/zip_source_file.h new file mode 100644 index 0000000..43a4645 --- /dev/null +++ b/Include/Libraries/libzip/zip_source_file.h @@ -0,0 +1,90 @@ +/* + zip_source_file.h -- header for common file operations + Copyright (C) 2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + +struct zip_source_file_stat { + zip_uint64_t size; /* must be valid for regular files */ + time_t mtime; /* must always be valid, is initialized to current time */ + bool exists; /* must always be vaild */ + bool regular_file; /* must always be valid */ +}; + +typedef struct zip_source_file_context zip_source_file_context_t; +typedef struct zip_source_file_operations zip_source_file_operations_t; +typedef struct zip_source_file_stat zip_source_file_stat_t; + +struct zip_source_file_context { + zip_error_t error; /* last error information */ + zip_int64_t supports; + + /* reading */ + char *fname; /* name of file to read from */ + void *f; /* file to read from */ + zip_stat_t st; /* stat information passed in */ + zip_file_attributes_t attributes; /* additional file attributes */ + zip_error_t stat_error; /* error returned for stat */ + zip_uint64_t start; /* start offset of data to read */ + zip_uint64_t len; /* length of the file, 0 for up to EOF */ + zip_uint64_t offset; /* current offset relative to start (0 is beginning of part we read) */ + + /* writing */ + char *tmpname; + void *fout; + + zip_source_file_operations_t *ops; + void *ops_userdata; +}; + + +/* The following methods must be implemented to support each feature: + - close, read, seek, and stat must always be implemented. + - To support specifying the file by name, open, and strdup must be implemented. + - For write support, the file must be specified by name and close, commit_write, create_temp_output, remove, rollback_write, and tell must be implemented. + - create_temp_output_cloning is always optional. */ + +struct zip_source_file_operations { + void (*close)(zip_source_file_context_t *ctx); + zip_int64_t (*commit_write)(zip_source_file_context_t *ctx); + zip_int64_t (*create_temp_output)(zip_source_file_context_t *ctx); + zip_int64_t (*create_temp_output_cloning)(zip_source_file_context_t *ctx, zip_uint64_t len); + bool (*open)(zip_source_file_context_t *ctx); + zip_int64_t (*read)(zip_source_file_context_t *ctx, void *buf, zip_uint64_t len); + zip_int64_t (*remove)(zip_source_file_context_t *ctx); + void (*rollback_write)(zip_source_file_context_t *ctx); + bool (*seek)(zip_source_file_context_t *ctx, void *f, zip_int64_t offset, int whence); + bool (*stat)(zip_source_file_context_t *ctx, zip_source_file_stat_t *st); + char *(*string_duplicate)(zip_source_file_context_t *ctx, const char *); + zip_int64_t (*tell)(zip_source_file_context_t *ctx, void *f); + zip_int64_t (*write)(zip_source_file_context_t *ctx, const void *data, zip_uint64_t len); +}; + +zip_source_t *zip_source_file_common_new(const char *fname, void *file, zip_uint64_t start, zip_int64_t len, const zip_stat_t *st, zip_source_file_operations_t *ops, void *ops_userdata, zip_error_t *error); diff --git a/Include/Libraries/libzip/zip_source_file_stdio.h b/Include/Libraries/libzip/zip_source_file_stdio.h new file mode 100644 index 0000000..1bf698c --- /dev/null +++ b/Include/Libraries/libzip/zip_source_file_stdio.h @@ -0,0 +1,47 @@ +#ifndef _HAD_ZIP_SOURCE_FILE_STDIO_H +#define _HAD_ZIP_SOURCE_FILE_STDIO_H + +/* + zip_source_file_stdio.h -- common header for stdio file implementation + Copyright (C) 2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +void _zip_stdio_op_close(zip_source_file_context_t *ctx); +zip_int64_t _zip_stdio_op_read(zip_source_file_context_t *ctx, void *buf, zip_uint64_t len); +bool _zip_stdio_op_seek(zip_source_file_context_t *ctx, void *f, zip_int64_t offset, int whence); +bool _zip_stdio_op_stat(zip_source_file_context_t *ctx, zip_source_file_stat_t *st); +zip_int64_t _zip_stdio_op_tell(zip_source_file_context_t *ctx, void *f); + +FILE *_zip_fopen_close_on_exec(const char *name, bool writeable); + +#endif /* _HAD_ZIP_SOURCE_FILE_STDIO_H */ diff --git a/Include/Libraries/libzip/zip_source_file_win32.h b/Include/Libraries/libzip/zip_source_file_win32.h new file mode 100644 index 0000000..88e45b1 --- /dev/null +++ b/Include/Libraries/libzip/zip_source_file_win32.h @@ -0,0 +1,76 @@ +#ifndef _HAD_ZIP_SOURCE_FILE_WIN32_H +#define _HAD_ZIP_SOURCE_FILE_WIN32_H + +/* + zip_source_file_win32.h -- common header for Windows file implementation + Copyright (C) 2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + +/* 0x0501 => Windows XP; needs to be at least this value because of GetFileSizeEx */ +#if !defined(MS_UWP) && !defined(_WIN32_WINNT) +#define _WIN32_WINNT 0x0501 +#endif + +#include + +#include + +#include + +#include "zipint.h" + +#include "zip_source_file.h" + +struct zip_win32_file_operations { + char *(*allocate_tempname)(const char *name, size_t extra_chars, size_t *lengthp); + HANDLE(__stdcall *create_file)(const void *name, DWORD access, DWORD share_mode, PSECURITY_ATTRIBUTES security_attributes, DWORD creation_disposition, DWORD file_attributes, HANDLE template_file); + BOOL(__stdcall *delete_file)(const void *name); + DWORD(__stdcall *get_file_attributes)(const void *name); + BOOL(__stdcall *get_file_attributes_ex)(const void *name, GET_FILEEX_INFO_LEVELS info_level, void *information); + void (*make_tempname)(char *buf, size_t len, const char *name, zip_uint32_t i); + BOOL(__stdcall *move_file)(const void *from, const void *to, DWORD flags); + BOOL(__stdcall *set_file_attributes)(const void *name, DWORD attributes); + char *(*string_duplicate)(const char *string); +}; + +typedef struct zip_win32_file_operations zip_win32_file_operations_t; + +extern zip_source_file_operations_t _zip_source_file_win32_named_ops; + +void _zip_win32_op_close(zip_source_file_context_t *ctx); +zip_int64_t _zip_win32_op_read(zip_source_file_context_t *ctx, void *buf, zip_uint64_t len); +bool _zip_win32_op_seek(zip_source_file_context_t *ctx, void *f, zip_int64_t offset, int whence); +zip_int64_t _zip_win32_op_tell(zip_source_file_context_t *ctx, void *f); + +bool _zip_filetime_to_time_t(FILETIME ft, time_t *t); +int _zip_win32_error_to_errno(DWORD win32err); + +#endif /* _HAD_ZIP_SOURCE_FILE_WIN32_H */ diff --git a/Include/Libraries/libzip/zipconf.h b/Include/Libraries/libzip/zipconf.h new file mode 100644 index 0000000..f6e9ed0 --- /dev/null +++ b/Include/Libraries/libzip/zipconf.h @@ -0,0 +1,51 @@ +#ifndef _HAD_ZIPCONF_H +#define _HAD_ZIPCONF_H + +/* + zipconf.h -- platform specific include file + + This file was generated automatically by CMake + based on ../cmake-zipconf.h.in. + */ + +#define LIBZIP_VERSION "1.7.3.1" +#define LIBZIP_VERSION_MAJOR 1 +#define LIBZIP_VERSION_MINOR 7 +#define LIBZIP_VERSION_MICRO 3 + +/* #undef ZIP_STATIC */ + +#define _Nullable +#define _Nonnull + +#if !defined(__STDC_FORMAT_MACROS) +#define __STDC_FORMAT_MACROS 1 +#endif +#include + +typedef int8_t zip_int8_t; +typedef uint8_t zip_uint8_t; +typedef int16_t zip_int16_t; +typedef uint16_t zip_uint16_t; +typedef int32_t zip_int32_t; +typedef uint32_t zip_uint32_t; +typedef int64_t zip_int64_t; +typedef uint64_t zip_uint64_t; + +#define ZIP_INT8_MIN (-ZIP_INT8_MAX-1) +#define ZIP_INT8_MAX 0x7f +#define ZIP_UINT8_MAX 0xff + +#define ZIP_INT16_MIN (-ZIP_INT16_MAX-1) +#define ZIP_INT16_MAX 0x7fff +#define ZIP_UINT16_MAX 0xffff + +#define ZIP_INT32_MIN (-ZIP_INT32_MAX-1L) +#define ZIP_INT32_MAX 0x7fffffffL +#define ZIP_UINT32_MAX 0xffffffffLU + +#define ZIP_INT64_MIN (-ZIP_INT64_MAX-1LL) +#define ZIP_INT64_MAX 0x7fffffffffffffffLL +#define ZIP_UINT64_MAX 0xffffffffffffffffULL + +#endif /* zipconf.h */ diff --git a/Include/Libraries/libzip/zipint.h b/Include/Libraries/libzip/zipint.h new file mode 100644 index 0000000..65e602c --- /dev/null +++ b/Include/Libraries/libzip/zipint.h @@ -0,0 +1,609 @@ +#ifndef _HAD_ZIPINT_H +#define _HAD_ZIPINT_H + +/* + zipint.h -- internal declarations. + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "config.h" + +#include "compat.h" + +#ifdef ZIP_ALLOCATE_BUFFER +#include +#endif + +#ifndef _ZIP_COMPILING_DEPRECATED +#define ZIP_DISABLE_DEPRECATED +#endif + +#include "zip.h" + +#define CENTRAL_MAGIC "PK\1\2" +#define LOCAL_MAGIC "PK\3\4" +#define EOCD_MAGIC "PK\5\6" +#define DATADES_MAGIC "PK\7\10" +#define EOCD64LOC_MAGIC "PK\6\7" +#define EOCD64_MAGIC "PK\6\6" +#define CDENTRYSIZE 46u +#define LENTRYSIZE 30 +#define MAXCOMLEN 65536 +#define MAXEXTLEN 65536 +#define EOCDLEN 22 +#define EOCD64LOCLEN 20 +#define EOCD64LEN 56 +#define CDBUFSIZE (MAXCOMLEN + EOCDLEN + EOCD64LOCLEN) +#define BUFSIZE 8192 +#define EFZIP64SIZE 28 +#define EF_WINZIP_AES_SIZE 7 +#define MAX_DATA_DESCRIPTOR_LENGTH 24 + +#define ZIP_CRYPTO_PKWARE_HEADERLEN 12 + +#define ZIP_CM_REPLACED_DEFAULT (-2) +#define ZIP_CM_WINZIP_AES 99 /* Winzip AES encrypted */ + +#define WINZIP_AES_PASSWORD_VERIFY_LENGTH 2 +#define WINZIP_AES_MAX_HEADER_LENGTH (16 + WINZIP_AES_PASSWORD_VERIFY_LENGTH) +#define AES_BLOCK_SIZE 16 +#define HMAC_LENGTH 10 +#define SHA1_LENGTH 20 +#define SALT_LENGTH(method) ((method) == ZIP_EM_AES_128 ? 8 : ((method) == ZIP_EM_AES_192 ? 12 : 16)) + +#define ZIP_CM_IS_DEFAULT(x) ((x) == ZIP_CM_DEFAULT || (x) == ZIP_CM_REPLACED_DEFAULT) +#define ZIP_CM_ACTUAL(x) ((zip_uint16_t)(ZIP_CM_IS_DEFAULT(x) ? ZIP_CM_DEFLATE : (x))) + +#define ZIP_EF_UTF_8_COMMENT 0x6375 +#define ZIP_EF_UTF_8_NAME 0x7075 +#define ZIP_EF_WINZIP_AES 0x9901 +#define ZIP_EF_ZIP64 0x0001 + +#define ZIP_EF_IS_INTERNAL(id) ((id) == ZIP_EF_UTF_8_COMMENT || (id) == ZIP_EF_UTF_8_NAME || (id) == ZIP_EF_WINZIP_AES || (id) == ZIP_EF_ZIP64) + +/* according to unzip-6.0's zipinfo.c, this corresponds to a regular file with rw permissions for everyone */ +#define ZIP_EXT_ATTRIB_DEFAULT (0100666u << 16) +/* according to unzip-6.0's zipinfo.c, this corresponds to a directory with rwx permissions for everyone */ +#define ZIP_EXT_ATTRIB_DEFAULT_DIR (0040777u << 16) + +#define ZIP_FILE_ATTRIBUTES_GENERAL_PURPOSE_BIT_FLAGS_ALLOWED_MASK 0x0836 + +#define ZIP_MAX(a, b) ((a) > (b) ? (a) : (b)) +#define ZIP_MIN(a, b) ((a) < (b) ? (a) : (b)) + +/* This section contains API that won't materialize like this. It's + placed in the internal section, pending cleanup. */ + +/* flags for compression and encryption sources */ + +#define ZIP_CODEC_DECODE 0 /* decompress/decrypt (encode flag not set) */ +#define ZIP_CODEC_ENCODE 1 /* compress/encrypt */ + +typedef zip_source_t *(*zip_encryption_implementation)(zip_t *, zip_source_t *, zip_uint16_t, int, const char *); + +zip_encryption_implementation _zip_get_encryption_implementation(zip_uint16_t method, int operation); + +/* clang-format off */ +enum zip_compression_status { + ZIP_COMPRESSION_OK, + ZIP_COMPRESSION_END, + ZIP_COMPRESSION_ERROR, + ZIP_COMPRESSION_NEED_DATA +}; +/* clang-format on */ +typedef enum zip_compression_status zip_compression_status_t; + +struct zip_compression_algorithm { + /* Return maxiumum compressed size for uncompressed data of given size. */ + zip_uint64_t (*maximum_compressed_size)(zip_uint64_t uncompressed_size); + + /* called once to create new context */ + void *(*allocate)(zip_uint16_t method, int compression_flags, zip_error_t *error); + /* called once to free context */ + void (*deallocate)(void *ctx); + + /* get compression specific general purpose bitflags */ + zip_uint16_t (*general_purpose_bit_flags)(void *ctx); + /* minimum version needed when using this algorithm */ + zip_uint8_t version_needed; + + /* start processing */ + bool (*start)(void *ctx, zip_stat_t *st, zip_file_attributes_t *attributes); + /* stop processing */ + bool (*end)(void *ctx); + + /* provide new input data, remains valid until next call to input or end */ + bool (*input)(void *ctx, zip_uint8_t *data, zip_uint64_t length); + + /* all input data has been provided */ + void (*end_of_input)(void *ctx); + + /* process input data, writing to data, which has room for length bytes, update length to number of bytes written */ + zip_compression_status_t (*process)(void *ctx, zip_uint8_t *data, zip_uint64_t *length); +}; +typedef struct zip_compression_algorithm zip_compression_algorithm_t; + +extern zip_compression_algorithm_t zip_algorithm_bzip2_compress; +extern zip_compression_algorithm_t zip_algorithm_bzip2_decompress; +extern zip_compression_algorithm_t zip_algorithm_deflate_compress; +extern zip_compression_algorithm_t zip_algorithm_deflate_decompress; +extern zip_compression_algorithm_t zip_algorithm_xz_compress; +extern zip_compression_algorithm_t zip_algorithm_xz_decompress; +extern zip_compression_algorithm_t zip_algorithm_zstd_compress; +extern zip_compression_algorithm_t zip_algorithm_zstd_decompress; + +zip_compression_algorithm_t *_zip_get_compression_algorithm(zip_int32_t method, bool compress); + +/* This API is not final yet, but we need it internally, so it's private for now. */ + +const zip_uint8_t *zip_get_extra_field_by_id(zip_t *, int, int, zip_uint16_t, int, zip_uint16_t *); + +/* This section contains API that is of limited use until support for + user-supplied compression/encryption implementation is finished. + Thus we will keep it private for now. */ + +typedef zip_int64_t (*zip_source_layered_callback)(zip_source_t *, void *, void *, zip_uint64_t, enum zip_source_cmd); +zip_source_t *zip_source_compress(zip_t *za, zip_source_t *src, zip_int32_t cm, int compression_flags); +zip_source_t *zip_source_crc(zip_t *, zip_source_t *, int); +zip_source_t *zip_source_decompress(zip_t *za, zip_source_t *src, zip_int32_t cm); +zip_source_t *zip_source_layered(zip_t *, zip_source_t *, zip_source_layered_callback, void *); +zip_source_t *zip_source_layered_create(zip_source_t *src, zip_source_layered_callback cb, void *ud, zip_error_t *error); +zip_source_t *zip_source_pkware_decode(zip_t *, zip_source_t *, zip_uint16_t, int, const char *); +zip_source_t *zip_source_pkware_encode(zip_t *, zip_source_t *, zip_uint16_t, int, const char *); +int zip_source_remove(zip_source_t *); +zip_int64_t zip_source_supports(zip_source_t *src); +zip_source_t *zip_source_window(zip_t *, zip_source_t *, zip_uint64_t, zip_uint64_t); +// zip_source_t *zip_source_winzip_aes_decode(zip_t *, zip_source_t *, zip_uint16_t, int, const char *); +// zip_source_t *zip_source_winzip_aes_encode(zip_t *, zip_source_t *, zip_uint16_t, int, const char *); +zip_source_t *zip_source_buffer_with_attributes(zip_t *za, const void *data, zip_uint64_t len, int freep, zip_file_attributes_t *attributes); + +/* error source for layered sources */ + +enum zip_les { ZIP_LES_NONE, ZIP_LES_UPPER, ZIP_LES_LOWER, ZIP_LES_INVAL }; + +/* directory entry: general purpose bit flags */ + +#define ZIP_GPBF_ENCRYPTED 0x0001u /* is encrypted */ +#define ZIP_GPBF_DATA_DESCRIPTOR 0x0008u /* crc/size after file data */ +#define ZIP_GPBF_STRONG_ENCRYPTION 0x0040u /* uses strong encryption */ +#define ZIP_GPBF_ENCODING_UTF_8 0x0800u /* file name encoding is UTF-8 */ + + +/* extra fields */ +#define ZIP_EF_LOCAL ZIP_FL_LOCAL /* include in local header */ +#define ZIP_EF_CENTRAL ZIP_FL_CENTRAL /* include in central directory */ +#define ZIP_EF_BOTH (ZIP_EF_LOCAL | ZIP_EF_CENTRAL) /* include in both */ + +#define ZIP_FL_FORCE_ZIP64 1024 /* force zip64 extra field (_zip_dirent_write) */ + +#define ZIP_FL_ENCODING_ALL (ZIP_FL_ENC_GUESS | ZIP_FL_ENC_CP437 | ZIP_FL_ENC_UTF_8) + + +/* encoding type */ +enum zip_encoding_type { + ZIP_ENCODING_UNKNOWN, /* not yet analyzed */ + ZIP_ENCODING_ASCII, /* plain ASCII */ + ZIP_ENCODING_UTF8_KNOWN, /* is UTF-8 */ + ZIP_ENCODING_UTF8_GUESSED, /* possibly UTF-8 */ + ZIP_ENCODING_CP437, /* Code Page 437 */ + ZIP_ENCODING_ERROR /* should be UTF-8 but isn't */ +}; + +typedef enum zip_encoding_type zip_encoding_type_t; + +struct zip_hash; +struct zip_progress; + +typedef struct zip_cdir zip_cdir_t; +typedef struct zip_dirent zip_dirent_t; +typedef struct zip_entry zip_entry_t; +typedef struct zip_extra_field zip_extra_field_t; +typedef struct zip_string zip_string_t; +typedef struct zip_buffer zip_buffer_t; +typedef struct zip_hash zip_hash_t; +typedef struct zip_progress zip_progress_t; + +/* zip archive, part of API */ + +struct zip { + zip_source_t *src; /* data source for archive */ + unsigned int open_flags; /* flags passed to zip_open */ + zip_error_t error; /* error information */ + + unsigned int flags; /* archive global flags */ + unsigned int ch_flags; /* changed archive global flags */ + + char *default_password; /* password used when no other supplied */ + + zip_string_t *comment_orig; /* archive comment */ + zip_string_t *comment_changes; /* changed archive comment */ + bool comment_changed; /* whether archive comment was changed */ + + zip_uint64_t nentry; /* number of entries */ + zip_uint64_t nentry_alloc; /* number of entries allocated */ + zip_entry_t *entry; /* entries */ + + unsigned int nopen_source; /* number of open sources using archive */ + unsigned int nopen_source_alloc; /* number of sources allocated */ + zip_source_t **open_source; /* open sources using archive */ + + zip_hash_t *names; /* hash table for name lookup */ + + zip_progress_t *progress; /* progress callback for zip_close() */ +}; + +/* file in zip archive, part of API */ + +struct zip_file { + zip_t *za; /* zip archive containing this file */ + zip_error_t error; /* error information */ + bool eof; + zip_source_t *src; /* data source */ +}; + +/* zip archive directory entry (central or local) */ + +#define ZIP_DIRENT_COMP_METHOD 0x0001u +#define ZIP_DIRENT_FILENAME 0x0002u +#define ZIP_DIRENT_COMMENT 0x0004u +#define ZIP_DIRENT_EXTRA_FIELD 0x0008u +#define ZIP_DIRENT_ATTRIBUTES 0x0010u +#define ZIP_DIRENT_LAST_MOD 0x0020u +#define ZIP_DIRENT_ENCRYPTION_METHOD 0x0040u +#define ZIP_DIRENT_PASSWORD 0x0080u +#define ZIP_DIRENT_ALL ZIP_UINT32_MAX + +struct zip_dirent { + zip_uint32_t changed; + bool local_extra_fields_read; /* whether we already read in local header extra fields */ + bool cloned; /* whether this instance is cloned, and thus shares non-changed strings */ + + bool crc_valid; /* if CRC is valid (sometimes not for encrypted archives) */ + + zip_uint16_t version_madeby; /* (c) version of creator */ + zip_uint16_t version_needed; /* (cl) version needed to extract */ + zip_uint16_t bitflags; /* (cl) general purpose bit flag */ + zip_int32_t comp_method; /* (cl) compression method used (uint16 and ZIP_CM_DEFAULT (-1)) */ + time_t last_mod; /* (cl) time of last modification */ + zip_uint32_t crc; /* (cl) CRC-32 of uncompressed data */ + zip_uint64_t comp_size; /* (cl) size of compressed data */ + zip_uint64_t uncomp_size; /* (cl) size of uncompressed data */ + zip_string_t *filename; /* (cl) file name (NUL-terminated) */ + zip_extra_field_t *extra_fields; /* (cl) extra fields, parsed */ + zip_string_t *comment; /* (c) file comment */ + zip_uint32_t disk_number; /* (c) disk number start */ + zip_uint16_t int_attrib; /* (c) internal file attributes */ + zip_uint32_t ext_attrib; /* (c) external file attributes */ + zip_uint64_t offset; /* (c) offset of local header */ + + zip_uint16_t compression_level; /* level of compression to use (never valid in orig) */ + zip_uint16_t encryption_method; /* encryption method, computed from other fields */ + char *password; /* file specific encryption password */ +}; + +/* zip archive central directory */ + +struct zip_cdir { + zip_entry_t *entry; /* directory entries */ + zip_uint64_t nentry; /* number of entries */ + zip_uint64_t nentry_alloc; /* number of entries allocated */ + + zip_uint64_t size; /* size of central directory */ + zip_uint64_t offset; /* offset of central directory in file */ + zip_string_t *comment; /* zip archive comment */ + bool is_zip64; /* central directory in zip64 format */ +}; + +struct zip_extra_field { + zip_extra_field_t *next; + zip_flags_t flags; /* in local/central header */ + zip_uint16_t id; /* header id */ + zip_uint16_t size; /* data size */ + zip_uint8_t *data; +}; + +enum zip_source_write_state { + ZIP_SOURCE_WRITE_CLOSED, /* write is not in progress */ + ZIP_SOURCE_WRITE_OPEN, /* write is in progress */ + ZIP_SOURCE_WRITE_FAILED, /* commit failed, only rollback allowed */ + ZIP_SOURCE_WRITE_REMOVED /* file was removed */ +}; +typedef enum zip_source_write_state zip_source_write_state_t; + +struct zip_source { + zip_source_t *src; + union { + zip_source_callback f; + zip_source_layered_callback l; + } cb; + void *ud; + zip_error_t error; + zip_int64_t supports; /* supported commands */ + unsigned int open_count; /* number of times source was opened (directly or as lower layer) */ + zip_source_write_state_t write_state; /* whether source is open for writing */ + bool source_closed; /* set if source archive is closed */ + zip_t *source_archive; /* zip archive we're reading from, NULL if not from archive */ + unsigned int refcount; + bool eof; /* EOF reached */ + bool had_read_error; /* a previous ZIP_SOURCE_READ reported an error */ + zip_uint64_t bytes_read; /* for sources that don't support ZIP_SOURCE_TELL. */ +}; + +#define ZIP_SOURCE_IS_OPEN_READING(src) ((src)->open_count > 0) +#define ZIP_SOURCE_IS_OPEN_WRITING(src) ((src)->write_state == ZIP_SOURCE_WRITE_OPEN) +#define ZIP_SOURCE_IS_LAYERED(src) ((src)->src != NULL) + +/* entry in zip archive directory */ + +struct zip_entry { + zip_dirent_t *orig; + zip_dirent_t *changes; + zip_source_t *source; + bool deleted; +}; + + +/* file or archive comment, or filename */ + +struct zip_string { + zip_uint8_t *raw; /* raw string */ + zip_uint16_t length; /* length of raw string */ + enum zip_encoding_type encoding; /* autorecognized encoding */ + zip_uint8_t *converted; /* autoconverted string */ + zip_uint32_t converted_length; /* length of converted */ +}; + + +/* byte array */ + +/* For performance, we usually keep 8k byte arrays on the stack. + However, there are (embedded) systems with a stack size of 12k; + for those, use malloc()/free() */ + +#ifdef ZIP_ALLOCATE_BUFFER +#define DEFINE_BYTE_ARRAY(buf, size) zip_uint8_t *buf +#define byte_array_init(buf, size) (((buf) = (zip_uint8_t *)malloc(size)) != NULL) +#define byte_array_fini(buf) (free(buf)) +#else +#define DEFINE_BYTE_ARRAY(buf, size) zip_uint8_t buf[size] +#define byte_array_init(buf, size) (1) +#define byte_array_fini(buf) ((void)0) +#endif + + +/* bounds checked access to memory buffer */ + +struct zip_buffer { + bool ok; + bool free_data; + + zip_uint8_t *data; + zip_uint64_t size; + zip_uint64_t offset; +}; + +/* which files to write in which order */ + +struct zip_filelist { + zip_uint64_t idx; + /* TODO const char *name; */ +}; + +typedef struct zip_filelist zip_filelist_t; + +struct _zip_winzip_aes; +typedef struct _zip_winzip_aes zip_winzip_aes_t; + +struct _zip_pkware_keys { + zip_uint32_t key[3]; +}; +typedef struct _zip_pkware_keys zip_pkware_keys_t; + +extern const char *const _zip_err_str[]; +extern const int _zip_nerr_str; +extern const int _zip_err_type[]; + +#define ZIP_MAX(a, b) ((a) > (b) ? (a) : (b)) +#define ZIP_MIN(a, b) ((a) < (b) ? (a) : (b)) + +#define ZIP_ENTRY_CHANGED(e, f) ((e)->changes && ((e)->changes->changed & (f))) +#define ZIP_ENTRY_DATA_CHANGED(x) ((x)->source != NULL) +#define ZIP_ENTRY_HAS_CHANGES(e) (ZIP_ENTRY_DATA_CHANGED(e) || (e)->deleted || ZIP_ENTRY_CHANGED((e), ZIP_DIRENT_ALL)) + +#define ZIP_IS_RDONLY(za) ((za)->ch_flags & ZIP_AFL_RDONLY) + + +#ifdef HAVE_EXPLICIT_MEMSET +#define _zip_crypto_clear(b, l) explicit_memset((b), 0, (l)) +#else +#ifdef HAVE_EXPLICIT_BZERO +#define _zip_crypto_clear(b, l) explicit_bzero((b), (l)) +#else +#include +#define _zip_crypto_clear(b, l) memset((b), 0, (l)) +#endif +#endif + + +zip_int64_t _zip_add_entry(zip_t *); + +zip_uint8_t *_zip_buffer_data(zip_buffer_t *buffer); +bool _zip_buffer_eof(zip_buffer_t *buffer); +void _zip_buffer_free(zip_buffer_t *buffer); +zip_uint8_t *_zip_buffer_get(zip_buffer_t *buffer, zip_uint64_t length); +zip_uint16_t _zip_buffer_get_16(zip_buffer_t *buffer); +zip_uint32_t _zip_buffer_get_32(zip_buffer_t *buffer); +zip_uint64_t _zip_buffer_get_64(zip_buffer_t *buffer); +zip_uint8_t _zip_buffer_get_8(zip_buffer_t *buffer); +zip_uint64_t _zip_buffer_left(zip_buffer_t *buffer); +zip_buffer_t *_zip_buffer_new(zip_uint8_t *data, zip_uint64_t size); +zip_buffer_t *_zip_buffer_new_from_source(zip_source_t *src, zip_uint64_t size, zip_uint8_t *buf, zip_error_t *error); +zip_uint64_t _zip_buffer_offset(zip_buffer_t *buffer); +bool _zip_buffer_ok(zip_buffer_t *buffer); +zip_uint8_t *_zip_buffer_peek(zip_buffer_t *buffer, zip_uint64_t length); +int _zip_buffer_put(zip_buffer_t *buffer, const void *src, size_t length); +int _zip_buffer_put_16(zip_buffer_t *buffer, zip_uint16_t i); +int _zip_buffer_put_32(zip_buffer_t *buffer, zip_uint32_t i); +int _zip_buffer_put_64(zip_buffer_t *buffer, zip_uint64_t i); +int _zip_buffer_put_8(zip_buffer_t *buffer, zip_uint8_t i); +zip_uint64_t _zip_buffer_read(zip_buffer_t *buffer, zip_uint8_t *data, zip_uint64_t length); +int _zip_buffer_skip(zip_buffer_t *buffer, zip_uint64_t length); +int _zip_buffer_set_offset(zip_buffer_t *buffer, zip_uint64_t offset); +zip_uint64_t _zip_buffer_size(zip_buffer_t *buffer); + +void _zip_cdir_free(zip_cdir_t *); +bool _zip_cdir_grow(zip_cdir_t *cd, zip_uint64_t additional_entries, zip_error_t *error); +zip_cdir_t *_zip_cdir_new(zip_uint64_t, zip_error_t *); +zip_int64_t _zip_cdir_write(zip_t *za, const zip_filelist_t *filelist, zip_uint64_t survivors); +time_t _zip_d2u_time(zip_uint16_t, zip_uint16_t); +void _zip_deregister_source(zip_t *za, zip_source_t *src); + +void _zip_dirent_apply_attributes(zip_dirent_t *, zip_file_attributes_t *, bool, zip_uint32_t); +zip_dirent_t *_zip_dirent_clone(const zip_dirent_t *); +void _zip_dirent_free(zip_dirent_t *); +void _zip_dirent_finalize(zip_dirent_t *); +void _zip_dirent_init(zip_dirent_t *); +bool _zip_dirent_needs_zip64(const zip_dirent_t *, zip_flags_t); +zip_dirent_t *_zip_dirent_new(void); +zip_int64_t _zip_dirent_read(zip_dirent_t *zde, zip_source_t *src, zip_buffer_t *buffer, bool local, zip_error_t *error); +void _zip_dirent_set_version_needed(zip_dirent_t *de, bool force_zip64); +zip_int32_t _zip_dirent_size(zip_source_t *src, zip_uint16_t, zip_error_t *); +int _zip_dirent_write(zip_t *za, zip_dirent_t *dirent, zip_flags_t flags); + +zip_extra_field_t *_zip_ef_clone(const zip_extra_field_t *, zip_error_t *); +zip_extra_field_t *_zip_ef_delete_by_id(zip_extra_field_t *, zip_uint16_t, zip_uint16_t, zip_flags_t); +void _zip_ef_free(zip_extra_field_t *); +const zip_uint8_t *_zip_ef_get_by_id(const zip_extra_field_t *, zip_uint16_t *, zip_uint16_t, zip_uint16_t, zip_flags_t, zip_error_t *); +zip_extra_field_t *_zip_ef_merge(zip_extra_field_t *, zip_extra_field_t *); +zip_extra_field_t *_zip_ef_new(zip_uint16_t, zip_uint16_t, const zip_uint8_t *, zip_flags_t); +bool _zip_ef_parse(const zip_uint8_t *, zip_uint16_t, zip_flags_t, zip_extra_field_t **, zip_error_t *); +zip_extra_field_t *_zip_ef_remove_internal(zip_extra_field_t *); +zip_uint16_t _zip_ef_size(const zip_extra_field_t *, zip_flags_t); +int _zip_ef_write(zip_t *za, const zip_extra_field_t *ef, zip_flags_t flags); + +void _zip_entry_finalize(zip_entry_t *); +void _zip_entry_init(zip_entry_t *); + +void _zip_error_clear(zip_error_t *); +void _zip_error_get(const zip_error_t *, int *, int *); + +void _zip_error_copy(zip_error_t *dst, const zip_error_t *src); +void _zip_error_set_from_source(zip_error_t *, zip_source_t *); + +const zip_uint8_t *_zip_extract_extra_field_by_id(zip_error_t *, zip_uint16_t, int, const zip_uint8_t *, zip_uint16_t, zip_uint16_t *); + +int _zip_file_extra_field_prepare_for_change(zip_t *, zip_uint64_t); +int _zip_file_fillbuf(void *, size_t, zip_file_t *); +zip_uint64_t _zip_file_get_end(const zip_t *za, zip_uint64_t index, zip_error_t *error); +zip_uint64_t _zip_file_get_offset(const zip_t *, zip_uint64_t, zip_error_t *); + +zip_dirent_t *_zip_get_dirent(zip_t *, zip_uint64_t, zip_flags_t, zip_error_t *); + +enum zip_encoding_type _zip_guess_encoding(zip_string_t *, enum zip_encoding_type); +zip_uint8_t *_zip_cp437_to_utf8(const zip_uint8_t *const, zip_uint32_t, zip_uint32_t *, zip_error_t *); + +bool _zip_hash_add(zip_hash_t *hash, const zip_uint8_t *name, zip_uint64_t index, zip_flags_t flags, zip_error_t *error); +bool _zip_hash_delete(zip_hash_t *hash, const zip_uint8_t *key, zip_error_t *error); +void _zip_hash_free(zip_hash_t *hash); +zip_int64_t _zip_hash_lookup(zip_hash_t *hash, const zip_uint8_t *name, zip_flags_t flags, zip_error_t *error); +zip_hash_t *_zip_hash_new(zip_error_t *error); +bool _zip_hash_reserve_capacity(zip_hash_t *hash, zip_uint64_t capacity, zip_error_t *error); +bool _zip_hash_revert(zip_hash_t *hash, zip_error_t *error); + +int _zip_mkstempm(char *path, int mode); + +zip_t *_zip_open(zip_source_t *, unsigned int, zip_error_t *); + +void _zip_progress_end(zip_progress_t *progress); +void _zip_progress_free(zip_progress_t *progress); +int _zip_progress_start(zip_progress_t *progress); +int _zip_progress_subrange(zip_progress_t *progress, double start, double end); +int _zip_progress_update(zip_progress_t *progress, double value); + +/* this symbol is extern so it can be overridden for regression testing */ +//ZIP_EXTERN bool zip_secure_random(zip_uint8_t *buffer, zip_uint16_t length); +zip_uint32_t zip_random_uint32(void); + +int _zip_read(zip_source_t *src, zip_uint8_t *data, zip_uint64_t length, zip_error_t *error); +int _zip_read_at_offset(zip_source_t *src, zip_uint64_t offset, unsigned char *b, size_t length, zip_error_t *error); +zip_uint8_t *_zip_read_data(zip_buffer_t *buffer, zip_source_t *src, size_t length, bool nulp, zip_error_t *error); +int _zip_read_local_ef(zip_t *, zip_uint64_t); +zip_string_t *_zip_read_string(zip_buffer_t *buffer, zip_source_t *src, zip_uint16_t length, bool nulp, zip_error_t *error); +int _zip_register_source(zip_t *za, zip_source_t *src); + +void _zip_set_open_error(int *zep, const zip_error_t *err, int ze); + +bool zip_source_accept_empty(zip_source_t *src); +zip_int64_t _zip_source_call(zip_source_t *src, void *data, zip_uint64_t length, zip_source_cmd_t command); +bool _zip_source_eof(zip_source_t *); +zip_source_t *_zip_source_file_or_p(const char *, FILE *, zip_uint64_t, zip_int64_t, const zip_stat_t *, zip_error_t *error); +bool _zip_source_had_error(zip_source_t *); +void _zip_source_invalidate(zip_source_t *src); +zip_source_t *_zip_source_new(zip_error_t *error); +int _zip_source_set_source_archive(zip_source_t *, zip_t *); +zip_source_t *_zip_source_window_new(zip_source_t *src, zip_uint64_t start, zip_uint64_t length, zip_stat_t *st, zip_file_attributes_t *attributes, zip_t *source_archive, zip_uint64_t source_index, zip_error_t *error); +zip_source_t *_zip_source_zip_new(zip_t *, zip_t *, zip_uint64_t, zip_flags_t, zip_uint64_t, zip_uint64_t, const char *); + +int _zip_stat_merge(zip_stat_t *dst, const zip_stat_t *src, zip_error_t *error); +int _zip_string_equal(const zip_string_t *, const zip_string_t *); +void _zip_string_free(zip_string_t *); +zip_uint32_t _zip_string_crc32(const zip_string_t *); +const zip_uint8_t *_zip_string_get(zip_string_t *, zip_uint32_t *, zip_flags_t, zip_error_t *); +zip_uint16_t _zip_string_length(const zip_string_t *); +zip_string_t *_zip_string_new(const zip_uint8_t *, zip_uint16_t, zip_flags_t, zip_error_t *); +int _zip_string_write(zip_t *za, const zip_string_t *string); +bool _zip_winzip_aes_decrypt(zip_winzip_aes_t *ctx, zip_uint8_t *data, zip_uint64_t length); +bool _zip_winzip_aes_encrypt(zip_winzip_aes_t *ctx, zip_uint8_t *data, zip_uint64_t length); +bool _zip_winzip_aes_finish(zip_winzip_aes_t *ctx, zip_uint8_t *hmac); +void _zip_winzip_aes_free(zip_winzip_aes_t *ctx); +zip_winzip_aes_t *_zip_winzip_aes_new(const zip_uint8_t *password, zip_uint64_t password_length, const zip_uint8_t *salt, zip_uint16_t key_size, zip_uint8_t *password_verify, zip_error_t *error); + +void _zip_pkware_encrypt(zip_pkware_keys_t *keys, zip_uint8_t *out, const zip_uint8_t *in, zip_uint64_t len); +void _zip_pkware_decrypt(zip_pkware_keys_t *keys, zip_uint8_t *out, const zip_uint8_t *in, zip_uint64_t len); +zip_pkware_keys_t *_zip_pkware_keys_new(zip_error_t *error); +void _zip_pkware_keys_free(zip_pkware_keys_t *keys); +void _zip_pkware_keys_reset(zip_pkware_keys_t *keys); + +int _zip_changed(const zip_t *, zip_uint64_t *); +const char *_zip_get_name(zip_t *, zip_uint64_t, zip_flags_t, zip_error_t *); +int _zip_local_header_read(zip_t *, int); +void *_zip_memdup(const void *, size_t, zip_error_t *); +zip_int64_t _zip_name_locate(zip_t *, const char *, zip_flags_t, zip_error_t *); +zip_t *_zip_new(zip_error_t *); + +zip_int64_t _zip_file_replace(zip_t *, zip_uint64_t, const char *, zip_source_t *, zip_flags_t); +int _zip_set_name(zip_t *, zip_uint64_t, const char *, zip_flags_t); +void _zip_u2d_time(time_t, zip_uint16_t *, zip_uint16_t *); +int _zip_unchange(zip_t *, zip_uint64_t, int); +void _zip_unchange_data(zip_entry_t *); +int _zip_write(zip_t *za, const void *data, zip_uint64_t length); + +#endif /* zipint.h */ diff --git a/Include/Libraries/zlib/FAQ b/Include/Libraries/zlib/FAQ new file mode 100644 index 0000000..99b7cf9 --- /dev/null +++ b/Include/Libraries/zlib/FAQ @@ -0,0 +1,368 @@ + + Frequently Asked Questions about zlib + + +If your question is not there, please check the zlib home page +http://zlib.net/ which may have more recent information. +The lastest zlib FAQ is at http://zlib.net/zlib_faq.html + + + 1. Is zlib Y2K-compliant? + + Yes. zlib doesn't handle dates. + + 2. Where can I get a Windows DLL version? + + The zlib sources can be compiled without change to produce a DLL. See the + file win32/DLL_FAQ.txt in the zlib distribution. Pointers to the + precompiled DLL are found in the zlib web site at http://zlib.net/ . + + 3. Where can I get a Visual Basic interface to zlib? + + See + * http://marknelson.us/1997/01/01/zlib-engine/ + * win32/DLL_FAQ.txt in the zlib distribution + + 4. compress() returns Z_BUF_ERROR. + + Make sure that before the call of compress(), the length of the compressed + buffer is equal to the available size of the compressed buffer and not + zero. For Visual Basic, check that this parameter is passed by reference + ("as any"), not by value ("as long"). + + 5. deflate() or inflate() returns Z_BUF_ERROR. + + Before making the call, make sure that avail_in and avail_out are not zero. + When setting the parameter flush equal to Z_FINISH, also make sure that + avail_out is big enough to allow processing all pending input. Note that a + Z_BUF_ERROR is not fatal--another call to deflate() or inflate() can be + made with more input or output space. A Z_BUF_ERROR may in fact be + unavoidable depending on how the functions are used, since it is not + possible to tell whether or not there is more output pending when + strm.avail_out returns with zero. See http://zlib.net/zlib_how.html for a + heavily annotated example. + + 6. Where's the zlib documentation (man pages, etc.)? + + It's in zlib.h . Examples of zlib usage are in the files test/example.c + and test/minigzip.c, with more in examples/ . + + 7. Why don't you use GNU autoconf or libtool or ...? + + Because we would like to keep zlib as a very small and simple package. + zlib is rather portable and doesn't need much configuration. + + 8. I found a bug in zlib. + + Most of the time, such problems are due to an incorrect usage of zlib. + Please try to reproduce the problem with a small program and send the + corresponding source to us at zlib@gzip.org . Do not send multi-megabyte + data files without prior agreement. + + 9. Why do I get "undefined reference to gzputc"? + + If "make test" produces something like + + example.o(.text+0x154): undefined reference to `gzputc' + + check that you don't have old files libz.* in /usr/lib, /usr/local/lib or + /usr/X11R6/lib. Remove any old versions, then do "make install". + +10. I need a Delphi interface to zlib. + + See the contrib/delphi directory in the zlib distribution. + +11. Can zlib handle .zip archives? + + Not by itself, no. See the directory contrib/minizip in the zlib + distribution. + +12. Can zlib handle .Z files? + + No, sorry. You have to spawn an uncompress or gunzip subprocess, or adapt + the code of uncompress on your own. + +13. How can I make a Unix shared library? + + By default a shared (and a static) library is built for Unix. So: + + make distclean + ./configure + make + +14. How do I install a shared zlib library on Unix? + + After the above, then: + + make install + + However, many flavors of Unix come with a shared zlib already installed. + Before going to the trouble of compiling a shared version of zlib and + trying to install it, you may want to check if it's already there! If you + can #include , it's there. The -lz option will probably link to + it. You can check the version at the top of zlib.h or with the + ZLIB_VERSION symbol defined in zlib.h . + +15. I have a question about OttoPDF. + + We are not the authors of OttoPDF. The real author is on the OttoPDF web + site: Joel Hainley, jhainley@myndkryme.com. + +16. Can zlib decode Flate data in an Adobe PDF file? + + Yes. See http://www.pdflib.com/ . To modify PDF forms, see + http://sourceforge.net/projects/acroformtool/ . + +17. Why am I getting this "register_frame_info not found" error on Solaris? + + After installing zlib 1.1.4 on Solaris 2.6, running applications using zlib + generates an error such as: + + ld.so.1: rpm: fatal: relocation error: file /usr/local/lib/libz.so: + symbol __register_frame_info: referenced symbol not found + + The symbol __register_frame_info is not part of zlib, it is generated by + the C compiler (cc or gcc). You must recompile applications using zlib + which have this problem. This problem is specific to Solaris. See + http://www.sunfreeware.com for Solaris versions of zlib and applications + using zlib. + +18. Why does gzip give an error on a file I make with compress/deflate? + + The compress and deflate functions produce data in the zlib format, which + is different and incompatible with the gzip format. The gz* functions in + zlib on the other hand use the gzip format. Both the zlib and gzip formats + use the same compressed data format internally, but have different headers + and trailers around the compressed data. + +19. Ok, so why are there two different formats? + + The gzip format was designed to retain the directory information about a + single file, such as the name and last modification date. The zlib format + on the other hand was designed for in-memory and communication channel + applications, and has a much more compact header and trailer and uses a + faster integrity check than gzip. + +20. Well that's nice, but how do I make a gzip file in memory? + + You can request that deflate write the gzip format instead of the zlib + format using deflateInit2(). You can also request that inflate decode the + gzip format using inflateInit2(). Read zlib.h for more details. + +21. Is zlib thread-safe? + + Yes. However any library routines that zlib uses and any application- + provided memory allocation routines must also be thread-safe. zlib's gz* + functions use stdio library routines, and most of zlib's functions use the + library memory allocation routines by default. zlib's *Init* functions + allow for the application to provide custom memory allocation routines. + + Of course, you should only operate on any given zlib or gzip stream from a + single thread at a time. + +22. Can I use zlib in my commercial application? + + Yes. Please read the license in zlib.h. + +23. Is zlib under the GNU license? + + No. Please read the license in zlib.h. + +24. The license says that altered source versions must be "plainly marked". So + what exactly do I need to do to meet that requirement? + + You need to change the ZLIB_VERSION and ZLIB_VERNUM #defines in zlib.h. In + particular, the final version number needs to be changed to "f", and an + identification string should be appended to ZLIB_VERSION. Version numbers + x.x.x.f are reserved for modifications to zlib by others than the zlib + maintainers. For example, if the version of the base zlib you are altering + is "1.2.3.4", then in zlib.h you should change ZLIB_VERNUM to 0x123f, and + ZLIB_VERSION to something like "1.2.3.f-zachary-mods-v3". You can also + update the version strings in deflate.c and inftrees.c. + + For altered source distributions, you should also note the origin and + nature of the changes in zlib.h, as well as in ChangeLog and README, along + with the dates of the alterations. The origin should include at least your + name (or your company's name), and an email address to contact for help or + issues with the library. + + Note that distributing a compiled zlib library along with zlib.h and + zconf.h is also a source distribution, and so you should change + ZLIB_VERSION and ZLIB_VERNUM and note the origin and nature of the changes + in zlib.h as you would for a full source distribution. + +25. Will zlib work on a big-endian or little-endian architecture, and can I + exchange compressed data between them? + + Yes and yes. + +26. Will zlib work on a 64-bit machine? + + Yes. It has been tested on 64-bit machines, and has no dependence on any + data types being limited to 32-bits in length. If you have any + difficulties, please provide a complete problem report to zlib@gzip.org + +27. Will zlib decompress data from the PKWare Data Compression Library? + + No. The PKWare DCL uses a completely different compressed data format than + does PKZIP and zlib. However, you can look in zlib's contrib/blast + directory for a possible solution to your problem. + +28. Can I access data randomly in a compressed stream? + + No, not without some preparation. If when compressing you periodically use + Z_FULL_FLUSH, carefully write all the pending data at those points, and + keep an index of those locations, then you can start decompression at those + points. You have to be careful to not use Z_FULL_FLUSH too often, since it + can significantly degrade compression. Alternatively, you can scan a + deflate stream once to generate an index, and then use that index for + random access. See examples/zran.c . + +29. Does zlib work on MVS, OS/390, CICS, etc.? + + It has in the past, but we have not heard of any recent evidence. There + were working ports of zlib 1.1.4 to MVS, but those links no longer work. + If you know of recent, successful applications of zlib on these operating + systems, please let us know. Thanks. + +30. Is there some simpler, easier to read version of inflate I can look at to + understand the deflate format? + + First off, you should read RFC 1951. Second, yes. Look in zlib's + contrib/puff directory. + +31. Does zlib infringe on any patents? + + As far as we know, no. In fact, that was originally the whole point behind + zlib. Look here for some more information: + + http://www.gzip.org/#faq11 + +32. Can zlib work with greater than 4 GB of data? + + Yes. inflate() and deflate() will process any amount of data correctly. + Each call of inflate() or deflate() is limited to input and output chunks + of the maximum value that can be stored in the compiler's "unsigned int" + type, but there is no limit to the number of chunks. Note however that the + strm.total_in and strm_total_out counters may be limited to 4 GB. These + counters are provided as a convenience and are not used internally by + inflate() or deflate(). The application can easily set up its own counters + updated after each call of inflate() or deflate() to count beyond 4 GB. + compress() and uncompress() may be limited to 4 GB, since they operate in a + single call. gzseek() and gztell() may be limited to 4 GB depending on how + zlib is compiled. See the zlibCompileFlags() function in zlib.h. + + The word "may" appears several times above since there is a 4 GB limit only + if the compiler's "long" type is 32 bits. If the compiler's "long" type is + 64 bits, then the limit is 16 exabytes. + +33. Does zlib have any security vulnerabilities? + + The only one that we are aware of is potentially in gzprintf(). If zlib is + compiled to use sprintf() or vsprintf(), then there is no protection + against a buffer overflow of an 8K string space (or other value as set by + gzbuffer()), other than the caller of gzprintf() assuring that the output + will not exceed 8K. On the other hand, if zlib is compiled to use + snprintf() or vsnprintf(), which should normally be the case, then there is + no vulnerability. The ./configure script will display warnings if an + insecure variation of sprintf() will be used by gzprintf(). Also the + zlibCompileFlags() function will return information on what variant of + sprintf() is used by gzprintf(). + + If you don't have snprintf() or vsnprintf() and would like one, you can + find a portable implementation here: + + http://www.ijs.si/software/snprintf/ + + Note that you should be using the most recent version of zlib. Versions + 1.1.3 and before were subject to a double-free vulnerability, and versions + 1.2.1 and 1.2.2 were subject to an access exception when decompressing + invalid compressed data. + +34. Is there a Java version of zlib? + + Probably what you want is to use zlib in Java. zlib is already included + as part of the Java SDK in the java.util.zip package. If you really want + a version of zlib written in the Java language, look on the zlib home + page for links: http://zlib.net/ . + +35. I get this or that compiler or source-code scanner warning when I crank it + up to maximally-pedantic. Can't you guys write proper code? + + Many years ago, we gave up attempting to avoid warnings on every compiler + in the universe. It just got to be a waste of time, and some compilers + were downright silly as well as contradicted each other. So now, we simply + make sure that the code always works. + +36. Valgrind (or some similar memory access checker) says that deflate is + performing a conditional jump that depends on an uninitialized value. + Isn't that a bug? + + No. That is intentional for performance reasons, and the output of deflate + is not affected. This only started showing up recently since zlib 1.2.x + uses malloc() by default for allocations, whereas earlier versions used + calloc(), which zeros out the allocated memory. Even though the code was + correct, versions 1.2.4 and later was changed to not stimulate these + checkers. + +37. Will zlib read the (insert any ancient or arcane format here) compressed + data format? + + Probably not. Look in the comp.compression FAQ for pointers to various + formats and associated software. + +38. How can I encrypt/decrypt zip files with zlib? + + zlib doesn't support encryption. The original PKZIP encryption is very + weak and can be broken with freely available programs. To get strong + encryption, use GnuPG, http://www.gnupg.org/ , which already includes zlib + compression. For PKZIP compatible "encryption", look at + http://www.info-zip.org/ + +39. What's the difference between the "gzip" and "deflate" HTTP 1.1 encodings? + + "gzip" is the gzip format, and "deflate" is the zlib format. They should + probably have called the second one "zlib" instead to avoid confusion with + the raw deflate compressed data format. While the HTTP 1.1 RFC 2616 + correctly points to the zlib specification in RFC 1950 for the "deflate" + transfer encoding, there have been reports of servers and browsers that + incorrectly produce or expect raw deflate data per the deflate + specification in RFC 1951, most notably Microsoft. So even though the + "deflate" transfer encoding using the zlib format would be the more + efficient approach (and in fact exactly what the zlib format was designed + for), using the "gzip" transfer encoding is probably more reliable due to + an unfortunate choice of name on the part of the HTTP 1.1 authors. + + Bottom line: use the gzip format for HTTP 1.1 encoding. + +40. Does zlib support the new "Deflate64" format introduced by PKWare? + + No. PKWare has apparently decided to keep that format proprietary, since + they have not documented it as they have previous compression formats. In + any case, the compression improvements are so modest compared to other more + modern approaches, that it's not worth the effort to implement. + +41. I'm having a problem with the zip functions in zlib, can you help? + + There are no zip functions in zlib. You are probably using minizip by + Giles Vollant, which is found in the contrib directory of zlib. It is not + part of zlib. In fact none of the stuff in contrib is part of zlib. The + files in there are not supported by the zlib authors. You need to contact + the authors of the respective contribution for help. + +42. The match.asm code in contrib is under the GNU General Public License. + Since it's part of zlib, doesn't that mean that all of zlib falls under the + GNU GPL? + + No. The files in contrib are not part of zlib. They were contributed by + other authors and are provided as a convenience to the user within the zlib + distribution. Each item in contrib has its own license. + +43. Is zlib subject to export controls? What is its ECCN? + + zlib is not subject to export controls, and so is classified as EAR99. + +44. Can you please sign these lengthy legal documents and fax them back to us + so that we can use your software in our product? + + No. Go away. Shoo. diff --git a/Include/Libraries/zlib/README b/Include/Libraries/zlib/README new file mode 100644 index 0000000..51106de --- /dev/null +++ b/Include/Libraries/zlib/README @@ -0,0 +1,115 @@ +ZLIB DATA COMPRESSION LIBRARY + +zlib 1.2.11 is a general purpose data compression library. All the code is +thread safe. The data format used by the zlib library is described by RFCs +(Request for Comments) 1950 to 1952 in the files +http://tools.ietf.org/html/rfc1950 (zlib format), rfc1951 (deflate format) and +rfc1952 (gzip format). + +All functions of the compression library are documented in the file zlib.h +(volunteer to write man pages welcome, contact zlib@gzip.org). A usage example +of the library is given in the file test/example.c which also tests that +the library is working correctly. Another example is given in the file +test/minigzip.c. The compression library itself is composed of all source +files in the root directory. + +To compile all files and run the test program, follow the instructions given at +the top of Makefile.in. In short "./configure; make test", and if that goes +well, "make install" should work for most flavors of Unix. For Windows, use +one of the special makefiles in win32/ or contrib/vstudio/ . For VMS, use +make_vms.com. + +Questions about zlib should be sent to , or to Gilles Vollant + for the Windows DLL version. The zlib home page is +http://zlib.net/ . Before reporting a problem, please check this site to +verify that you have the latest version of zlib; otherwise get the latest +version and check whether the problem still exists or not. + +PLEASE read the zlib FAQ http://zlib.net/zlib_faq.html before asking for help. + +Mark Nelson wrote an article about zlib for the Jan. 1997 +issue of Dr. Dobb's Journal; a copy of the article is available at +http://marknelson.us/1997/01/01/zlib-engine/ . + +The changes made in version 1.2.11 are documented in the file ChangeLog. + +Unsupported third party contributions are provided in directory contrib/ . + +zlib is available in Java using the java.util.zip package, documented at +http://java.sun.com/developer/technicalArticles/Programming/compression/ . + +A Perl interface to zlib written by Paul Marquess is available +at CPAN (Comprehensive Perl Archive Network) sites, including +http://search.cpan.org/~pmqs/IO-Compress-Zlib/ . + +A Python interface to zlib written by A.M. Kuchling is +available in Python 1.5 and later versions, see +http://docs.python.org/library/zlib.html . + +zlib is built into tcl: http://wiki.tcl.tk/4610 . + +An experimental package to read and write files in .zip format, written on top +of zlib by Gilles Vollant , is available in the +contrib/minizip directory of zlib. + + +Notes for some targets: + +- For Windows DLL versions, please see win32/DLL_FAQ.txt + +- For 64-bit Irix, deflate.c must be compiled without any optimization. With + -O, one libpng test fails. The test works in 32 bit mode (with the -n32 + compiler flag). The compiler bug has been reported to SGI. + +- zlib doesn't work with gcc 2.6.3 on a DEC 3000/300LX under OSF/1 2.1 it works + when compiled with cc. + +- On Digital Unix 4.0D (formely OSF/1) on AlphaServer, the cc option -std1 is + necessary to get gzprintf working correctly. This is done by configure. + +- zlib doesn't work on HP-UX 9.05 with some versions of /bin/cc. It works with + other compilers. Use "make test" to check your compiler. + +- gzdopen is not supported on RISCOS or BEOS. + +- For PalmOs, see http://palmzlib.sourceforge.net/ + + +Acknowledgments: + + The deflate format used by zlib was defined by Phil Katz. The deflate and + zlib specifications were written by L. Peter Deutsch. Thanks to all the + people who reported problems and suggested various improvements in zlib; they + are too numerous to cite here. + +Copyright notice: + + (C) 1995-2017 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + +If you use the zlib library in a product, we would appreciate *not* receiving +lengthy legal documents to sign. The sources are provided for free but without +warranty of any kind. The library has been entirely written by Jean-loup +Gailly and Mark Adler; it does not include third-party code. + +If you redistribute modified sources, we would appreciate that you include in +the file ChangeLog history information documenting your changes. Please read +the FAQ for more information on the distribution of modified source versions. diff --git a/Include/Libraries/zlib/crc32.h b/Include/Libraries/zlib/crc32.h new file mode 100644 index 0000000..9e0c778 --- /dev/null +++ b/Include/Libraries/zlib/crc32.h @@ -0,0 +1,441 @@ +/* crc32.h -- tables for rapid CRC calculation + * Generated automatically by crc32.c + */ + +local const z_crc_t FAR crc_table[TBLS][256] = +{ + { + 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL, + 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL, + 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL, + 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL, + 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL, + 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL, + 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL, + 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL, + 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL, + 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL, + 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL, + 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL, + 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL, + 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL, + 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL, + 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL, + 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL, + 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL, + 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL, + 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL, + 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL, + 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL, + 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL, + 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL, + 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL, + 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL, + 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL, + 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL, + 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL, + 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL, + 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL, + 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL, + 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL, + 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL, + 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL, + 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL, + 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL, + 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL, + 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL, + 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL, + 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL, + 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL, + 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL, + 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL, + 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL, + 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL, + 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL, + 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL, + 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL, + 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL, + 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL, + 0x2d02ef8dUL +#ifdef BYFOUR + }, + { + 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL, + 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL, + 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL, + 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL, + 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL, + 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL, + 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL, + 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL, + 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL, + 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL, + 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL, + 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL, + 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL, + 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL, + 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL, + 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL, + 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL, + 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL, + 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL, + 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL, + 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL, + 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL, + 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL, + 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL, + 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL, + 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL, + 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL, + 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL, + 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL, + 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL, + 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL, + 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL, + 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL, + 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL, + 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL, + 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL, + 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL, + 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL, + 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL, + 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL, + 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL, + 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL, + 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL, + 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL, + 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL, + 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL, + 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL, + 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL, + 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL, + 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL, + 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL, + 0x9324fd72UL + }, + { + 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL, + 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL, + 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL, + 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL, + 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL, + 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL, + 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL, + 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL, + 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL, + 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL, + 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL, + 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL, + 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL, + 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL, + 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL, + 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL, + 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL, + 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL, + 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL, + 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL, + 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL, + 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL, + 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL, + 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL, + 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL, + 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL, + 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL, + 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL, + 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL, + 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL, + 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL, + 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL, + 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL, + 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL, + 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL, + 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL, + 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL, + 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL, + 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL, + 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL, + 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL, + 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL, + 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL, + 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL, + 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL, + 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL, + 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL, + 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL, + 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL, + 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL, + 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL, + 0xbe9834edUL + }, + { + 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL, + 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL, + 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL, + 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL, + 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL, + 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL, + 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL, + 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL, + 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL, + 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL, + 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL, + 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL, + 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL, + 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL, + 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL, + 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL, + 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL, + 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL, + 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL, + 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL, + 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL, + 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL, + 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL, + 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL, + 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL, + 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL, + 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL, + 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL, + 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL, + 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL, + 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL, + 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL, + 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL, + 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL, + 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL, + 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL, + 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL, + 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL, + 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL, + 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL, + 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL, + 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL, + 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL, + 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL, + 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL, + 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL, + 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL, + 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL, + 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL, + 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL, + 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL, + 0xde0506f1UL + }, + { + 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL, + 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL, + 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL, + 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL, + 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL, + 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL, + 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL, + 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL, + 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL, + 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL, + 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL, + 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL, + 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL, + 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL, + 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL, + 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL, + 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL, + 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL, + 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL, + 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL, + 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL, + 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL, + 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL, + 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL, + 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL, + 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL, + 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL, + 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL, + 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL, + 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL, + 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL, + 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL, + 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL, + 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL, + 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL, + 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL, + 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL, + 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL, + 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL, + 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL, + 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL, + 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL, + 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL, + 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL, + 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL, + 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL, + 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL, + 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL, + 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL, + 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL, + 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL, + 0x8def022dUL + }, + { + 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL, + 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL, + 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL, + 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL, + 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL, + 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL, + 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL, + 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL, + 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL, + 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL, + 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL, + 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL, + 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL, + 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL, + 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL, + 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL, + 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL, + 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL, + 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL, + 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL, + 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL, + 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL, + 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL, + 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL, + 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL, + 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL, + 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL, + 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL, + 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL, + 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL, + 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL, + 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL, + 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL, + 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL, + 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL, + 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL, + 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL, + 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL, + 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL, + 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL, + 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL, + 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL, + 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL, + 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL, + 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL, + 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL, + 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL, + 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL, + 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL, + 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL, + 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL, + 0x72fd2493UL + }, + { + 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL, + 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL, + 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL, + 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL, + 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL, + 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL, + 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL, + 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL, + 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL, + 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL, + 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL, + 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL, + 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL, + 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL, + 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL, + 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL, + 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL, + 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL, + 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL, + 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL, + 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL, + 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL, + 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL, + 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL, + 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL, + 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL, + 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL, + 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL, + 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL, + 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL, + 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL, + 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL, + 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL, + 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL, + 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL, + 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL, + 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL, + 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL, + 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL, + 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL, + 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL, + 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL, + 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL, + 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL, + 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL, + 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL, + 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL, + 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL, + 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL, + 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL, + 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL, + 0xed3498beUL + }, + { + 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL, + 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL, + 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL, + 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL, + 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL, + 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL, + 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL, + 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL, + 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL, + 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL, + 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL, + 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL, + 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL, + 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL, + 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL, + 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL, + 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL, + 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL, + 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL, + 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL, + 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL, + 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL, + 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL, + 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL, + 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL, + 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL, + 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL, + 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL, + 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL, + 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL, + 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL, + 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL, + 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL, + 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL, + 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL, + 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL, + 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL, + 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL, + 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL, + 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL, + 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL, + 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL, + 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL, + 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL, + 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL, + 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL, + 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL, + 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL, + 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL, + 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL, + 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL, + 0xf10605deUL +#endif + } +}; diff --git a/Include/Libraries/zlib/deflate.h b/Include/Libraries/zlib/deflate.h new file mode 100644 index 0000000..23ecdd3 --- /dev/null +++ b/Include/Libraries/zlib/deflate.h @@ -0,0 +1,349 @@ +/* deflate.h -- internal compression state + * Copyright (C) 1995-2016 Jean-loup Gailly + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* @(#) $Id$ */ + +#ifndef DEFLATE_H +#define DEFLATE_H + +#include "zutil.h" + +/* define NO_GZIP when compiling if you want to disable gzip header and + trailer creation by deflate(). NO_GZIP would be used to avoid linking in + the crc code when it is not needed. For shared libraries, gzip encoding + should be left enabled. */ +#ifndef NO_GZIP +# define GZIP +#endif + +/* =========================================================================== + * Internal compression state. + */ + +#define LENGTH_CODES 29 +/* number of length codes, not counting the special END_BLOCK code */ + +#define LITERALS 256 +/* number of literal bytes 0..255 */ + +#define L_CODES (LITERALS+1+LENGTH_CODES) +/* number of Literal or Length codes, including the END_BLOCK code */ + +#define D_CODES 30 +/* number of distance codes */ + +#define BL_CODES 19 +/* number of codes used to transfer the bit lengths */ + +#define HEAP_SIZE (2*L_CODES+1) +/* maximum heap size */ + +#define MAX_BITS 15 +/* All codes must not exceed MAX_BITS bits */ + +#define Buf_size 16 +/* size of bit buffer in bi_buf */ + +#define INIT_STATE 42 /* zlib header -> BUSY_STATE */ +#ifdef GZIP +# define GZIP_STATE 57 /* gzip header -> BUSY_STATE | EXTRA_STATE */ +#endif +#define EXTRA_STATE 69 /* gzip extra block -> NAME_STATE */ +#define NAME_STATE 73 /* gzip file name -> COMMENT_STATE */ +#define COMMENT_STATE 91 /* gzip comment -> HCRC_STATE */ +#define HCRC_STATE 103 /* gzip header CRC -> BUSY_STATE */ +#define BUSY_STATE 113 /* deflate -> FINISH_STATE */ +#define FINISH_STATE 666 /* stream complete */ +/* Stream status */ + + +/* Data structure describing a single value and its code string. */ +typedef struct ct_data_s { + union { + ush freq; /* frequency count */ + ush code; /* bit string */ + } fc; + union { + ush dad; /* father node in Huffman tree */ + ush len; /* length of bit string */ + } dl; +} FAR ct_data; + +#define Freq fc.freq +#define Code fc.code +#define Dad dl.dad +#define Len dl.len + +typedef struct static_tree_desc_s static_tree_desc; + +typedef struct tree_desc_s { + ct_data *dyn_tree; /* the dynamic tree */ + int max_code; /* largest code with non zero frequency */ + const static_tree_desc *stat_desc; /* the corresponding static tree */ +} FAR tree_desc; + +typedef ush Pos; +typedef Pos FAR Posf; +typedef unsigned IPos; + +/* A Pos is an index in the character window. We use short instead of int to + * save space in the various tables. IPos is used only for parameter passing. + */ + +typedef struct internal_state { + z_streamp strm; /* pointer back to this zlib stream */ + int status; /* as the name implies */ + Bytef *pending_buf; /* output still pending */ + ulg pending_buf_size; /* size of pending_buf */ + Bytef *pending_out; /* next pending byte to output to the stream */ + ulg pending; /* nb of bytes in the pending buffer */ + int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ + gz_headerp gzhead; /* gzip header information to write */ + ulg gzindex; /* where in extra, name, or comment */ + Byte method; /* can only be DEFLATED */ + int last_flush; /* value of flush param for previous deflate call */ + + /* used by deflate.c: */ + + uInt w_size; /* LZ77 window size (32K by default) */ + uInt w_bits; /* log2(w_size) (8..16) */ + uInt w_mask; /* w_size - 1 */ + + Bytef *window; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. Also, it limits + * the window size to 64K, which is quite useful on MSDOS. + * To do: use the user input buffer as sliding window. + */ + + ulg window_size; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + Posf *prev; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + Posf *head; /* Heads of the hash chains or NIL. */ + + uInt ins_h; /* hash index of string to be inserted */ + uInt hash_size; /* number of elements in hash table */ + uInt hash_bits; /* log2(hash_size) */ + uInt hash_mask; /* hash_size-1 */ + + uInt hash_shift; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + long block_start; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + uInt match_length; /* length of best match */ + IPos prev_match; /* previous match */ + int match_available; /* set if previous match exists */ + uInt strstart; /* start of string to insert */ + uInt match_start; /* start of matching string */ + uInt lookahead; /* number of valid bytes ahead in window */ + + uInt prev_length; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + uInt max_chain_length; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + uInt max_lazy_match; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ +# define max_insert_length max_lazy_match + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + int level; /* compression level (1..9) */ + int strategy; /* favor or force Huffman coding*/ + + uInt good_match; + /* Use a faster search when the previous match is longer than this */ + + int nice_match; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + /* Didn't use ct_data typedef below to suppress compiler warning */ + struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + struct tree_desc_s l_desc; /* desc. for literal tree */ + struct tree_desc_s d_desc; /* desc. for distance tree */ + struct tree_desc_s bl_desc; /* desc. for bit length tree */ + + ush bl_count[MAX_BITS+1]; + /* number of codes at each bit length for an optimal tree */ + + int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + int heap_len; /* number of elements in the heap */ + int heap_max; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + uch depth[2*L_CODES+1]; + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + uchf *l_buf; /* buffer for literals or lengths */ + + uInt lit_bufsize; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + uInt last_lit; /* running index in l_buf */ + + ushf *d_buf; + /* Buffer for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + ulg opt_len; /* bit length of current block with optimal trees */ + ulg static_len; /* bit length of current block with static trees */ + uInt matches; /* number of string matches in current block */ + uInt insert; /* bytes at end of window left to insert */ + +#ifdef ZLIB_DEBUG + ulg compressed_len; /* total bit length of compressed file mod 2^32 */ + ulg bits_sent; /* bit length of compressed data sent mod 2^32 */ +#endif + + ush bi_buf; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + int bi_valid; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + ulg high_water; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ + +} FAR deflate_state; + +/* Output a byte on the stream. + * IN assertion: there is enough room in pending_buf. + */ +#define put_byte(s, c) {s->pending_buf[s->pending++] = (Bytef)(c);} + + +#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) +/* Minimum amount of lookahead, except at the end of the input file. + * See deflate.c for comments about the MIN_MATCH+1. + */ + +#define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD) +/* In order to simplify the code, particularly on 16 bit machines, match + * distances are limited to MAX_DIST instead of WSIZE. + */ + +#define WIN_INIT MAX_MATCH +/* Number of bytes after end of data in window to initialize in order to avoid + memory checker errors from longest match routines */ + + /* in trees.c */ +void ZLIB_INTERNAL _tr_init OF((deflate_state *s)); +int ZLIB_INTERNAL _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); +void ZLIB_INTERNAL _tr_flush_block OF((deflate_state *s, charf *buf, + ulg stored_len, int last)); +void ZLIB_INTERNAL _tr_flush_bits OF((deflate_state *s)); +void ZLIB_INTERNAL _tr_align OF((deflate_state *s)); +void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf, + ulg stored_len, int last)); + +#define d_code(dist) \ + ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]) +/* Mapping from a distance to a distance code. dist is the distance - 1 and + * must not have side effects. _dist_code[256] and _dist_code[257] are never + * used. + */ + +#ifndef ZLIB_DEBUG +/* Inline versions of _tr_tally for speed: */ + +#if defined(GEN_TREES_H) || !defined(STDC) + extern uch ZLIB_INTERNAL _length_code[]; + extern uch ZLIB_INTERNAL _dist_code[]; +#else + extern const uch ZLIB_INTERNAL _length_code[]; + extern const uch ZLIB_INTERNAL _dist_code[]; +#endif + +# define _tr_tally_lit(s, c, flush) \ + { uch cc = (c); \ + s->d_buf[s->last_lit] = 0; \ + s->l_buf[s->last_lit++] = cc; \ + s->dyn_ltree[cc].Freq++; \ + flush = (s->last_lit == s->lit_bufsize-1); \ + } +# define _tr_tally_dist(s, distance, length, flush) \ + { uch len = (uch)(length); \ + ush dist = (ush)(distance); \ + s->d_buf[s->last_lit] = dist; \ + s->l_buf[s->last_lit++] = len; \ + dist--; \ + s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \ + s->dyn_dtree[d_code(dist)].Freq++; \ + flush = (s->last_lit == s->lit_bufsize-1); \ + } +#else +# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c) +# define _tr_tally_dist(s, distance, length, flush) \ + flush = _tr_tally(s, distance, length) +#endif + +#endif /* DEFLATE_H */ diff --git a/Include/Libraries/zlib/gzguts.h b/Include/Libraries/zlib/gzguts.h new file mode 100644 index 0000000..990a4d2 --- /dev/null +++ b/Include/Libraries/zlib/gzguts.h @@ -0,0 +1,218 @@ +/* gzguts.h -- zlib internal header definitions for gz* operations + * Copyright (C) 2004, 2005, 2010, 2011, 2012, 2013, 2016 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#ifdef _LARGEFILE64_SOURCE +# ifndef _LARGEFILE_SOURCE +# define _LARGEFILE_SOURCE 1 +# endif +# ifdef _FILE_OFFSET_BITS +# undef _FILE_OFFSET_BITS +# endif +#endif + +#ifdef HAVE_HIDDEN +# define ZLIB_INTERNAL __attribute__((visibility ("hidden"))) +#else +# define ZLIB_INTERNAL +#endif + +#include +#include "zlib.h" +#ifdef STDC +# include +# include +# include +#endif + +#ifndef _POSIX_SOURCE +# define _POSIX_SOURCE +#endif +#include + +#ifdef _WIN32 +# include +#endif + +#if defined(__TURBOC__) || defined(_MSC_VER) || defined(_WIN32) +# include +#endif + +#if defined(_WIN32) || defined(__CYGWIN__) +# define WIDECHAR +#endif + +#ifdef WINAPI_FAMILY +# define open _open +# define read _read +# define write _write +# define close _close +#endif + +#ifdef NO_DEFLATE /* for compatibility with old definition */ +# define NO_GZCOMPRESS +#endif + +#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif + +#if defined(__CYGWIN__) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif + +#if defined(MSDOS) && defined(__BORLANDC__) && (BORLANDC > 0x410) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif + +#ifndef HAVE_VSNPRINTF +# ifdef MSDOS +/* vsnprintf may exist on some MS-DOS compilers (DJGPP?), + but for now we just assume it doesn't. */ +# define NO_vsnprintf +# endif +# ifdef __TURBOC__ +# define NO_vsnprintf +# endif +# ifdef WIN32 +/* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */ +# if !defined(vsnprintf) && !defined(NO_vsnprintf) +# if !defined(_MSC_VER) || ( defined(_MSC_VER) && _MSC_VER < 1500 ) +# define vsnprintf _vsnprintf +# endif +# endif +# endif +# ifdef __SASC +# define NO_vsnprintf +# endif +# ifdef VMS +# define NO_vsnprintf +# endif +# ifdef __OS400__ +# define NO_vsnprintf +# endif +# ifdef __MVS__ +# define NO_vsnprintf +# endif +#endif + +/* unlike snprintf (which is required in C99), _snprintf does not guarantee + null termination of the result -- however this is only used in gzlib.c where + the result is assured to fit in the space provided */ +#if defined(_MSC_VER) && _MSC_VER < 1900 +# define snprintf _snprintf +#endif + +#ifndef local +# define local static +#endif +/* since "static" is used to mean two completely different things in C, we + define "local" for the non-static meaning of "static", for readability + (compile with -Dlocal if your debugger can't find static symbols) */ + +/* gz* functions always use library allocation functions */ +#ifndef STDC + extern voidp malloc OF((uInt size)); + extern void free OF((voidpf ptr)); +#endif + +/* get errno and strerror definition */ +#if defined UNDER_CE +# include +# define zstrerror() gz_strwinerror((DWORD)GetLastError()) +#else +# ifndef NO_STRERROR +# include +# define zstrerror() strerror(errno) +# else +# define zstrerror() "stdio error (consult errno)" +# endif +#endif + +/* provide prototypes for these when building zlib without LFS */ +#if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); + ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); +#endif + +/* default memLevel */ +#if MAX_MEM_LEVEL >= 8 +# define DEF_MEM_LEVEL 8 +#else +# define DEF_MEM_LEVEL MAX_MEM_LEVEL +#endif + +/* default i/o buffer size -- double this for output when reading (this and + twice this must be able to fit in an unsigned type) */ +#define GZBUFSIZE 8192 + +/* gzip modes, also provide a little integrity check on the passed structure */ +#define GZ_NONE 0 +#define GZ_READ 7247 +#define GZ_WRITE 31153 +#define GZ_APPEND 1 /* mode set to GZ_WRITE after the file is opened */ + +/* values for gz_state how */ +#define LOOK 0 /* look for a gzip header */ +#define COPY 1 /* copy input directly */ +#define GZIP 2 /* decompress a gzip stream */ + +/* internal gzip file state data structure */ +typedef struct { + /* exposed contents for gzgetc() macro */ + struct gzFile_s x; /* "x" for exposed */ + /* x.have: number of bytes available at x.next */ + /* x.next: next output data to deliver or write */ + /* x.pos: current position in uncompressed data */ + /* used for both reading and writing */ + int mode; /* see gzip modes above */ + int fd; /* file descriptor */ + char *path; /* path or fd for error messages */ + unsigned size; /* buffer size, zero if not allocated yet */ + unsigned want; /* requested buffer size, default is GZBUFSIZE */ + unsigned char *in; /* input buffer (double-sized when writing) */ + unsigned char *out; /* output buffer (double-sized when reading) */ + int direct; /* 0 if processing gzip, 1 if transparent */ + /* just for reading */ + int how; /* 0: get header, 1: copy, 2: decompress */ + z_off64_t start; /* where the gzip data started, for rewinding */ + int eof; /* true if end of input file reached */ + int past; /* true if read requested past end */ + /* just for writing */ + int level; /* compression level */ + int strategy; /* compression strategy */ + /* seek request */ + z_off64_t skip; /* amount to skip (already rewound if backwards) */ + int seek; /* true if seek request pending */ + /* error information */ + int err; /* error code */ + char *msg; /* error message */ + /* zlib inflate or deflate stream */ + z_stream strm; /* stream structure in-place (not a pointer) */ +} gz_state; +typedef gz_state FAR *gz_statep; + +/* shared functions */ +void ZLIB_INTERNAL gz_error OF((gz_statep, int, const char *)); +#if defined UNDER_CE +char ZLIB_INTERNAL *gz_strwinerror OF((DWORD error)); +#endif + +/* GT_OFF(x), where x is an unsigned value, is true if x > maximum z_off64_t + value -- needed when comparing unsigned to z_off64_t, which is signed + (possible z_off64_t types off_t, off64_t, and long are all signed) */ +#ifdef INT_MAX +# define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > INT_MAX) +#else +unsigned ZLIB_INTERNAL gz_intmax OF((void)); +# define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > gz_intmax()) +#endif diff --git a/Include/Libraries/zlib/inffast.h b/Include/Libraries/zlib/inffast.h new file mode 100644 index 0000000..e5c1aa4 --- /dev/null +++ b/Include/Libraries/zlib/inffast.h @@ -0,0 +1,11 @@ +/* inffast.h -- header to use inffast.c + * Copyright (C) 1995-2003, 2010 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +void ZLIB_INTERNAL inflate_fast OF((z_streamp strm, unsigned start)); diff --git a/Include/Libraries/zlib/inffixed.h b/Include/Libraries/zlib/inffixed.h new file mode 100644 index 0000000..d628327 --- /dev/null +++ b/Include/Libraries/zlib/inffixed.h @@ -0,0 +1,94 @@ + /* inffixed.h -- table for decoding fixed codes + * Generated automatically by makefixed(). + */ + + /* WARNING: this file should *not* be used by applications. + It is part of the implementation of this library and is + subject to change. Applications should only use zlib.h. + */ + + static const code lenfix[512] = { + {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48}, + {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128}, + {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59}, + {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176}, + {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20}, + {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100}, + {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8}, + {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216}, + {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76}, + {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114}, + {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2}, + {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148}, + {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42}, + {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86}, + {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15}, + {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236}, + {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62}, + {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142}, + {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31}, + {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162}, + {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25}, + {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105}, + {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4}, + {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202}, + {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69}, + {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125}, + {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13}, + {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195}, + {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35}, + {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91}, + {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19}, + {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246}, + {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55}, + {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135}, + {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99}, + {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190}, + {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16}, + {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96}, + {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6}, + {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209}, + {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72}, + {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116}, + {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4}, + {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153}, + {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44}, + {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82}, + {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11}, + {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229}, + {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58}, + {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138}, + {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51}, + {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173}, + {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30}, + {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110}, + {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0}, + {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195}, + {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65}, + {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121}, + {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9}, + {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258}, + {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37}, + {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93}, + {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23}, + {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251}, + {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51}, + {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131}, + {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67}, + {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183}, + {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23}, + {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103}, + {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9}, + {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223}, + {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79}, + {0,9,255} + }; + + static const code distfix[32] = { + {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025}, + {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193}, + {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385}, + {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577}, + {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073}, + {22,5,193},{64,5,0} + }; diff --git a/Include/Libraries/zlib/inflate.h b/Include/Libraries/zlib/inflate.h new file mode 100644 index 0000000..a46cce6 --- /dev/null +++ b/Include/Libraries/zlib/inflate.h @@ -0,0 +1,125 @@ +/* inflate.h -- internal inflate state definition + * Copyright (C) 1995-2016 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* define NO_GZIP when compiling if you want to disable gzip header and + trailer decoding by inflate(). NO_GZIP would be used to avoid linking in + the crc code when it is not needed. For shared libraries, gzip decoding + should be left enabled. */ +#ifndef NO_GZIP +# define GUNZIP +#endif + +/* Possible inflate modes between inflate() calls */ +typedef enum { + HEAD = 16180, /* i: waiting for magic header */ + FLAGS, /* i: waiting for method and flags (gzip) */ + TIME, /* i: waiting for modification time (gzip) */ + OS, /* i: waiting for extra flags and operating system (gzip) */ + EXLEN, /* i: waiting for extra length (gzip) */ + EXTRA, /* i: waiting for extra bytes (gzip) */ + NAME, /* i: waiting for end of file name (gzip) */ + COMMENT, /* i: waiting for end of comment (gzip) */ + HCRC, /* i: waiting for header crc (gzip) */ + DICTID, /* i: waiting for dictionary check value */ + DICT, /* waiting for inflateSetDictionary() call */ + TYPE, /* i: waiting for type bits, including last-flag bit */ + TYPEDO, /* i: same, but skip check to exit inflate on new block */ + STORED, /* i: waiting for stored size (length and complement) */ + COPY_, /* i/o: same as COPY below, but only first time in */ + COPY, /* i/o: waiting for input or output to copy stored block */ + TABLE, /* i: waiting for dynamic block table lengths */ + LENLENS, /* i: waiting for code length code lengths */ + CODELENS, /* i: waiting for length/lit and distance code lengths */ + LEN_, /* i: same as LEN below, but only first time in */ + LEN, /* i: waiting for length/lit/eob code */ + LENEXT, /* i: waiting for length extra bits */ + DIST, /* i: waiting for distance code */ + DISTEXT, /* i: waiting for distance extra bits */ + MATCH, /* o: waiting for output space to copy string */ + LIT, /* o: waiting for output space to write literal */ + CHECK, /* i: waiting for 32-bit check value */ + LENGTH, /* i: waiting for 32-bit length (gzip) */ + DONE, /* finished check, done -- remain here until reset */ + BAD, /* got a data error -- remain here until reset */ + MEM, /* got an inflate() memory error -- remain here until reset */ + SYNC /* looking for synchronization bytes to restart inflate() */ +} inflate_mode; + +/* + State transitions between above modes - + + (most modes can go to BAD or MEM on error -- not shown for clarity) + + Process header: + HEAD -> (gzip) or (zlib) or (raw) + (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME -> COMMENT -> + HCRC -> TYPE + (zlib) -> DICTID or TYPE + DICTID -> DICT -> TYPE + (raw) -> TYPEDO + Read deflate blocks: + TYPE -> TYPEDO -> STORED or TABLE or LEN_ or CHECK + STORED -> COPY_ -> COPY -> TYPE + TABLE -> LENLENS -> CODELENS -> LEN_ + LEN_ -> LEN + Read deflate codes in fixed or dynamic block: + LEN -> LENEXT or LIT or TYPE + LENEXT -> DIST -> DISTEXT -> MATCH -> LEN + LIT -> LEN + Process trailer: + CHECK -> LENGTH -> DONE + */ + +/* State maintained between inflate() calls -- approximately 7K bytes, not + including the allocated sliding window, which is up to 32K bytes. */ +struct inflate_state { + z_streamp strm; /* pointer back to this zlib stream */ + inflate_mode mode; /* current inflate mode */ + int last; /* true if processing last block */ + int wrap; /* bit 0 true for zlib, bit 1 true for gzip, + bit 2 true to validate check value */ + int havedict; /* true if dictionary provided */ + int flags; /* gzip header method and flags (0 if zlib) */ + unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */ + unsigned long check; /* protected copy of check value */ + unsigned long total; /* protected copy of output count */ + gz_headerp head; /* where to save gzip header information */ + /* sliding window */ + unsigned wbits; /* log base 2 of requested window size */ + unsigned wsize; /* window size or zero if not using window */ + unsigned whave; /* valid bytes in the window */ + unsigned wnext; /* window write index */ + unsigned char FAR *window; /* allocated sliding window, if needed */ + /* bit accumulator */ + unsigned long hold; /* input bit accumulator */ + unsigned bits; /* number of bits in "in" */ + /* for string and stored block copying */ + unsigned length; /* literal or length of data to copy */ + unsigned offset; /* distance back to copy string from */ + /* for table and code decoding */ + unsigned extra; /* extra bits needed */ + /* fixed and dynamic code tables */ + code const FAR *lencode; /* starting table for length/literal codes */ + code const FAR *distcode; /* starting table for distance codes */ + unsigned lenbits; /* index bits for lencode */ + unsigned distbits; /* index bits for distcode */ + /* dynamic table building */ + unsigned ncode; /* number of code length code lengths */ + unsigned nlen; /* number of length code lengths */ + unsigned ndist; /* number of distance code lengths */ + unsigned have; /* number of code lengths in lens[] */ + code FAR *next; /* next available space in codes[] */ + unsigned short lens[320]; /* temporary storage for code lengths */ + unsigned short work[288]; /* work area for code table building */ + code codes[ENOUGH]; /* space for code tables */ + int sane; /* if false, allow invalid distance too far */ + int back; /* bits back of last unprocessed length/lit */ + unsigned was; /* initial length of match */ +}; diff --git a/Include/Libraries/zlib/inftrees.h b/Include/Libraries/zlib/inftrees.h new file mode 100644 index 0000000..baa53a0 --- /dev/null +++ b/Include/Libraries/zlib/inftrees.h @@ -0,0 +1,62 @@ +/* inftrees.h -- header to use inftrees.c + * Copyright (C) 1995-2005, 2010 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* Structure for decoding tables. Each entry provides either the + information needed to do the operation requested by the code that + indexed that table entry, or it provides a pointer to another + table that indexes more bits of the code. op indicates whether + the entry is a pointer to another table, a literal, a length or + distance, an end-of-block, or an invalid code. For a table + pointer, the low four bits of op is the number of index bits of + that table. For a length or distance, the low four bits of op + is the number of extra bits to get after the code. bits is + the number of bits in this code or part of the code to drop off + of the bit buffer. val is the actual byte to output in the case + of a literal, the base length or distance, or the offset from + the current table to the next table. Each entry is four bytes. */ +typedef struct { + unsigned char op; /* operation, extra bits, table bits */ + unsigned char bits; /* bits in this part of the code */ + unsigned short val; /* offset in table or code value */ +} code; + +/* op values as set by inflate_table(): + 00000000 - literal + 0000tttt - table link, tttt != 0 is the number of table index bits + 0001eeee - length or distance, eeee is the number of extra bits + 01100000 - end of block + 01000000 - invalid code + */ + +/* Maximum size of the dynamic table. The maximum number of code structures is + 1444, which is the sum of 852 for literal/length codes and 592 for distance + codes. These values were found by exhaustive searches using the program + examples/enough.c found in the zlib distribtution. The arguments to that + program are the number of symbols, the initial root table size, and the + maximum bit length of a code. "enough 286 9 15" for literal/length codes + returns returns 852, and "enough 30 6 15" for distance codes returns 592. + The initial root table size (9 or 6) is found in the fifth argument of the + inflate_table() calls in inflate.c and infback.c. If the root table size is + changed, then these maximum sizes would be need to be recalculated and + updated. */ +#define ENOUGH_LENS 852 +#define ENOUGH_DISTS 592 +#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS) + +/* Type of code to build for inflate_table() */ +typedef enum { + CODES, + LENS, + DISTS +} codetype; + +int ZLIB_INTERNAL inflate_table OF((codetype type, unsigned short FAR *lens, + unsigned codes, code FAR * FAR *table, + unsigned FAR *bits, unsigned short FAR *work)); diff --git a/Include/Libraries/zlib/trees.h b/Include/Libraries/zlib/trees.h new file mode 100644 index 0000000..d35639d --- /dev/null +++ b/Include/Libraries/zlib/trees.h @@ -0,0 +1,128 @@ +/* header created automatically with -DGEN_TREES_H */ + +local const ct_data static_ltree[L_CODES+2] = { +{{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}}, +{{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}}, +{{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}}, +{{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}}, +{{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}}, +{{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}}, +{{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}}, +{{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}}, +{{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}}, +{{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}}, +{{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}}, +{{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}}, +{{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}}, +{{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}}, +{{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}}, +{{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}}, +{{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}}, +{{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}}, +{{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}}, +{{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}}, +{{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}}, +{{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}}, +{{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}}, +{{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}}, +{{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}}, +{{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}}, +{{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}}, +{{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}}, +{{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}}, +{{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}}, +{{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}}, +{{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}}, +{{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}}, +{{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}}, +{{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}}, +{{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}}, +{{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}}, +{{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}}, +{{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}}, +{{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}}, +{{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}}, +{{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}}, +{{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}}, +{{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}}, +{{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}}, +{{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}}, +{{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}}, +{{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}}, +{{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}}, +{{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}}, +{{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}}, +{{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}}, +{{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}}, +{{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}}, +{{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}}, +{{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}}, +{{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}}, +{{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}} +}; + +local const ct_data static_dtree[D_CODES] = { +{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}}, +{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}}, +{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}}, +{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}}, +{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}}, +{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}} +}; + +const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = { + 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, + 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, +10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, +11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, +12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, +13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, +13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, +18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, +23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 +}; + +const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, +13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, +17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, +19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, +21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, +22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, +23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, +25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 +}; + +local const int base_length[LENGTH_CODES] = { +0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, +64, 80, 96, 112, 128, 160, 192, 224, 0 +}; + +local const int base_dist[D_CODES] = { + 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, + 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, + 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 +}; + diff --git a/Include/Libraries/zlib/zconf.h b/Include/Libraries/zlib/zconf.h new file mode 100644 index 0000000..352f552 --- /dev/null +++ b/Include/Libraries/zlib/zconf.h @@ -0,0 +1,536 @@ +/* zconf.h -- configuration of the zlib compression library + * Copyright (C) 1995-2016 Jean-loup Gailly, Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#ifndef ZCONF_H +#define ZCONF_H +/* #undef Z_PREFIX */ +/* #undef Z_HAVE_UNISTD_H */ + +/* + * If you *really* need a unique prefix for all types and library functions, + * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. + * Even better than compiling with -DZ_PREFIX would be to use configure to set + * this permanently in zconf.h using "./configure --zprefix". + */ +#ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ +# define Z_PREFIX_SET + +/* all linked symbols and init macros */ +# define _dist_code z__dist_code +# define _length_code z__length_code +# define _tr_align z__tr_align +# define _tr_flush_bits z__tr_flush_bits +# define _tr_flush_block z__tr_flush_block +# define _tr_init z__tr_init +# define _tr_stored_block z__tr_stored_block +# define _tr_tally z__tr_tally +# define adler32 z_adler32 +# define adler32_combine z_adler32_combine +# define adler32_combine64 z_adler32_combine64 +# define adler32_z z_adler32_z +# ifndef Z_SOLO +# define compress z_compress +# define compress2 z_compress2 +# define compressBound z_compressBound +# endif +# define crc32 z_crc32 +# define crc32_combine z_crc32_combine +# define crc32_combine64 z_crc32_combine64 +# define crc32_z z_crc32_z +# define deflate z_deflate +# define deflateBound z_deflateBound +# define deflateCopy z_deflateCopy +# define deflateEnd z_deflateEnd +# define deflateGetDictionary z_deflateGetDictionary +# define deflateInit z_deflateInit +# define deflateInit2 z_deflateInit2 +# define deflateInit2_ z_deflateInit2_ +# define deflateInit_ z_deflateInit_ +# define deflateParams z_deflateParams +# define deflatePending z_deflatePending +# define deflatePrime z_deflatePrime +# define deflateReset z_deflateReset +# define deflateResetKeep z_deflateResetKeep +# define deflateSetDictionary z_deflateSetDictionary +# define deflateSetHeader z_deflateSetHeader +# define deflateTune z_deflateTune +# define deflate_copyright z_deflate_copyright +# define get_crc_table z_get_crc_table +# ifndef Z_SOLO +# define gz_error z_gz_error +# define gz_intmax z_gz_intmax +# define gz_strwinerror z_gz_strwinerror +# define gzbuffer z_gzbuffer +# define gzclearerr z_gzclearerr +# define gzclose z_gzclose +# define gzclose_r z_gzclose_r +# define gzclose_w z_gzclose_w +# define gzdirect z_gzdirect +# define gzdopen z_gzdopen +# define gzeof z_gzeof +# define gzerror z_gzerror +# define gzflush z_gzflush +# define gzfread z_gzfread +# define gzfwrite z_gzfwrite +# define gzgetc z_gzgetc +# define gzgetc_ z_gzgetc_ +# define gzgets z_gzgets +# define gzoffset z_gzoffset +# define gzoffset64 z_gzoffset64 +# define gzopen z_gzopen +# define gzopen64 z_gzopen64 +# ifdef _WIN32 +# define gzopen_w z_gzopen_w +# endif +# define gzprintf z_gzprintf +# define gzputc z_gzputc +# define gzputs z_gzputs +# define gzread z_gzread +# define gzrewind z_gzrewind +# define gzseek z_gzseek +# define gzseek64 z_gzseek64 +# define gzsetparams z_gzsetparams +# define gztell z_gztell +# define gztell64 z_gztell64 +# define gzungetc z_gzungetc +# define gzvprintf z_gzvprintf +# define gzwrite z_gzwrite +# endif +# define inflate z_inflate +# define inflateBack z_inflateBack +# define inflateBackEnd z_inflateBackEnd +# define inflateBackInit z_inflateBackInit +# define inflateBackInit_ z_inflateBackInit_ +# define inflateCodesUsed z_inflateCodesUsed +# define inflateCopy z_inflateCopy +# define inflateEnd z_inflateEnd +# define inflateGetDictionary z_inflateGetDictionary +# define inflateGetHeader z_inflateGetHeader +# define inflateInit z_inflateInit +# define inflateInit2 z_inflateInit2 +# define inflateInit2_ z_inflateInit2_ +# define inflateInit_ z_inflateInit_ +# define inflateMark z_inflateMark +# define inflatePrime z_inflatePrime +# define inflateReset z_inflateReset +# define inflateReset2 z_inflateReset2 +# define inflateResetKeep z_inflateResetKeep +# define inflateSetDictionary z_inflateSetDictionary +# define inflateSync z_inflateSync +# define inflateSyncPoint z_inflateSyncPoint +# define inflateUndermine z_inflateUndermine +# define inflateValidate z_inflateValidate +# define inflate_copyright z_inflate_copyright +# define inflate_fast z_inflate_fast +# define inflate_table z_inflate_table +# ifndef Z_SOLO +# define uncompress z_uncompress +# define uncompress2 z_uncompress2 +# endif +# define zError z_zError +# ifndef Z_SOLO +# define zcalloc z_zcalloc +# define zcfree z_zcfree +# endif +# define zlibCompileFlags z_zlibCompileFlags +# define zlibVersion z_zlibVersion + +/* all zlib typedefs in zlib.h and zconf.h */ +# define Byte z_Byte +# define Bytef z_Bytef +# define alloc_func z_alloc_func +# define charf z_charf +# define free_func z_free_func +# ifndef Z_SOLO +# define gzFile z_gzFile +# endif +# define gz_header z_gz_header +# define gz_headerp z_gz_headerp +# define in_func z_in_func +# define intf z_intf +# define out_func z_out_func +# define uInt z_uInt +# define uIntf z_uIntf +# define uLong z_uLong +# define uLongf z_uLongf +# define voidp z_voidp +# define voidpc z_voidpc +# define voidpf z_voidpf + +/* all zlib structs in zlib.h and zconf.h */ +# define gz_header_s z_gz_header_s +# define internal_state z_internal_state + +#endif + +#if defined(__MSDOS__) && !defined(MSDOS) +# define MSDOS +#endif +#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) +# define OS2 +#endif +#if defined(_WINDOWS) && !defined(WINDOWS) +# define WINDOWS +#endif +#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) +# ifndef WIN32 +# define WIN32 +# endif +#endif +#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) +# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) +# ifndef SYS16BIT +# define SYS16BIT +# endif +# endif +#endif + +/* + * Compile with -DMAXSEG_64K if the alloc function cannot allocate more + * than 64k bytes at a time (needed on systems with 16-bit int). + */ +#ifdef SYS16BIT +# define MAXSEG_64K +#endif +#ifdef MSDOS +# define UNALIGNED_OK +#endif + +#ifdef __STDC_VERSION__ +# ifndef STDC +# define STDC +# endif +# if __STDC_VERSION__ >= 199901L +# ifndef STDC99 +# define STDC99 +# endif +# endif +#endif +#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) +# define STDC +#endif +#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) +# define STDC +#endif +#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) +# define STDC +#endif +#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) +# define STDC +#endif + +#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ +# define STDC +#endif + +#ifndef STDC +# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ +# define const /* note: need a more gentle solution here */ +# endif +#endif + +#if defined(ZLIB_CONST) && !defined(z_const) +# define z_const const +#else +# define z_const +#endif + +#ifdef Z_SOLO + typedef unsigned long z_size_t; +#else +# define z_longlong long long +# if defined(NO_SIZE_T) + typedef unsigned NO_SIZE_T z_size_t; +# elif defined(STDC) +# include + typedef size_t z_size_t; +# else + typedef unsigned long z_size_t; +# endif +# undef z_longlong +#endif + +/* Maximum value for memLevel in deflateInit2 */ +#ifndef MAX_MEM_LEVEL +# ifdef MAXSEG_64K +# define MAX_MEM_LEVEL 8 +# else +# define MAX_MEM_LEVEL 9 +# endif +#endif + +/* Maximum value for windowBits in deflateInit2 and inflateInit2. + * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files + * created by gzip. (Files created by minigzip can still be extracted by + * gzip.) + */ +#ifndef MAX_WBITS +# define MAX_WBITS 15 /* 32K LZ77 window */ +#endif + +/* The memory requirements for deflate are (in bytes): + (1 << (windowBits+2)) + (1 << (memLevel+9)) + that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) + plus a few kilobytes for small objects. For example, if you want to reduce + the default memory requirements from 256K to 128K, compile with + make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" + Of course this will generally degrade compression (there's no free lunch). + + The memory requirements for inflate are (in bytes) 1 << windowBits + that is, 32K for windowBits=15 (default value) plus about 7 kilobytes + for small objects. +*/ + + /* Type declarations */ + +#ifndef OF /* function prototypes */ +# ifdef STDC +# define OF(args) args +# else +# define OF(args) () +# endif +#endif + +#ifndef Z_ARG /* function prototypes for stdarg */ +# if defined(STDC) || defined(Z_HAVE_STDARG_H) +# define Z_ARG(args) args +# else +# define Z_ARG(args) () +# endif +#endif + +/* The following definitions for FAR are needed only for MSDOS mixed + * model programming (small or medium model with some far allocations). + * This was tested only with MSC; for other MSDOS compilers you may have + * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, + * just define FAR to be empty. + */ +#ifdef SYS16BIT +# if defined(M_I86SM) || defined(M_I86MM) + /* MSC small or medium model */ +# define SMALL_MEDIUM +# ifdef _MSC_VER +# define FAR _far +# else +# define FAR far +# endif +# endif +# if (defined(__SMALL__) || defined(__MEDIUM__)) + /* Turbo C small or medium model */ +# define SMALL_MEDIUM +# ifdef __BORLANDC__ +# define FAR _far +# else +# define FAR far +# endif +# endif +#endif + +#if defined(WINDOWS) || defined(WIN32) + /* If building or using zlib as a DLL, define ZLIB_DLL. + * This is not mandatory, but it offers a little performance increase. + */ +# ifdef ZLIB_DLL +# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) +# ifdef ZLIB_INTERNAL +# define ZEXTERN extern __declspec(dllexport) +# else +# define ZEXTERN extern __declspec(dllimport) +# endif +# endif +# endif /* ZLIB_DLL */ + /* If building or using zlib with the WINAPI/WINAPIV calling convention, + * define ZLIB_WINAPI. + * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. + */ +# ifdef ZLIB_WINAPI +# ifdef FAR +# undef FAR +# endif +# include + /* No need for _export, use ZLIB.DEF instead. */ + /* For complete Windows compatibility, use WINAPI, not __stdcall. */ +# define ZEXPORT WINAPI +# ifdef WIN32 +# define ZEXPORTVA WINAPIV +# else +# define ZEXPORTVA FAR CDECL +# endif +# endif +#endif + +#if defined (__BEOS__) +# ifdef ZLIB_DLL +# ifdef ZLIB_INTERNAL +# define ZEXPORT __declspec(dllexport) +# define ZEXPORTVA __declspec(dllexport) +# else +# define ZEXPORT __declspec(dllimport) +# define ZEXPORTVA __declspec(dllimport) +# endif +# endif +#endif + +#ifndef ZEXTERN +# define ZEXTERN extern +#endif +#ifndef ZEXPORT +# define ZEXPORT +#endif +#ifndef ZEXPORTVA +# define ZEXPORTVA +#endif + +#ifndef FAR +# define FAR +#endif + +#if !defined(__MACTYPES__) +typedef unsigned char Byte; /* 8 bits */ +#endif +typedef unsigned int uInt; /* 16 bits or more */ +typedef unsigned long uLong; /* 32 bits or more */ + +#ifdef SMALL_MEDIUM + /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ +# define Bytef Byte FAR +#else + typedef Byte FAR Bytef; +#endif +typedef char FAR charf; +typedef int FAR intf; +typedef uInt FAR uIntf; +typedef uLong FAR uLongf; + +#ifdef STDC + typedef void const *voidpc; + typedef void FAR *voidpf; + typedef void *voidp; +#else + typedef Byte const *voidpc; + typedef Byte FAR *voidpf; + typedef Byte *voidp; +#endif + +#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC) +# include +# if (UINT_MAX == 0xffffffffUL) +# define Z_U4 unsigned +# elif (ULONG_MAX == 0xffffffffUL) +# define Z_U4 unsigned long +# elif (USHRT_MAX == 0xffffffffUL) +# define Z_U4 unsigned short +# endif +#endif + +#ifdef Z_U4 + typedef Z_U4 z_crc_t; +#else + typedef unsigned long z_crc_t; +#endif + +#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ +# define Z_HAVE_UNISTD_H +#endif + +#ifdef HAVE_STDARG_H /* may be set to #if 1 by ./configure */ +# define Z_HAVE_STDARG_H +#endif + +#ifdef STDC +# ifndef Z_SOLO +# include /* for off_t */ +# endif +#endif + +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifndef Z_SOLO +# include /* for va_list */ +# endif +#endif + +#ifdef _WIN32 +# ifndef Z_SOLO +# include /* for wchar_t */ +# endif +#endif + +/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and + * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even + * though the former does not conform to the LFS document), but considering + * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as + * equivalently requesting no 64-bit operations + */ +#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1 +# undef _LARGEFILE64_SOURCE +#endif + +#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H) +# define Z_HAVE_UNISTD_H +#endif +#ifndef Z_SOLO +# if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) +# include /* for SEEK_*, off_t, and _LFS64_LARGEFILE */ +# ifdef VMS +# include /* for off_t */ +# endif +# ifndef z_off_t +# define z_off_t off_t +# endif +# endif +#endif + +#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0 +# define Z_LFS64 +#endif + +#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64) +# define Z_LARGE64 +#endif + +#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64) +# define Z_WANT64 +#endif + +#if !defined(SEEK_SET) && !defined(Z_SOLO) +# define SEEK_SET 0 /* Seek from beginning of file. */ +# define SEEK_CUR 1 /* Seek from current position. */ +# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ +#endif + +#ifndef z_off_t +# define z_off_t long +#endif + +#if !defined(_WIN32) && defined(Z_LARGE64) +# define z_off64_t off64_t +#else +# if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO) +# define z_off64_t __int64 +# else +# define z_off64_t z_off_t +# endif +#endif + +/* MVS linker does not support external names larger than 8 bytes */ +#if defined(__MVS__) + #pragma map(deflateInit_,"DEIN") + #pragma map(deflateInit2_,"DEIN2") + #pragma map(deflateEnd,"DEEND") + #pragma map(deflateBound,"DEBND") + #pragma map(inflateInit_,"ININ") + #pragma map(inflateInit2_,"ININ2") + #pragma map(inflateEnd,"INEND") + #pragma map(inflateSync,"INSY") + #pragma map(inflateSetDictionary,"INSEDI") + #pragma map(compressBound,"CMBND") + #pragma map(inflate_table,"INTABL") + #pragma map(inflate_fast,"INFA") + #pragma map(inflate_copyright,"INCOPY") +#endif + +#endif /* ZCONF_H */ diff --git a/Include/Libraries/zlib/zlib.h b/Include/Libraries/zlib/zlib.h new file mode 100644 index 0000000..f09cdaf --- /dev/null +++ b/Include/Libraries/zlib/zlib.h @@ -0,0 +1,1912 @@ +/* zlib.h -- interface of the 'zlib' general purpose compression library + version 1.2.11, January 15th, 2017 + + Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + + + The data format used by the zlib library is described by RFCs (Request for + Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950 + (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format). +*/ + +#ifndef ZLIB_H +#define ZLIB_H + +#include "zconf.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ZLIB_VERSION "1.2.11" +#define ZLIB_VERNUM 0x12b0 +#define ZLIB_VER_MAJOR 1 +#define ZLIB_VER_MINOR 2 +#define ZLIB_VER_REVISION 11 +#define ZLIB_VER_SUBREVISION 0 + +/* + The 'zlib' compression library provides in-memory compression and + decompression functions, including integrity checks of the uncompressed data. + This version of the library supports only one compression method (deflation) + but other algorithms will be added later and will have the same stream + interface. + + Compression can be done in a single step if the buffers are large enough, + or can be done by repeated calls of the compression function. In the latter + case, the application must provide more input and/or consume the output + (providing more output space) before each call. + + The compressed data format used by default by the in-memory functions is + the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped + around a deflate stream, which is itself documented in RFC 1951. + + The library also supports reading and writing files in gzip (.gz) format + with an interface similar to that of stdio using the functions that start + with "gz". The gzip format is different from the zlib format. gzip is a + gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. + + This library can optionally read and write gzip and raw deflate streams in + memory as well. + + The zlib format was designed to be compact and fast for use in memory + and on communications channels. The gzip format was designed for single- + file compression on file systems, has a larger header than zlib to maintain + directory information, and uses a different, slower check method than zlib. + + The library does not install any signal handler. The decoder checks + the consistency of the compressed data, so the library should never crash + even in the case of corrupted input. +*/ + +typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); +typedef void (*free_func) OF((voidpf opaque, voidpf address)); + +struct internal_state; + +typedef struct z_stream_s { + z_const Bytef *next_in; /* next input byte */ + uInt avail_in; /* number of bytes available at next_in */ + uLong total_in; /* total number of input bytes read so far */ + + Bytef *next_out; /* next output byte will go here */ + uInt avail_out; /* remaining free space at next_out */ + uLong total_out; /* total number of bytes output so far */ + + z_const char *msg; /* last error message, NULL if no error */ + struct internal_state FAR *state; /* not visible by applications */ + + alloc_func zalloc; /* used to allocate the internal state */ + free_func zfree; /* used to free the internal state */ + voidpf opaque; /* private data object passed to zalloc and zfree */ + + int data_type; /* best guess about the data type: binary or text + for deflate, or the decoding state for inflate */ + uLong adler; /* Adler-32 or CRC-32 value of the uncompressed data */ + uLong reserved; /* reserved for future use */ +} z_stream; + +typedef z_stream FAR *z_streamp; + +/* + gzip header information passed to and from zlib routines. See RFC 1952 + for more details on the meanings of these fields. +*/ +typedef struct gz_header_s { + int text; /* true if compressed data believed to be text */ + uLong time; /* modification time */ + int xflags; /* extra flags (not used when writing a gzip file) */ + int os; /* operating system */ + Bytef *extra; /* pointer to extra field or Z_NULL if none */ + uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ + uInt extra_max; /* space at extra (only when reading header) */ + Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ + uInt name_max; /* space at name (only when reading header) */ + Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ + uInt comm_max; /* space at comment (only when reading header) */ + int hcrc; /* true if there was or will be a header crc */ + int done; /* true when done reading gzip header (not used + when writing a gzip file) */ +} gz_header; + +typedef gz_header FAR *gz_headerp; + +/* + The application must update next_in and avail_in when avail_in has dropped + to zero. It must update next_out and avail_out when avail_out has dropped + to zero. The application must initialize zalloc, zfree and opaque before + calling the init function. All other fields are set by the compression + library and must not be updated by the application. + + The opaque value provided by the application will be passed as the first + parameter for calls of zalloc and zfree. This can be useful for custom + memory management. The compression library attaches no meaning to the + opaque value. + + zalloc must return Z_NULL if there is not enough memory for the object. + If zlib is used in a multi-threaded application, zalloc and zfree must be + thread safe. In that case, zlib is thread-safe. When zalloc and zfree are + Z_NULL on entry to the initialization function, they are set to internal + routines that use the standard library functions malloc() and free(). + + On 16-bit systems, the functions zalloc and zfree must be able to allocate + exactly 65536 bytes, but will not be required to allocate more than this if + the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers + returned by zalloc for objects of exactly 65536 bytes *must* have their + offset normalized to zero. The default allocation function provided by this + library ensures this (see zutil.c). To reduce memory requirements and avoid + any allocation of 64K objects, at the expense of compression ratio, compile + the library with -DMAX_WBITS=14 (see zconf.h). + + The fields total_in and total_out can be used for statistics or progress + reports. After compression, total_in holds the total size of the + uncompressed data and may be saved for use by the decompressor (particularly + if the decompressor wants to decompress everything in a single step). +*/ + + /* constants */ + +#define Z_NO_FLUSH 0 +#define Z_PARTIAL_FLUSH 1 +#define Z_SYNC_FLUSH 2 +#define Z_FULL_FLUSH 3 +#define Z_FINISH 4 +#define Z_BLOCK 5 +#define Z_TREES 6 +/* Allowed flush values; see deflate() and inflate() below for details */ + +#define Z_OK 0 +#define Z_STREAM_END 1 +#define Z_NEED_DICT 2 +#define Z_ERRNO (-1) +#define Z_STREAM_ERROR (-2) +#define Z_DATA_ERROR (-3) +#define Z_MEM_ERROR (-4) +#define Z_BUF_ERROR (-5) +#define Z_VERSION_ERROR (-6) +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + +#define Z_NO_COMPRESSION 0 +#define Z_BEST_SPEED 1 +#define Z_BEST_COMPRESSION 9 +#define Z_DEFAULT_COMPRESSION (-1) +/* compression levels */ + +#define Z_FILTERED 1 +#define Z_HUFFMAN_ONLY 2 +#define Z_RLE 3 +#define Z_FIXED 4 +#define Z_DEFAULT_STRATEGY 0 +/* compression strategy; see deflateInit2() below for details */ + +#define Z_BINARY 0 +#define Z_TEXT 1 +#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ +#define Z_UNKNOWN 2 +/* Possible values of the data_type field for deflate() */ + +#define Z_DEFLATED 8 +/* The deflate compression method (the only one supported in this version) */ + +#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ + +#define zlib_version zlibVersion() +/* for compatibility with versions < 1.0.2 */ + + + /* basic functions */ + +ZEXTERN const char * ZEXPORT zlibVersion OF((void)); +/* The application can compare zlibVersion and ZLIB_VERSION for consistency. + If the first character differs, the library code actually used is not + compatible with the zlib.h header file used by the application. This check + is automatically made by deflateInit and inflateInit. + */ + +/* +ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); + + Initializes the internal stream state for compression. The fields + zalloc, zfree and opaque must be initialized before by the caller. If + zalloc and zfree are set to Z_NULL, deflateInit updates them to use default + allocation functions. + + The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: + 1 gives best speed, 9 gives best compression, 0 gives no compression at all + (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION + requests a default compromise between speed and compression (currently + equivalent to level 6). + + deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if level is not a valid compression level, or + Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible + with the version assumed by the caller (ZLIB_VERSION). msg is set to null + if there is no error message. deflateInit does not perform any compression: + this will be done by deflate(). +*/ + + +ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); +/* + deflate compresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. deflate performs one or both of the + following actions: + + - Compress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in and avail_in are updated and + processing will resume at this point for the next call of deflate(). + + - Generate more output starting at next_out and update next_out and avail_out + accordingly. This action is forced if the parameter flush is non zero. + Forcing flush frequently degrades the compression ratio, so this parameter + should be set only when necessary. Some output may be provided even if + flush is zero. + + Before the call of deflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming more + output, and updating avail_in or avail_out accordingly; avail_out should + never be zero before the call. The application can consume the compressed + output when it wants, for example when the output buffer is full (avail_out + == 0), or after each call of deflate(). If deflate returns Z_OK and with + zero avail_out, it must be called again after making room in the output + buffer because there might be more output pending. See deflatePending(), + which can be used if desired to determine whether or not there is more ouput + in that case. + + Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to + decide how much data to accumulate before producing output, in order to + maximize compression. + + If the parameter flush is set to Z_SYNC_FLUSH, all pending output is + flushed to the output buffer and the output is aligned on a byte boundary, so + that the decompressor can get all input data available so far. (In + particular avail_in is zero after the call if enough output space has been + provided before the call.) Flushing may degrade compression for some + compression algorithms and so it should be used only when necessary. This + completes the current deflate block and follows it with an empty stored block + that is three bits plus filler bits to the next byte, followed by four bytes + (00 00 ff ff). + + If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the + output buffer, but the output is not aligned to a byte boundary. All of the + input data so far will be available to the decompressor, as for Z_SYNC_FLUSH. + This completes the current deflate block and follows it with an empty fixed + codes block that is 10 bits long. This assures that enough bytes are output + in order for the decompressor to finish the block before the empty fixed + codes block. + + If flush is set to Z_BLOCK, a deflate block is completed and emitted, as + for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to + seven bits of the current block are held to be written as the next byte after + the next deflate block is completed. In this case, the decompressor may not + be provided enough bits at this point in order to complete decompression of + the data provided so far to the compressor. It may need to wait for the next + block to be emitted. This is for advanced applications that need to control + the emission of deflate blocks. + + If flush is set to Z_FULL_FLUSH, all output is flushed as with + Z_SYNC_FLUSH, and the compression state is reset so that decompression can + restart from this point if previous compressed data has been damaged or if + random access is desired. Using Z_FULL_FLUSH too often can seriously degrade + compression. + + If deflate returns with avail_out == 0, this function must be called again + with the same value of the flush parameter and more output space (updated + avail_out), until the flush is complete (deflate returns with non-zero + avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that + avail_out is greater than six to avoid repeated flush markers due to + avail_out == 0 on return. + + If the parameter flush is set to Z_FINISH, pending input is processed, + pending output is flushed and deflate returns with Z_STREAM_END if there was + enough output space. If deflate returns with Z_OK or Z_BUF_ERROR, this + function must be called again with Z_FINISH and more output space (updated + avail_out) but no more input data, until it returns with Z_STREAM_END or an + error. After deflate has returned Z_STREAM_END, the only possible operations + on the stream are deflateReset or deflateEnd. + + Z_FINISH can be used in the first deflate call after deflateInit if all the + compression is to be done in a single step. In order to complete in one + call, avail_out must be at least the value returned by deflateBound (see + below). Then deflate is guaranteed to return Z_STREAM_END. If not enough + output space is provided, deflate will not return Z_STREAM_END, and it must + be called again as described above. + + deflate() sets strm->adler to the Adler-32 checksum of all input read + so far (that is, total_in bytes). If a gzip stream is being generated, then + strm->adler will be the CRC-32 checksum of the input read so far. (See + deflateInit2 below.) + + deflate() may update strm->data_type if it can make a good guess about + the input data type (Z_BINARY or Z_TEXT). If in doubt, the data is + considered binary. This field is only for information purposes and does not + affect the compression algorithm in any manner. + + deflate() returns Z_OK if some progress has been made (more input + processed or more output produced), Z_STREAM_END if all input has been + consumed and all output has been produced (only when flush is set to + Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example + if next_in or next_out was Z_NULL or the state was inadvertently written over + by the application), or Z_BUF_ERROR if no progress is possible (for example + avail_in or avail_out was zero). Note that Z_BUF_ERROR is not fatal, and + deflate() can be called again with more input and more output space to + continue compressing. +*/ + + +ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending + output. + + deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the + stream state was inconsistent, Z_DATA_ERROR if the stream was freed + prematurely (some input or output was discarded). In the error case, msg + may be set but then points to a static string (which must not be + deallocated). +*/ + + +/* +ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); + + Initializes the internal stream state for decompression. The fields + next_in, avail_in, zalloc, zfree and opaque must be initialized before by + the caller. In the current version of inflate, the provided input is not + read or consumed. The allocation of a sliding window will be deferred to + the first call of inflate (if the decompression does not complete on the + first call). If zalloc and zfree are set to Z_NULL, inflateInit updates + them to use default allocation functions. + + inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller, or Z_STREAM_ERROR if the parameters are + invalid, such as a null pointer to the structure. msg is set to null if + there is no error message. inflateInit does not perform any decompression. + Actual decompression will be done by inflate(). So next_in, and avail_in, + next_out, and avail_out are unused and unchanged. The current + implementation of inflateInit() does not process any header information -- + that is deferred until inflate() is called. +*/ + + +ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); +/* + inflate decompresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. inflate performs one or both of the + following actions: + + - Decompress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), then next_in and avail_in are updated + accordingly, and processing will resume at this point for the next call of + inflate(). + + - Generate more output starting at next_out and update next_out and avail_out + accordingly. inflate() provides as much output as possible, until there is + no more input data or no more space in the output buffer (see below about + the flush parameter). + + Before the call of inflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming more + output, and updating the next_* and avail_* values accordingly. If the + caller of inflate() does not provide both available input and available + output space, it is possible that there will be no progress made. The + application can consume the uncompressed output when it wants, for example + when the output buffer is full (avail_out == 0), or after each call of + inflate(). If inflate returns Z_OK and with zero avail_out, it must be + called again after making room in the output buffer because there might be + more output pending. + + The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH, + Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much + output as possible to the output buffer. Z_BLOCK requests that inflate() + stop if and when it gets to the next deflate block boundary. When decoding + the zlib or gzip format, this will cause inflate() to return immediately + after the header and before the first block. When doing a raw inflate, + inflate() will go ahead and process the first block, and will return when it + gets to the end of that block, or when it runs out of data. + + The Z_BLOCK option assists in appending to or combining deflate streams. + To assist in this, on return inflate() always sets strm->data_type to the + number of unused bits in the last byte taken from strm->next_in, plus 64 if + inflate() is currently decoding the last block in the deflate stream, plus + 128 if inflate() returned immediately after decoding an end-of-block code or + decoding the complete header up to just before the first byte of the deflate + stream. The end-of-block will not be indicated until all of the uncompressed + data from that block has been written to strm->next_out. The number of + unused bits may in general be greater than seven, except when bit 7 of + data_type is set, in which case the number of unused bits will be less than + eight. data_type is set as noted here every time inflate() returns for all + flush options, and so can be used to determine the amount of currently + consumed input in bits. + + The Z_TREES option behaves as Z_BLOCK does, but it also returns when the + end of each deflate block header is reached, before any actual data in that + block is decoded. This allows the caller to determine the length of the + deflate block header for later use in random access within a deflate block. + 256 is added to the value of strm->data_type when inflate() returns + immediately after reaching the end of the deflate block header. + + inflate() should normally be called until it returns Z_STREAM_END or an + error. However if all decompression is to be performed in a single step (a + single call of inflate), the parameter flush should be set to Z_FINISH. In + this case all pending input is processed and all pending output is flushed; + avail_out must be large enough to hold all of the uncompressed data for the + operation to complete. (The size of the uncompressed data may have been + saved by the compressor for this purpose.) The use of Z_FINISH is not + required to perform an inflation in one step. However it may be used to + inform inflate that a faster approach can be used for the single inflate() + call. Z_FINISH also informs inflate to not maintain a sliding window if the + stream completes, which reduces inflate's memory footprint. If the stream + does not complete, either because not all of the stream is provided or not + enough output space is provided, then a sliding window will be allocated and + inflate() can be called again to continue the operation as if Z_NO_FLUSH had + been used. + + In this implementation, inflate() always flushes as much output as + possible to the output buffer, and always uses the faster approach on the + first call. So the effects of the flush parameter in this implementation are + on the return value of inflate() as noted below, when inflate() returns early + when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of + memory for a sliding window when Z_FINISH is used. + + If a preset dictionary is needed after this call (see inflateSetDictionary + below), inflate sets strm->adler to the Adler-32 checksum of the dictionary + chosen by the compressor and returns Z_NEED_DICT; otherwise it sets + strm->adler to the Adler-32 checksum of all output produced so far (that is, + total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described + below. At the end of the stream, inflate() checks that its computed Adler-32 + checksum is equal to that saved by the compressor and returns Z_STREAM_END + only if the checksum is correct. + + inflate() can decompress and check either zlib-wrapped or gzip-wrapped + deflate data. The header type is detected automatically, if requested when + initializing with inflateInit2(). Any information contained in the gzip + header is not retained unless inflateGetHeader() is used. When processing + gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output + produced so far. The CRC-32 is checked against the gzip trailer, as is the + uncompressed length, modulo 2^32. + + inflate() returns Z_OK if some progress has been made (more input processed + or more output produced), Z_STREAM_END if the end of the compressed data has + been reached and all uncompressed output has been produced, Z_NEED_DICT if a + preset dictionary is needed at this point, Z_DATA_ERROR if the input data was + corrupted (input stream not conforming to the zlib format or incorrect check + value, in which case strm->msg points to a string with a more specific + error), Z_STREAM_ERROR if the stream structure was inconsistent (for example + next_in or next_out was Z_NULL, or the state was inadvertently written over + by the application), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR + if no progress was possible or if there was not enough room in the output + buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and + inflate() can be called again with more input and more output space to + continue decompressing. If Z_DATA_ERROR is returned, the application may + then call inflateSync() to look for a good compression block if a partial + recovery of the data is to be attempted. +*/ + + +ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending + output. + + inflateEnd returns Z_OK if success, or Z_STREAM_ERROR if the stream state + was inconsistent. +*/ + + + /* Advanced functions */ + +/* + The following functions are needed only in some special applications. +*/ + +/* +ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, + int level, + int method, + int windowBits, + int memLevel, + int strategy)); + + This is another version of deflateInit with more compression options. The + fields next_in, zalloc, zfree and opaque must be initialized before by the + caller. + + The method parameter is the compression method. It must be Z_DEFLATED in + this version of the library. + + The windowBits parameter is the base two logarithm of the window size + (the size of the history buffer). It should be in the range 8..15 for this + version of the library. Larger values of this parameter result in better + compression at the expense of memory usage. The default value is 15 if + deflateInit is used instead. + + For the current implementation of deflate(), a windowBits value of 8 (a + window size of 256 bytes) is not supported. As a result, a request for 8 + will result in 9 (a 512-byte window). In that case, providing 8 to + inflateInit2() will result in an error when the zlib header with 9 is + checked against the initialization of inflate(). The remedy is to not use 8 + with deflateInit2() with this initialization, or at least in that case use 9 + with inflateInit2(). + + windowBits can also be -8..-15 for raw deflate. In this case, -windowBits + determines the window size. deflate() will then generate raw deflate data + with no zlib header or trailer, and will not compute a check value. + + windowBits can also be greater than 15 for optional gzip encoding. Add + 16 to windowBits to write a simple gzip header and trailer around the + compressed data instead of a zlib wrapper. The gzip header will have no + file name, no extra data, no comment, no modification time (set to zero), no + header crc, and the operating system will be set to the appropriate value, + if the operating system was determined at compile time. If a gzip stream is + being written, strm->adler is a CRC-32 instead of an Adler-32. + + For raw deflate or gzip encoding, a request for a 256-byte window is + rejected as invalid, since only the zlib header provides a means of + transmitting the window size to the decompressor. + + The memLevel parameter specifies how much memory should be allocated + for the internal compression state. memLevel=1 uses minimum memory but is + slow and reduces compression ratio; memLevel=9 uses maximum memory for + optimal speed. The default value is 8. See zconf.h for total memory usage + as a function of windowBits and memLevel. + + The strategy parameter is used to tune the compression algorithm. Use the + value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a + filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no + string match), or Z_RLE to limit match distances to one (run-length + encoding). Filtered data consists mostly of small values with a somewhat + random distribution. In this case, the compression algorithm is tuned to + compress them better. The effect of Z_FILTERED is to force more Huffman + coding and less string matching; it is somewhat intermediate between + Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as + fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The + strategy parameter only affects the compression ratio but not the + correctness of the compressed output even if it is not set appropriately. + Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler + decoder for special applications. + + deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid + method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is + incompatible with the version assumed by the caller (ZLIB_VERSION). msg is + set to null if there is no error message. deflateInit2 does not perform any + compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the compression dictionary from the given byte sequence + without producing any compressed output. When using the zlib format, this + function must be called immediately after deflateInit, deflateInit2 or + deflateReset, and before any call of deflate. When doing raw deflate, this + function must be called either before any call of deflate, or immediately + after the completion of a deflate block, i.e. after all input has been + consumed and all output has been delivered when using any of the flush + options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH. The + compressor and decompressor must use exactly the same dictionary (see + inflateSetDictionary). + + The dictionary should consist of strings (byte sequences) that are likely + to be encountered later in the data to be compressed, with the most commonly + used strings preferably put towards the end of the dictionary. Using a + dictionary is most useful when the data to be compressed is short and can be + predicted with good accuracy; the data can then be compressed better than + with the default empty dictionary. + + Depending on the size of the compression data structures selected by + deflateInit or deflateInit2, a part of the dictionary may in effect be + discarded, for example if the dictionary is larger than the window size + provided in deflateInit or deflateInit2. Thus the strings most likely to be + useful should be put at the end of the dictionary, not at the front. In + addition, the current implementation of deflate will use at most the window + size minus 262 bytes of the provided dictionary. + + Upon return of this function, strm->adler is set to the Adler-32 value + of the dictionary; the decompressor may later use this value to determine + which dictionary has been used by the compressor. (The Adler-32 value + applies to the whole dictionary even if only a subset of the dictionary is + actually used by the compressor.) If a raw deflate was requested, then the + Adler-32 value is not computed and strm->adler is not set. + + deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a + parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is + inconsistent (for example if deflate has already been called for this stream + or if not at a block boundary for raw deflate). deflateSetDictionary does + not perform any compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateGetDictionary OF((z_streamp strm, + Bytef *dictionary, + uInt *dictLength)); +/* + Returns the sliding dictionary being maintained by deflate. dictLength is + set to the number of bytes in the dictionary, and that many bytes are copied + to dictionary. dictionary must have enough space, where 32768 bytes is + always enough. If deflateGetDictionary() is called with dictionary equal to + Z_NULL, then only the dictionary length is returned, and nothing is copied. + Similary, if dictLength is Z_NULL, then it is not set. + + deflateGetDictionary() may return a length less than the window size, even + when more than the window size in input has been provided. It may return up + to 258 bytes less in that case, due to how zlib's implementation of deflate + manages the sliding window and lookahead for matches, where matches can be + up to 258 bytes long. If the application needs the last window-size bytes of + input, then that would need to be saved by the application outside of zlib. + + deflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the + stream state is inconsistent. +*/ + +ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when several compression strategies will be + tried, for example when there are several ways of pre-processing the input + data with a filter. The streams that will be discarded should then be freed + by calling deflateEnd. Note that deflateCopy duplicates the internal + compression state which can be quite large, so this strategy is slow and can + consume lots of memory. + + deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being Z_NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); +/* + This function is equivalent to deflateEnd followed by deflateInit, but + does not free and reallocate the internal compression state. The stream + will leave the compression level and any other attributes that may have been + set unchanged. + + deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). +*/ + +ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, + int level, + int strategy)); +/* + Dynamically update the compression level and compression strategy. The + interpretation of level and strategy is as in deflateInit2(). This can be + used to switch between compression and straight copy of the input data, or + to switch to a different kind of input data requiring a different strategy. + If the compression approach (which is a function of the level) or the + strategy is changed, and if any input has been consumed in a previous + deflate() call, then the input available so far is compressed with the old + level and strategy using deflate(strm, Z_BLOCK). There are three approaches + for the compression levels 0, 1..3, and 4..9 respectively. The new level + and strategy will take effect at the next call of deflate(). + + If a deflate(strm, Z_BLOCK) is performed by deflateParams(), and it does + not have enough output space to complete, then the parameter change will not + take effect. In this case, deflateParams() can be called again with the + same parameters and more output space to try again. + + In order to assure a change in the parameters on the first try, the + deflate stream should be flushed using deflate() with Z_BLOCK or other flush + request until strm.avail_out is not zero, before calling deflateParams(). + Then no more input data should be provided before the deflateParams() call. + If this is done, the old level and strategy will be applied to the data + compressed before deflateParams(), and the new level and strategy will be + applied to the the data compressed after deflateParams(). + + deflateParams returns Z_OK on success, Z_STREAM_ERROR if the source stream + state was inconsistent or if a parameter was invalid, or Z_BUF_ERROR if + there was not enough output space to complete the compression of the + available input data before a change in the strategy or approach. Note that + in the case of a Z_BUF_ERROR, the parameters are not changed. A return + value of Z_BUF_ERROR is not fatal, in which case deflateParams() can be + retried with more output space. +*/ + +ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, + int good_length, + int max_lazy, + int nice_length, + int max_chain)); +/* + Fine tune deflate's internal compression parameters. This should only be + used by someone who understands the algorithm used by zlib's deflate for + searching for the best matching string, and even then only by the most + fanatic optimizer trying to squeeze out the last compressed bit for their + specific input data. Read the deflate.c source code for the meaning of the + max_lazy, good_length, nice_length, and max_chain parameters. + + deflateTune() can be called after deflateInit() or deflateInit2(), and + returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. + */ + +ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, + uLong sourceLen)); +/* + deflateBound() returns an upper bound on the compressed size after + deflation of sourceLen bytes. It must be called after deflateInit() or + deflateInit2(), and after deflateSetHeader(), if used. This would be used + to allocate an output buffer for deflation in a single pass, and so would be + called before deflate(). If that first deflate() call is provided the + sourceLen input bytes, an output buffer allocated to the size returned by + deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed + to return Z_STREAM_END. Note that it is possible for the compressed size to + be larger than the value returned by deflateBound() if flush options other + than Z_FINISH or Z_NO_FLUSH are used. +*/ + +ZEXTERN int ZEXPORT deflatePending OF((z_streamp strm, + unsigned *pending, + int *bits)); +/* + deflatePending() returns the number of bytes and bits of output that have + been generated, but not yet provided in the available output. The bytes not + provided would be due to the available output space having being consumed. + The number of bits of output not provided are between 0 and 7, where they + await more bits to join them in order to fill out a full byte. If pending + or bits are Z_NULL, then those values are not set. + + deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. + */ + +ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + deflatePrime() inserts bits in the deflate output stream. The intent + is that this function is used to start off the deflate output with the bits + leftover from a previous deflate stream when appending to it. As such, this + function can only be used for raw deflate, and must be used before the first + deflate() call after a deflateInit2() or deflateReset(). bits must be less + than or equal to 16, and that many of the least significant bits of value + will be inserted in the output. + + deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough + room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the + source stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, + gz_headerp head)); +/* + deflateSetHeader() provides gzip header information for when a gzip + stream is requested by deflateInit2(). deflateSetHeader() may be called + after deflateInit2() or deflateReset() and before the first call of + deflate(). The text, time, os, extra field, name, and comment information + in the provided gz_header structure are written to the gzip header (xflag is + ignored -- the extra flags are set according to the compression level). The + caller must assure that, if not Z_NULL, name and comment are terminated with + a zero byte, and that if extra is not Z_NULL, that extra_len bytes are + available there. If hcrc is true, a gzip header crc is included. Note that + the current versions of the command-line version of gzip (up through version + 1.3.x) do not support header crc's, and will report that it is a "multi-part + gzip file" and give up. + + If deflateSetHeader is not used, the default gzip header has text false, + the time set to zero, and os set to 255, with no extra, name, or comment + fields. The gzip header is returned to the default state by deflateReset(). + + deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, + int windowBits)); + + This is another version of inflateInit with an extra parameter. The + fields next_in, avail_in, zalloc, zfree and opaque must be initialized + before by the caller. + + The windowBits parameter is the base two logarithm of the maximum window + size (the size of the history buffer). It should be in the range 8..15 for + this version of the library. The default value is 15 if inflateInit is used + instead. windowBits must be greater than or equal to the windowBits value + provided to deflateInit2() while compressing, or it must be equal to 15 if + deflateInit2() was not used. If a compressed stream with a larger window + size is given as input, inflate() will return with the error code + Z_DATA_ERROR instead of trying to allocate a larger window. + + windowBits can also be zero to request that inflate use the window size in + the zlib header of the compressed stream. + + windowBits can also be -8..-15 for raw inflate. In this case, -windowBits + determines the window size. inflate() will then process raw deflate data, + not looking for a zlib or gzip header, not generating a check value, and not + looking for any check values for comparison at the end of the stream. This + is for use with other formats that use the deflate compressed data format + such as zip. Those formats provide their own check values. If a custom + format is developed using the raw deflate format for compressed data, it is + recommended that a check value such as an Adler-32 or a CRC-32 be applied to + the uncompressed data as is done in the zlib, gzip, and zip formats. For + most applications, the zlib format should be used as is. Note that comments + above on the use in deflateInit2() applies to the magnitude of windowBits. + + windowBits can also be greater than 15 for optional gzip decoding. Add + 32 to windowBits to enable zlib and gzip decoding with automatic header + detection, or add 16 to decode only the gzip format (the zlib format will + return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a + CRC-32 instead of an Adler-32. Unlike the gunzip utility and gzread() (see + below), inflate() will not automatically decode concatenated gzip streams. + inflate() will return Z_STREAM_END at the end of the gzip stream. The state + would need to be reset to continue decoding a subsequent gzip stream. + + inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller, or Z_STREAM_ERROR if the parameters are + invalid, such as a null pointer to the structure. msg is set to null if + there is no error message. inflateInit2 does not perform any decompression + apart from possibly reading the zlib header if present: actual decompression + will be done by inflate(). (So next_in and avail_in may be modified, but + next_out and avail_out are unused and unchanged.) The current implementation + of inflateInit2() does not process any header information -- that is + deferred until inflate() is called. +*/ + +ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the decompression dictionary from the given uncompressed byte + sequence. This function must be called immediately after a call of inflate, + if that call returned Z_NEED_DICT. The dictionary chosen by the compressor + can be determined from the Adler-32 value returned by that call of inflate. + The compressor and decompressor must use exactly the same dictionary (see + deflateSetDictionary). For raw inflate, this function can be called at any + time to set the dictionary. If the provided dictionary is smaller than the + window and there is already data in the window, then the provided dictionary + will amend what's there. The application must insure that the dictionary + that was used for compression is provided. + + inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a + parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is + inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the + expected one (incorrect Adler-32 value). inflateSetDictionary does not + perform any decompression: this will be done by subsequent calls of + inflate(). +*/ + +ZEXTERN int ZEXPORT inflateGetDictionary OF((z_streamp strm, + Bytef *dictionary, + uInt *dictLength)); +/* + Returns the sliding dictionary being maintained by inflate. dictLength is + set to the number of bytes in the dictionary, and that many bytes are copied + to dictionary. dictionary must have enough space, where 32768 bytes is + always enough. If inflateGetDictionary() is called with dictionary equal to + Z_NULL, then only the dictionary length is returned, and nothing is copied. + Similary, if dictLength is Z_NULL, then it is not set. + + inflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the + stream state is inconsistent. +*/ + +ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); +/* + Skips invalid compressed data until a possible full flush point (see above + for the description of deflate with Z_FULL_FLUSH) can be found, or until all + available input is skipped. No output is provided. + + inflateSync searches for a 00 00 FF FF pattern in the compressed data. + All full flush points have this pattern, but not all occurrences of this + pattern are full flush points. + + inflateSync returns Z_OK if a possible full flush point has been found, + Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point + has been found, or Z_STREAM_ERROR if the stream structure was inconsistent. + In the success case, the application may save the current current value of + total_in which indicates where valid compressed data was found. In the + error case, the application may repeatedly call inflateSync, providing more + input each time, until success or end of the input data. +*/ + +ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when randomly accessing a large stream. The + first pass through the stream can periodically record the inflate state, + allowing restarting inflate at those points when randomly accessing the + stream. + + inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being Z_NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); +/* + This function is equivalent to inflateEnd followed by inflateInit, + but does not free and reallocate the internal decompression state. The + stream will keep attributes that may have been set by inflateInit2. + + inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). +*/ + +ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm, + int windowBits)); +/* + This function is the same as inflateReset, but it also permits changing + the wrap and window size requests. The windowBits parameter is interpreted + the same as it is for inflateInit2. If the window size is changed, then the + memory allocated for the window is freed, and the window will be reallocated + by inflate() if needed. + + inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL), or if + the windowBits parameter is invalid. +*/ + +ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + This function inserts bits in the inflate input stream. The intent is + that this function is used to start inflating at a bit position in the + middle of a byte. The provided bits will be used before any bytes are used + from next_in. This function should only be used with raw inflate, and + should be used before the first inflate() call after inflateInit2() or + inflateReset(). bits must be less than or equal to 16, and that many of the + least significant bits of value will be inserted in the input. + + If bits is negative, then the input stream bit buffer is emptied. Then + inflatePrime() can be called again to put bits in the buffer. This is used + to clear out bits leftover after feeding inflate a block description prior + to feeding inflate codes. + + inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm)); +/* + This function returns two values, one in the lower 16 bits of the return + value, and the other in the remaining upper bits, obtained by shifting the + return value down 16 bits. If the upper value is -1 and the lower value is + zero, then inflate() is currently decoding information outside of a block. + If the upper value is -1 and the lower value is non-zero, then inflate is in + the middle of a stored block, with the lower value equaling the number of + bytes from the input remaining to copy. If the upper value is not -1, then + it is the number of bits back from the current bit position in the input of + the code (literal or length/distance pair) currently being processed. In + that case the lower value is the number of bytes already emitted for that + code. + + A code is being processed if inflate is waiting for more input to complete + decoding of the code, or if it has completed decoding but is waiting for + more output space to write the literal or match data. + + inflateMark() is used to mark locations in the input data for random + access, which may be at bit positions, and to note those cases where the + output of a code may span boundaries of random access blocks. The current + location in the input stream can be determined from avail_in and data_type + as noted in the description for the Z_BLOCK flush parameter for inflate. + + inflateMark returns the value noted above, or -65536 if the provided + source stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, + gz_headerp head)); +/* + inflateGetHeader() requests that gzip header information be stored in the + provided gz_header structure. inflateGetHeader() may be called after + inflateInit2() or inflateReset(), and before the first call of inflate(). + As inflate() processes the gzip stream, head->done is zero until the header + is completed, at which time head->done is set to one. If a zlib stream is + being decoded, then head->done is set to -1 to indicate that there will be + no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be + used to force inflate() to return immediately after header processing is + complete and before any actual data is decompressed. + + The text, time, xflags, and os fields are filled in with the gzip header + contents. hcrc is set to true if there is a header CRC. (The header CRC + was valid if done is set to one.) If extra is not Z_NULL, then extra_max + contains the maximum number of bytes to write to extra. Once done is true, + extra_len contains the actual extra field length, and extra contains the + extra field, or that field truncated if extra_max is less than extra_len. + If name is not Z_NULL, then up to name_max characters are written there, + terminated with a zero unless the length is greater than name_max. If + comment is not Z_NULL, then up to comm_max characters are written there, + terminated with a zero unless the length is greater than comm_max. When any + of extra, name, or comment are not Z_NULL and the respective field is not + present in the header, then that field is set to Z_NULL to signal its + absence. This allows the use of deflateSetHeader() with the returned + structure to duplicate the header. However if those fields are set to + allocated memory, then the application will need to save those pointers + elsewhere so that they can be eventually freed. + + If inflateGetHeader is not used, then the header information is simply + discarded. The header is always checked for validity, including the header + CRC if present. inflateReset() will reset the process to discard the header + information. The application would need to call inflateGetHeader() again to + retrieve the header from the next gzip stream. + + inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, + unsigned char FAR *window)); + + Initialize the internal stream state for decompression using inflateBack() + calls. The fields zalloc, zfree and opaque in strm must be initialized + before the call. If zalloc and zfree are Z_NULL, then the default library- + derived memory allocation routines are used. windowBits is the base two + logarithm of the window size, in the range 8..15. window is a caller + supplied buffer of that size. Except for special applications where it is + assured that deflate was used with small window sizes, windowBits must be 15 + and a 32K byte window must be supplied to be able to decompress general + deflate streams. + + See inflateBack() for the usage of these routines. + + inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of + the parameters are invalid, Z_MEM_ERROR if the internal state could not be + allocated, or Z_VERSION_ERROR if the version of the library does not match + the version of the header file. +*/ + +typedef unsigned (*in_func) OF((void FAR *, + z_const unsigned char FAR * FAR *)); +typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); + +ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, + in_func in, void FAR *in_desc, + out_func out, void FAR *out_desc)); +/* + inflateBack() does a raw inflate with a single call using a call-back + interface for input and output. This is potentially more efficient than + inflate() for file i/o applications, in that it avoids copying between the + output and the sliding window by simply making the window itself the output + buffer. inflate() can be faster on modern CPUs when used with large + buffers. inflateBack() trusts the application to not change the output + buffer passed by the output function, at least until inflateBack() returns. + + inflateBackInit() must be called first to allocate the internal state + and to initialize the state with the user-provided window buffer. + inflateBack() may then be used multiple times to inflate a complete, raw + deflate stream with each call. inflateBackEnd() is then called to free the + allocated state. + + A raw deflate stream is one with no zlib or gzip header or trailer. + This routine would normally be used in a utility that reads zip or gzip + files and writes out uncompressed files. The utility would decode the + header and process the trailer on its own, hence this routine expects only + the raw deflate stream to decompress. This is different from the default + behavior of inflate(), which expects a zlib header and trailer around the + deflate stream. + + inflateBack() uses two subroutines supplied by the caller that are then + called by inflateBack() for input and output. inflateBack() calls those + routines until it reads a complete deflate stream and writes out all of the + uncompressed data, or until it encounters an error. The function's + parameters and return types are defined above in the in_func and out_func + typedefs. inflateBack() will call in(in_desc, &buf) which should return the + number of bytes of provided input, and a pointer to that input in buf. If + there is no input available, in() must return zero -- buf is ignored in that + case -- and inflateBack() will return a buffer error. inflateBack() will + call out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. + out() should return zero on success, or non-zero on failure. If out() + returns non-zero, inflateBack() will return with an error. Neither in() nor + out() are permitted to change the contents of the window provided to + inflateBackInit(), which is also the buffer that out() uses to write from. + The length written by out() will be at most the window size. Any non-zero + amount of input may be provided by in(). + + For convenience, inflateBack() can be provided input on the first call by + setting strm->next_in and strm->avail_in. If that input is exhausted, then + in() will be called. Therefore strm->next_in must be initialized before + calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called + immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in + must also be initialized, and then if strm->avail_in is not zero, input will + initially be taken from strm->next_in[0 .. strm->avail_in - 1]. + + The in_desc and out_desc parameters of inflateBack() is passed as the + first parameter of in() and out() respectively when they are called. These + descriptors can be optionally used to pass any information that the caller- + supplied in() and out() functions need to do their job. + + On return, inflateBack() will set strm->next_in and strm->avail_in to + pass back any unused input that was provided by the last in() call. The + return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR + if in() or out() returned an error, Z_DATA_ERROR if there was a format error + in the deflate stream (in which case strm->msg is set to indicate the nature + of the error), or Z_STREAM_ERROR if the stream was not properly initialized. + In the case of Z_BUF_ERROR, an input or output error can be distinguished + using strm->next_in which will be Z_NULL only if in() returned an error. If + strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning + non-zero. (in() will always be called before out(), so strm->next_in is + assured to be defined if out() returns non-zero.) Note that inflateBack() + cannot return Z_OK. +*/ + +ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); +/* + All memory allocated by inflateBackInit() is freed. + + inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream + state was inconsistent. +*/ + +ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); +/* Return flags indicating compile-time options. + + Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: + 1.0: size of uInt + 3.2: size of uLong + 5.4: size of voidpf (pointer) + 7.6: size of z_off_t + + Compiler, assembler, and debug options: + 8: ZLIB_DEBUG + 9: ASMV or ASMINF -- use ASM code + 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention + 11: 0 (reserved) + + One-time table building (smaller code, but not thread-safe if true): + 12: BUILDFIXED -- build static block decoding tables when needed + 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed + 14,15: 0 (reserved) + + Library content (indicates missing functionality): + 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking + deflate code when not needed) + 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect + and decode gzip streams (to avoid linking crc code) + 18-19: 0 (reserved) + + Operation variations (changes in library functionality): + 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate + 21: FASTEST -- deflate algorithm with only one, lowest compression level + 22,23: 0 (reserved) + + The sprintf variant used by gzprintf (zero is best): + 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format + 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! + 26: 0 = returns value, 1 = void -- 1 means inferred string length returned + + Remainder: + 27-31: 0 (reserved) + */ + +#ifndef Z_SOLO + + /* utility functions */ + +/* + The following utility functions are implemented on top of the basic + stream-oriented functions. To simplify the interface, some default options + are assumed (compression level and memory usage, standard memory allocation + functions). The source code of these utility functions can be modified if + you need special options. +*/ + +ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Compresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total size + of the destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed data. compress() is equivalent to compress2() with a level + parameter of Z_DEFAULT_COMPRESSION. + + compress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer. +*/ + +ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen, + int level)); +/* + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed data. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ + +ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); +/* + compressBound() returns an upper bound on the compressed size after + compress() or compress2() on sourceLen bytes. It would be used before a + compress() or compress2() call to allocate the destination buffer. +*/ + +ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Decompresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total size + of the destination buffer, which must be large enough to hold the entire + uncompressed data. (The size of the uncompressed data must have been saved + previously by the compressor and transmitted to the decompressor by some + mechanism outside the scope of this compression library.) Upon exit, destLen + is the actual size of the uncompressed data. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. In + the case where there is not enough room, uncompress() will fill the output + buffer with the uncompressed data up to that point. +*/ + +ZEXTERN int ZEXPORT uncompress2 OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong *sourceLen)); +/* + Same as uncompress, except that sourceLen is a pointer, where the + length of the source is *sourceLen. On return, *sourceLen is the number of + source bytes consumed. +*/ + + /* gzip file access functions */ + +/* + This library supports reading and writing files in gzip (.gz) format with + an interface similar to that of stdio, using the functions that start with + "gz". The gzip format is different from the zlib format. gzip is a gzip + wrapper, documented in RFC 1952, wrapped around a deflate stream. +*/ + +typedef struct gzFile_s *gzFile; /* semi-opaque gzip file descriptor */ + +/* +ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); + + Opens a gzip (.gz) file for reading or writing. The mode parameter is as + in fopen ("rb" or "wb") but can also include a compression level ("wb9") or + a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only + compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F' + for fixed code compression as in "wb9F". (See the description of + deflateInit2 for more information about the strategy parameter.) 'T' will + request transparent writing or appending with no compression and not using + the gzip format. + + "a" can be used instead of "w" to request that the gzip stream that will + be written be appended to the file. "+" will result in an error, since + reading and writing to the same gzip file is not supported. The addition of + "x" when writing will create the file exclusively, which fails if the file + already exists. On systems that support it, the addition of "e" when + reading or writing will set the flag to close the file on an execve() call. + + These functions, as well as gzip, will read and decode a sequence of gzip + streams in a file. The append function of gzopen() can be used to create + such a file. (Also see gzflush() for another way to do this.) When + appending, gzopen does not test whether the file begins with a gzip stream, + nor does it look for the end of the gzip streams to begin appending. gzopen + will simply append a gzip stream to the existing file. + + gzopen can be used to read a file which is not in gzip format; in this + case gzread will directly read from the file without decompression. When + reading, this will be detected automatically by looking for the magic two- + byte gzip header. + + gzopen returns NULL if the file could not be opened, if there was + insufficient memory to allocate the gzFile state, or if an invalid mode was + specified (an 'r', 'w', or 'a' was not provided, or '+' was provided). + errno can be checked to determine if the reason gzopen failed was that the + file could not be opened. +*/ + +ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); +/* + gzdopen associates a gzFile with the file descriptor fd. File descriptors + are obtained from calls like open, dup, creat, pipe or fileno (if the file + has been previously opened with fopen). The mode parameter is as in gzopen. + + The next call of gzclose on the returned gzFile will also close the file + descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor + fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, + mode);. The duplicated descriptor should be saved to avoid a leak, since + gzdopen does not close fd if it fails. If you are using fileno() to get the + file descriptor from a FILE *, then you will have to use dup() to avoid + double-close()ing the file descriptor. Both gzclose() and fclose() will + close the associated file descriptor, so they need to have different file + descriptors. + + gzdopen returns NULL if there was insufficient memory to allocate the + gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not + provided, or '+' was provided), or if fd is -1. The file descriptor is not + used until the next gz* read, write, seek, or close operation, so gzdopen + will not detect if fd is invalid (unless fd is -1). +*/ + +ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size)); +/* + Set the internal buffer size used by this library's functions. The + default buffer size is 8192 bytes. This function must be called after + gzopen() or gzdopen(), and before any other calls that read or write the + file. The buffer memory allocation is always deferred to the first read or + write. Three times that size in buffer space is allocated. A larger buffer + size of, for example, 64K or 128K bytes will noticeably increase the speed + of decompression (reading). + + The new buffer size also affects the maximum length for gzprintf(). + + gzbuffer() returns 0 on success, or -1 on failure, such as being called + too late. +*/ + +ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); +/* + Dynamically update the compression level or strategy. See the description + of deflateInit2 for the meaning of these parameters. Previously provided + data is flushed before the parameter change. + + gzsetparams returns Z_OK if success, Z_STREAM_ERROR if the file was not + opened for writing, Z_ERRNO if there is an error writing the flushed data, + or Z_MEM_ERROR if there is a memory allocation error. +*/ + +ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); +/* + Reads the given number of uncompressed bytes from the compressed file. If + the input file is not in gzip format, gzread copies the given number of + bytes into the buffer directly from the file. + + After reaching the end of a gzip stream in the input, gzread will continue + to read, looking for another gzip stream. Any number of gzip streams may be + concatenated in the input file, and will all be decompressed by gzread(). + If something other than a gzip stream is encountered after a gzip stream, + that remaining trailing garbage is ignored (and no error is returned). + + gzread can be used to read a gzip file that is being concurrently written. + Upon reaching the end of the input, gzread will return with the available + data. If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then + gzclearerr can be used to clear the end of file indicator in order to permit + gzread to be tried again. Z_OK indicates that a gzip stream was completed + on the last gzread. Z_BUF_ERROR indicates that the input file ended in the + middle of a gzip stream. Note that gzread does not return -1 in the event + of an incomplete gzip stream. This error is deferred until gzclose(), which + will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip + stream. Alternatively, gzerror can be used before gzclose to detect this + case. + + gzread returns the number of uncompressed bytes actually read, less than + len for end of file, or -1 for error. If len is too large to fit in an int, + then nothing is read, -1 is returned, and the error state is set to + Z_STREAM_ERROR. +*/ + +ZEXTERN z_size_t ZEXPORT gzfread OF((voidp buf, z_size_t size, z_size_t nitems, + gzFile file)); +/* + Read up to nitems items of size size from file to buf, otherwise operating + as gzread() does. This duplicates the interface of stdio's fread(), with + size_t request and return types. If the library defines size_t, then + z_size_t is identical to size_t. If not, then z_size_t is an unsigned + integer type that can contain a pointer. + + gzfread() returns the number of full items read of size size, or zero if + the end of the file was reached and a full item could not be read, or if + there was an error. gzerror() must be consulted if zero is returned in + order to determine if there was an error. If the multiplication of size and + nitems overflows, i.e. the product does not fit in a z_size_t, then nothing + is read, zero is returned, and the error state is set to Z_STREAM_ERROR. + + In the event that the end of file is reached and only a partial item is + available at the end, i.e. the remaining uncompressed data length is not a + multiple of size, then the final partial item is nevetheless read into buf + and the end-of-file flag is set. The length of the partial item read is not + provided, but could be inferred from the result of gztell(). This behavior + is the same as the behavior of fread() implementations in common libraries, + but it prevents the direct use of gzfread() to read a concurrently written + file, reseting and retrying on end-of-file, when size is not 1. +*/ + +ZEXTERN int ZEXPORT gzwrite OF((gzFile file, + voidpc buf, unsigned len)); +/* + Writes the given number of uncompressed bytes into the compressed file. + gzwrite returns the number of uncompressed bytes written or 0 in case of + error. +*/ + +ZEXTERN z_size_t ZEXPORT gzfwrite OF((voidpc buf, z_size_t size, + z_size_t nitems, gzFile file)); +/* + gzfwrite() writes nitems items of size size from buf to file, duplicating + the interface of stdio's fwrite(), with size_t request and return types. If + the library defines size_t, then z_size_t is identical to size_t. If not, + then z_size_t is an unsigned integer type that can contain a pointer. + + gzfwrite() returns the number of full items written of size size, or zero + if there was an error. If the multiplication of size and nitems overflows, + i.e. the product does not fit in a z_size_t, then nothing is written, zero + is returned, and the error state is set to Z_STREAM_ERROR. +*/ + +ZEXTERN int ZEXPORTVA gzprintf Z_ARG((gzFile file, const char *format, ...)); +/* + Converts, formats, and writes the arguments to the compressed file under + control of the format string, as in fprintf. gzprintf returns the number of + uncompressed bytes actually written, or a negative zlib error code in case + of error. The number of uncompressed bytes written is limited to 8191, or + one less than the buffer size given to gzbuffer(). The caller should assure + that this limit is not exceeded. If it is exceeded, then gzprintf() will + return an error (0) with nothing written. In this case, there may also be a + buffer overflow with unpredictable consequences, which is possible only if + zlib was compiled with the insecure functions sprintf() or vsprintf() + because the secure snprintf() or vsnprintf() functions were not available. + This can be determined using zlibCompileFlags(). +*/ + +ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); +/* + Writes the given null-terminated string to the compressed file, excluding + the terminating null character. + + gzputs returns the number of characters written, or -1 in case of error. +*/ + +ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); +/* + Reads bytes from the compressed file until len-1 characters are read, or a + newline character is read and transferred to buf, or an end-of-file + condition is encountered. If any characters are read or if len == 1, the + string is terminated with a null character. If no characters are read due + to an end-of-file or len < 1, then the buffer is left untouched. + + gzgets returns buf which is a null-terminated string, or it returns NULL + for end-of-file or in case of error. If there was an error, the contents at + buf are indeterminate. +*/ + +ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); +/* + Writes c, converted to an unsigned char, into the compressed file. gzputc + returns the value that was written, or -1 in case of error. +*/ + +ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); +/* + Reads one byte from the compressed file. gzgetc returns this byte or -1 + in case of end of file or error. This is implemented as a macro for speed. + As such, it does not do all of the checking the other functions do. I.e. + it does not check to see if file is NULL, nor whether the structure file + points to has been clobbered or not. +*/ + +ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); +/* + Push one character back onto the stream to be read as the first character + on the next read. At least one character of push-back is allowed. + gzungetc() returns the character pushed, or -1 on failure. gzungetc() will + fail if c is -1, and may fail if a character has been pushed but not read + yet. If gzungetc is used immediately after gzopen or gzdopen, at least the + output buffer size of pushed characters is allowed. (See gzbuffer above.) + The pushed character will be discarded if the stream is repositioned with + gzseek() or gzrewind(). +*/ + +ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); +/* + Flushes all pending output into the compressed file. The parameter flush + is as in the deflate() function. The return value is the zlib error number + (see function gzerror below). gzflush is only permitted when writing. + + If the flush parameter is Z_FINISH, the remaining data is written and the + gzip stream is completed in the output. If gzwrite() is called again, a new + gzip stream will be started in the output. gzread() is able to read such + concatenated gzip streams. + + gzflush should be called only when strictly necessary because it will + degrade compression if called too often. +*/ + +/* +ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, + z_off_t offset, int whence)); + + Sets the starting position for the next gzread or gzwrite on the given + compressed file. The offset represents a number of bytes in the + uncompressed data stream. The whence parameter is defined as in lseek(2); + the value SEEK_END is not supported. + + If the file is opened for reading, this function is emulated but can be + extremely slow. If the file is opened for writing, only forward seeks are + supported; gzseek then compresses a sequence of zeroes up to the new + starting position. + + gzseek returns the resulting offset location as measured in bytes from + the beginning of the uncompressed stream, or -1 in case of error, in + particular if the file is opened for writing and the new starting position + would be before the current position. +*/ + +ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); +/* + Rewinds the given file. This function is supported only for reading. + + gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) +*/ + +/* +ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); + + Returns the starting position for the next gzread or gzwrite on the given + compressed file. This position represents a number of bytes in the + uncompressed data stream, and is zero when starting, even if appending or + reading a gzip stream from the middle of a file using gzdopen(). + + gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) +*/ + +/* +ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file)); + + Returns the current offset in the file being read or written. This offset + includes the count of bytes that precede the gzip stream, for example when + appending or when using gzdopen() for reading. When reading, the offset + does not include as yet unused buffered input. This information can be used + for a progress indicator. On error, gzoffset() returns -1. +*/ + +ZEXTERN int ZEXPORT gzeof OF((gzFile file)); +/* + Returns true (1) if the end-of-file indicator has been set while reading, + false (0) otherwise. Note that the end-of-file indicator is set only if the + read tried to go past the end of the input, but came up short. Therefore, + just like feof(), gzeof() may return false even if there is no more data to + read, in the event that the last read request was for the exact number of + bytes remaining in the input file. This will happen if the input file size + is an exact multiple of the buffer size. + + If gzeof() returns true, then the read functions will return no more data, + unless the end-of-file indicator is reset by gzclearerr() and the input file + has grown since the previous end of file was detected. +*/ + +ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); +/* + Returns true (1) if file is being copied directly while reading, or false + (0) if file is a gzip stream being decompressed. + + If the input file is empty, gzdirect() will return true, since the input + does not contain a gzip stream. + + If gzdirect() is used immediately after gzopen() or gzdopen() it will + cause buffers to be allocated to allow reading the file to determine if it + is a gzip file. Therefore if gzbuffer() is used, it should be called before + gzdirect(). + + When writing, gzdirect() returns true (1) if transparent writing was + requested ("wT" for the gzopen() mode), or false (0) otherwise. (Note: + gzdirect() is not needed when writing. Transparent writing must be + explicitly requested, so the application already knows the answer. When + linking statically, using gzdirect() will include all of the zlib code for + gzip file reading and decompression, which may not be desired.) +*/ + +ZEXTERN int ZEXPORT gzclose OF((gzFile file)); +/* + Flushes all pending output if necessary, closes the compressed file and + deallocates the (de)compression state. Note that once file is closed, you + cannot call gzerror with file, since its structures have been deallocated. + gzclose must not be called more than once on the same file, just as free + must not be called more than once on the same allocation. + + gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a + file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the + last read ended in the middle of a gzip stream, or Z_OK on success. +*/ + +ZEXTERN int ZEXPORT gzclose_r OF((gzFile file)); +ZEXTERN int ZEXPORT gzclose_w OF((gzFile file)); +/* + Same as gzclose(), but gzclose_r() is only for use when reading, and + gzclose_w() is only for use when writing or appending. The advantage to + using these instead of gzclose() is that they avoid linking in zlib + compression or decompression code that is not used when only reading or only + writing respectively. If gzclose() is used, then both compression and + decompression code will be included the application when linking to a static + zlib library. +*/ + +ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); +/* + Returns the error message for the last error which occurred on the given + compressed file. errnum is set to zlib error number. If an error occurred + in the file system and not in the compression library, errnum is set to + Z_ERRNO and the application may consult errno to get the exact error code. + + The application must not modify the returned string. Future calls to + this function may invalidate the previously returned string. If file is + closed, then the string previously returned by gzerror will no longer be + available. + + gzerror() should be used to distinguish errors from end-of-file for those + functions above that do not distinguish those cases in their return values. +*/ + +ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); +/* + Clears the error and end-of-file flags for file. This is analogous to the + clearerr() function in stdio. This is useful for continuing to read a gzip + file that is being written concurrently. +*/ + +#endif /* !Z_SOLO */ + + /* checksum functions */ + +/* + These functions are not related to compression but are exported + anyway because they might be useful in applications using the compression + library. +*/ + +ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); +/* + Update a running Adler-32 checksum with the bytes buf[0..len-1] and + return the updated checksum. If buf is Z_NULL, this function returns the + required initial value for the checksum. + + An Adler-32 checksum is almost as reliable as a CRC-32 but can be computed + much faster. + + Usage example: + + uLong adler = adler32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + adler = adler32(adler, buffer, length); + } + if (adler != original_adler) error(); +*/ + +ZEXTERN uLong ZEXPORT adler32_z OF((uLong adler, const Bytef *buf, + z_size_t len)); +/* + Same as adler32(), but with a size_t length. +*/ + +/* +ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, + z_off_t len2)); + + Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 + and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for + each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of + seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. Note + that the z_off_t type (like off_t) is a signed integer. If len2 is + negative, the result has no meaning or utility. +*/ + +ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); +/* + Update a running CRC-32 with the bytes buf[0..len-1] and return the + updated CRC-32. If buf is Z_NULL, this function returns the required + initial value for the crc. Pre- and post-conditioning (one's complement) is + performed within this function so it shouldn't be done by the application. + + Usage example: + + uLong crc = crc32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + crc = crc32(crc, buffer, length); + } + if (crc != original_crc) error(); +*/ + +ZEXTERN uLong ZEXPORT crc32_z OF((uLong adler, const Bytef *buf, + z_size_t len)); +/* + Same as crc32(), but with a size_t length. +*/ + +/* +ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); + + Combine two CRC-32 check values into one. For two sequences of bytes, + seq1 and seq2 with lengths len1 and len2, CRC-32 check values were + calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 + check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and + len2. +*/ + + + /* various hacks, don't look :) */ + +/* deflateInit and inflateInit are macros to allow checking the zlib version + * and the compiler's view of z_stream: + */ +ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, + int windowBits, int memLevel, + int strategy, const char *version, + int stream_size)); +ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, + unsigned char FAR *window, + const char *version, + int stream_size)); +#ifdef Z_PREFIX_SET +# define z_deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) +# define z_inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) +# define z_deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ + (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) +# define z_inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ + (int)sizeof(z_stream)) +# define z_inflateBackInit(strm, windowBits, window) \ + inflateBackInit_((strm), (windowBits), (window), \ + ZLIB_VERSION, (int)sizeof(z_stream)) +#else +# define deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) +# define inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) +# define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ + (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) +# define inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ + (int)sizeof(z_stream)) +# define inflateBackInit(strm, windowBits, window) \ + inflateBackInit_((strm), (windowBits), (window), \ + ZLIB_VERSION, (int)sizeof(z_stream)) +#endif + +#ifndef Z_SOLO + +/* gzgetc() macro and its supporting function and exposed data structure. Note + * that the real internal state is much larger than the exposed structure. + * This abbreviated structure exposes just enough for the gzgetc() macro. The + * user should not mess with these exposed elements, since their names or + * behavior could change in the future, perhaps even capriciously. They can + * only be used by the gzgetc() macro. You have been warned. + */ +struct gzFile_s { + unsigned have; + unsigned char *next; + z_off64_t pos; +}; +ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file)); /* backward compatibility */ +#ifdef Z_PREFIX_SET +# undef z_gzgetc +# define z_gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) +#else +# define gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) +#endif + +/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or + * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if + * both are true, the application gets the *64 functions, and the regular + * functions are changed to 64 bits) -- in case these are set on systems + * without large file support, _LFS64_LARGEFILE must also be true + */ +#ifdef Z_LARGE64 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); + ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t)); +#endif + +#if !defined(ZLIB_INTERNAL) && defined(Z_WANT64) +# ifdef Z_PREFIX_SET +# define z_gzopen z_gzopen64 +# define z_gzseek z_gzseek64 +# define z_gztell z_gztell64 +# define z_gzoffset z_gzoffset64 +# define z_adler32_combine z_adler32_combine64 +# define z_crc32_combine z_crc32_combine64 +# else +# define gzopen gzopen64 +# define gzseek gzseek64 +# define gztell gztell64 +# define gzoffset gzoffset64 +# define adler32_combine adler32_combine64 +# define crc32_combine crc32_combine64 +# endif +# ifndef Z_LARGE64 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int)); + ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); +# endif +#else + ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *)); + ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int)); + ZEXTERN z_off_t ZEXPORT gztell OF((gzFile)); + ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); +#endif + +#else /* Z_SOLO */ + + ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); + +#endif /* !Z_SOLO */ + +/* undocumented functions */ +ZEXTERN const char * ZEXPORT zError OF((int)); +ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp)); +ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table OF((void)); +ZEXTERN int ZEXPORT inflateUndermine OF((z_streamp, int)); +ZEXTERN int ZEXPORT inflateValidate OF((z_streamp, int)); +ZEXTERN unsigned long ZEXPORT inflateCodesUsed OF ((z_streamp)); +ZEXTERN int ZEXPORT inflateResetKeep OF((z_streamp)); +ZEXTERN int ZEXPORT deflateResetKeep OF((z_streamp)); +#if (defined(_WIN32) || defined(__CYGWIN__)) && !defined(Z_SOLO) +ZEXTERN gzFile ZEXPORT gzopen_w OF((const wchar_t *path, + const char *mode)); +#endif +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifndef Z_SOLO +ZEXTERN int ZEXPORTVA gzvprintf Z_ARG((gzFile file, + const char *format, + va_list va)); +# endif +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* ZLIB_H */ diff --git a/Include/Libraries/zlib/zutil.h b/Include/Libraries/zlib/zutil.h new file mode 100644 index 0000000..b079ea6 --- /dev/null +++ b/Include/Libraries/zlib/zutil.h @@ -0,0 +1,271 @@ +/* zutil.h -- internal interface and configuration of the compression library + * Copyright (C) 1995-2016 Jean-loup Gailly, Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* @(#) $Id$ */ + +#ifndef ZUTIL_H +#define ZUTIL_H + +#ifdef HAVE_HIDDEN +# define ZLIB_INTERNAL __attribute__((visibility ("hidden"))) +#else +# define ZLIB_INTERNAL +#endif + +#include "zlib.h" + +#if defined(STDC) && !defined(Z_SOLO) +# if !(defined(_WIN32_WCE) && defined(_MSC_VER)) +# include +# endif +# include +# include +#endif + +#ifdef Z_SOLO + typedef long ptrdiff_t; /* guess -- will be caught if guess is wrong */ +#endif + +#ifndef local +# define local static +#endif +/* since "static" is used to mean two completely different things in C, we + define "local" for the non-static meaning of "static", for readability + (compile with -Dlocal if your debugger can't find static symbols) */ + +typedef unsigned char uch; +typedef uch FAR uchf; +typedef unsigned short ush; +typedef ush FAR ushf; +typedef unsigned long ulg; + +extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ +/* (size given to avoid silly warnings with Visual C++) */ + +#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] + +#define ERR_RETURN(strm,err) \ + return (strm->msg = ERR_MSG(err), (err)) +/* To be used only when the state is known to be valid */ + + /* common constants */ + +#ifndef DEF_WBITS +# define DEF_WBITS MAX_WBITS +#endif +/* default windowBits for decompression. MAX_WBITS is for compression only */ + +#if MAX_MEM_LEVEL >= 8 +# define DEF_MEM_LEVEL 8 +#else +# define DEF_MEM_LEVEL MAX_MEM_LEVEL +#endif +/* default memLevel */ + +#define STORED_BLOCK 0 +#define STATIC_TREES 1 +#define DYN_TREES 2 +/* The three kinds of block type */ + +#define MIN_MATCH 3 +#define MAX_MATCH 258 +/* The minimum and maximum match lengths */ + +#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ + + /* target dependencies */ + +#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32)) +# define OS_CODE 0x00 +# ifndef Z_SOLO +# if defined(__TURBOC__) || defined(__BORLANDC__) +# if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__)) + /* Allow compilation with ANSI keywords only enabled */ + void _Cdecl farfree( void *block ); + void *_Cdecl farmalloc( unsigned long nbytes ); +# else +# include +# endif +# else /* MSC or DJGPP */ +# include +# endif +# endif +#endif + +#ifdef AMIGA +# define OS_CODE 1 +#endif + +#if defined(VAXC) || defined(VMS) +# define OS_CODE 2 +# define F_OPEN(name, mode) \ + fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512") +#endif + +#ifdef __370__ +# if __TARGET_LIB__ < 0x20000000 +# define OS_CODE 4 +# elif __TARGET_LIB__ < 0x40000000 +# define OS_CODE 11 +# else +# define OS_CODE 8 +# endif +#endif + +#if defined(ATARI) || defined(atarist) +# define OS_CODE 5 +#endif + +#ifdef OS2 +# define OS_CODE 6 +# if defined(M_I86) && !defined(Z_SOLO) +# include +# endif +#endif + +#if defined(MACOS) || defined(TARGET_OS_MAC) +# define OS_CODE 7 +# ifndef Z_SOLO +# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os +# include /* for fdopen */ +# else +# ifndef fdopen +# define fdopen(fd,mode) NULL /* No fdopen() */ +# endif +# endif +# endif +#endif + +#ifdef __acorn +# define OS_CODE 13 +#endif + +#if defined(WIN32) && !defined(__CYGWIN__) +# define OS_CODE 10 +#endif + +#ifdef _BEOS_ +# define OS_CODE 16 +#endif + +#ifdef __TOS_OS400__ +# define OS_CODE 18 +#endif + +#ifdef __APPLE__ +# define OS_CODE 19 +#endif + +#if defined(_BEOS_) || defined(RISCOS) +# define fdopen(fd,mode) NULL /* No fdopen() */ +#endif + +#if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined __INTERIX +# if defined(_WIN32_WCE) +# define fdopen(fd,mode) NULL /* No fdopen() */ +# ifndef _PTRDIFF_T_DEFINED + typedef int ptrdiff_t; +# define _PTRDIFF_T_DEFINED +# endif +# else +# define fdopen(fd,type) _fdopen(fd,type) +# endif +#endif + +#if defined(__BORLANDC__) && !defined(MSDOS) + #pragma warn -8004 + #pragma warn -8008 + #pragma warn -8066 +#endif + +/* provide prototypes for these when building zlib without LFS */ +#if !defined(_WIN32) && \ + (!defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0) + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); +#endif + + /* common defaults */ + +#ifndef OS_CODE +# define OS_CODE 3 /* assume Unix */ +#endif + +#ifndef F_OPEN +# define F_OPEN(name, mode) fopen((name), (mode)) +#endif + + /* functions */ + +#if defined(pyr) || defined(Z_SOLO) +# define NO_MEMCPY +#endif +#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__) + /* Use our own functions for small and medium model with MSC <= 5.0. + * You may have to use the same strategy for Borland C (untested). + * The __SC__ check is for Symantec. + */ +# define NO_MEMCPY +#endif +#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY) +# define HAVE_MEMCPY +#endif +#ifdef HAVE_MEMCPY +# ifdef SMALL_MEDIUM /* MSDOS small or medium model */ +# define zmemcpy _fmemcpy +# define zmemcmp _fmemcmp +# define zmemzero(dest, len) _fmemset(dest, 0, len) +# else +# define zmemcpy memcpy +# define zmemcmp memcmp +# define zmemzero(dest, len) memset(dest, 0, len) +# endif +#else + void ZLIB_INTERNAL zmemcpy OF((Bytef* dest, const Bytef* source, uInt len)); + int ZLIB_INTERNAL zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len)); + void ZLIB_INTERNAL zmemzero OF((Bytef* dest, uInt len)); +#endif + +/* Diagnostic functions */ +#ifdef ZLIB_DEBUG +# include + extern int ZLIB_INTERNAL z_verbose; + extern void ZLIB_INTERNAL z_error OF((char *m)); +# define Assert(cond,msg) {if(!(cond)) z_error(msg);} +# define Trace(x) {if (z_verbose>=0) fprintf x ;} +# define Tracev(x) {if (z_verbose>0) fprintf x ;} +# define Tracevv(x) {if (z_verbose>1) fprintf x ;} +# define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;} +# define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;} +#else +# define Assert(cond,msg) +# define Trace(x) +# define Tracev(x) +# define Tracevv(x) +# define Tracec(c,x) +# define Tracecv(c,x) +#endif + +#ifndef Z_SOLO + voidpf ZLIB_INTERNAL zcalloc OF((voidpf opaque, unsigned items, + unsigned size)); + void ZLIB_INTERNAL zcfree OF((voidpf opaque, voidpf ptr)); +#endif + +#define ZALLOC(strm, items, size) \ + (*((strm)->zalloc))((strm)->opaque, (items), (size)) +#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) +#define TRY_FREE(s, p) {if (p) ZFREE(s, p);} + +/* Reverse the bytes in a 32-bit value */ +#define ZSWAP32(q) ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ + (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) + +#endif /* ZUTIL_H */ diff --git a/Include/Model/Classes/NMR_KeyStore.h b/Include/Model/Classes/NMR_KeyStore.h new file mode 100644 index 0000000..68049f9 --- /dev/null +++ b/Include/Model/Classes/NMR_KeyStore.h @@ -0,0 +1,107 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_KeyStore.h defines the KeyStore Class. A keystore is an in memory representation of the 3MF file keystore. + +--*/ + +#ifndef __NMR_KEYSTORE +#define __NMR_KEYSTORE + +#include +#include +#include +#include +#include "Common/NMR_Types.h" +#include "Common/NMR_SecureContentTypes.h" +#include "Common/NMR_UUID.h" + +namespace NMR { + class CKeyStoreConsumer; + using PKeyStoreConsumer = std::shared_ptr; + class CKeyStoreResourceDataGroup; + using PKeyStoreResourceDataGroup = std::shared_ptr; + class CKeyStoreResourceData; + using PKeyStoreResourceData = std::shared_ptr; + class CKeyStoreAccessRight; + using PKeyStoreAccessRight = std::shared_ptr; + + class CPackageModelPath; + using PPackageModelPath = std::shared_ptr; + + class CKeyStore { + private: + PUUID m_UUID; + + std::vector m_Consumers; + std::map m_ConsumerRefs; + + std::vector m_ResourceDataGroups; + std::map m_ResourceDataGroupsRefs; + + std::vector m_ResourceDatas; + std::map m_ResourceDataRefs; + + std::mutex mtx; + public: + CKeyStore(); + ~CKeyStore(); + PUUID getUUID(); + void setUUID(PUUID uuid); + void addConsumer(PKeyStoreConsumer const &consumer); + nfUint64 getConsumerCount() const; + PKeyStoreConsumer getConsumer(nfUint64 index) const; + PKeyStoreConsumer findConsumerById(std::string id); + void removeConsumer(NMR::PKeyStoreConsumer consumer); + + nfUint64 getResourceDataGroupCount() const; + PKeyStoreResourceDataGroup getResourceDataGroup(nfUint64 index) const; + void addResourceDataGroup(PKeyStoreResourceDataGroup const &dataGroup); + PKeyStoreResourceDataGroup findResourceDataGroupByResourceDataPath(PPackageModelPath const & rdPath); + void removeResourceDataGroup(PKeyStoreResourceDataGroup rdg); + + nfUint64 addResourceData(PKeyStoreResourceData const & rd); + void removeResourceData(NMR::PKeyStoreResourceData const & rd); + nfUint64 getResourceDataCount(); + PKeyStoreResourceData getResourceData(nfUint64 index) const; + PKeyStoreResourceData findResourceData(PPackageModelPath const & path); + + std::vector getResourceDataByGroup(PKeyStoreResourceDataGroup const & rdg) const; + + PKeyStoreResourceDataGroup findResourceDataGroupByResourceDataPath(std::string const & rdPath); + PKeyStoreResourceData findResourceData(std::string const & path); + + bool empty() const; + protected: + void clearAll(); + }; + + typedef std::shared_ptr PKeyStore; +} + +#endif diff --git a/Include/Model/Classes/NMR_KeyStoreAccessRight.h b/Include/Model/Classes/NMR_KeyStoreAccessRight.h new file mode 100644 index 0000000..d6edf2a --- /dev/null +++ b/Include/Model/Classes/NMR_KeyStoreAccessRight.h @@ -0,0 +1,61 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_KeyStoreAccessRight.h defines the KeyStoreAccessRight Class. A accessright is an in memory representation of the 3MF keystore resource data accessright. + +--*/ + +#ifndef __NMR_KEYSTOREACCESSRIGHT +#define __NMR_KEYSTOREACCESSRIGHT + +#include +#include +#include "Common/NMR_Types.h" +#include "Model/Classes/NMR_KeyStoreConsumer.h" +namespace NMR { + class CKeyStoreAccessRight { + private: + PKeyStoreConsumer m_pConsumer; + eKeyStoreWrapAlgorithm m_eAlgorithm; + eKeyStoreMaskGenerationFunction m_eMgf; + eKeyStoreMessageDigest m_eDigest; + std::vector m_rgCipherValue; + public: + CKeyStoreAccessRight(PKeyStoreConsumer const & consumer, eKeyStoreWrapAlgorithm const algorithm, eKeyStoreMaskGenerationFunction const mgf, eKeyStoreMessageDigest const digest, std::vector const & cipherValue); + PKeyStoreConsumer getConsumer() const; + eKeyStoreWrapAlgorithm getAlgorithm() const; + eKeyStoreMaskGenerationFunction getMgf() const; + eKeyStoreMessageDigest getDigest() const; + std::vector const & getCipherValue() const; + void setCipherValue(std::vector const & cv); + nfBool isNew() const; + }; + + typedef std::shared_ptr PKeyStoreAccessRight; +} +#endif diff --git a/Include/Model/Classes/NMR_KeyStoreCEKParams.h b/Include/Model/Classes/NMR_KeyStoreCEKParams.h new file mode 100644 index 0000000..becdeb0 --- /dev/null +++ b/Include/Model/Classes/NMR_KeyStoreCEKParams.h @@ -0,0 +1,86 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_KeyStoreDecryptRight.h defines the KeyStoreDecryptRight Class. A decryptright is an in memory representation of the 3MF keystore resource data decrypright. + +--*/ + +#ifndef __NMR_KEYSTORECEKPARAMS +#define __NMR_KEYSTORECEKPARAMS + +#include +#include +#include +#include "Common/NMR_Types.h" +#include "Model/Classes/NMR_KeyStoreConsumer.h" +namespace NMR { + + class CKeyStoreCEKParams { + protected: + eKeyStoreEncryptAlgorithm m_eAlgorithm; + nfBool m_bCompression; + std::vector m_rgIv, m_rgTag, m_rgAad; + nfUint64 m_nDescriptor; + public: + CKeyStoreCEKParams(nfBool const & compression, + eKeyStoreEncryptAlgorithm const & encryptionAlgorithm, + std::vector const & iv, + std::vector const & tag, + std::vector const & aad, + nfUint64 descriptor); + + eKeyStoreEncryptAlgorithm getEncryptionAlgorithm() const; + nfBool isCompressed() const; + std::vector const & getInitVector() const; + std::vector const & getAuthTag() const; + std::vector const & getAddAuthData() const; + nfUint64 getDescriptor() const; + + void setAuthTag(std::vector const & buf); + void setAddAuthData(std::vector const & buf); + }; + + typedef std::shared_ptr PKeyStoreCEKParams; + + class CKeyStoreContentEncryptionParams: public CKeyStoreCEKParams { + std::vector m_rgKey; + public: + CKeyStoreContentEncryptionParams(nfBool const & compression, + eKeyStoreEncryptAlgorithm const & encryptionAlgorithm, + std::vector const & key, + std::vector const & iv, + std::vector const & tag, + std::vector const & aad, + nfUint64 descriptor); + + std::vector const & getKey() const; + }; + + typedef std::shared_ptr PCKeyStoreContentEncryptionParams; +} +#endif \ No newline at end of file diff --git a/Include/Model/Classes/NMR_KeyStoreConsumer.h b/Include/Model/Classes/NMR_KeyStoreConsumer.h new file mode 100644 index 0000000..577e7e8 --- /dev/null +++ b/Include/Model/Classes/NMR_KeyStoreConsumer.h @@ -0,0 +1,64 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_KeyStoreConsumer.h defines the KeyStore Consumer Class. A consumer is an in memory representation of the 3MF file KeyStore Consumer. + +--*/ + +#ifndef __NMR_KEYSTORECONSUMER +#define __NMR_KEYSTORECONSUMER + +#include +#include +#include +#include +#include "Common/NMR_Types.h" +#include "Common/NMR_SecureContentTypes.h" + +namespace NMR { + class CKeyStoreConsumer { + std::string m_sConsumerID; + std::string m_sKeyID; + std::string m_sKeyValue; + public: + CKeyStoreConsumer(std::string const & consumerID, std::string const & keyID, std::string keyValue); + + std::string getConsumerID() const; + + std::string getKeyID() const; + void setKeyID(std::string const & keyID); + nfBool hasKeyID() const; + + std::string getKeyValue() const; + void setKeyValue(std::string const & keyValue); + nfBool hasKeyValue() const; + }; + + typedef std::shared_ptr PKeyStoreConsumer; +} +#endif \ No newline at end of file diff --git a/Include/Model/Classes/NMR_KeyStoreFactory.h b/Include/Model/Classes/NMR_KeyStoreFactory.h new file mode 100644 index 0000000..b9979ff --- /dev/null +++ b/Include/Model/Classes/NMR_KeyStoreFactory.h @@ -0,0 +1,84 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_KeyStoreFactory.h defines the CKeyStoreFactory Class. It is responsible for creating logic of keystore entities. + +--*/ + +#ifndef __NMR_KEYSTOREFACTORY +#define __NMR_KEYSTOREFACTORY + +#include +#include +#include + +#include +#include "Common/NMR_SecureContentTypes.h" + + +namespace NMR { + + class CModel; + using PModel = std::shared_ptr; + class CKeyStore; + using PKeyStore = std::shared_ptr; + class CKeyStoreConsumer; + using PKeyStoreConsumer = std::shared_ptr; + class CKeyStoreResourceDataGroup; + using PKeyStoreResourceDataGroup = std::shared_ptr; + class CKeyStoreAccessRight; + using PKeyStoreAccessRight = std::shared_ptr; + class CKeyStoreResourceData; + using PKeyStoreResourceData = std::shared_ptr; + class CKeyStoreContentEncryptionParams; + using PKeyStoreContentEncryptionParams = std::shared_ptr; + class CKeyStoreCEKParams; + using PKeyStoreCEKParams = std::shared_ptr; + + class CUUID; + using PUUID = std::shared_ptr; + + class CPackageModelPath; + using PPackageModelPath = std::shared_ptr; + + class CKeyStoreFactory { + public: + static PKeyStore makeKeyStore(); + static PKeyStoreResourceDataGroup makeResourceDataGroup(PUUID const & keyUUID = nullptr, std::vector const & key = std::vector()); + static PKeyStoreConsumer makeConsumer(std::string const & consumerID, std::string const & keyId = std::string(), std::string const & keyValue = std::string()); + static PKeyStoreAccessRight makeAccessRight(PKeyStoreConsumer const & consumer, eKeyStoreWrapAlgorithm const algorithm, eKeyStoreMaskGenerationFunction const mask, eKeyStoreMessageDigest const digest, std::vector const & cipherValue = std::vector()); + static PKeyStoreResourceData makeResourceData(PKeyStoreResourceDataGroup const & rdg, PPackageModelPath const & path, PKeyStoreCEKParams params = nullptr); + static PKeyStoreContentEncryptionParams makeContentEncryptionParams(PKeyStoreResourceData rd, PKeyStoreResourceDataGroup rdg); + static PKeyStoreCEKParams makeCEKParams(nfBool compressed, eKeyStoreEncryptAlgorithm algorithm, std::vector const & aad, std::vector const & iv = std::vector(), std::vector const & tag = std::vector()); + }; +} + + +#endif // !__NMR_KEYSTOREFACTORY + + diff --git a/Include/Model/Classes/NMR_KeyStoreResourceData.h b/Include/Model/Classes/NMR_KeyStoreResourceData.h new file mode 100644 index 0000000..b4a481c --- /dev/null +++ b/Include/Model/Classes/NMR_KeyStoreResourceData.h @@ -0,0 +1,76 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_KeyStoreResourceData.h defines the KeyStoreResourceData Class. A ResourceData is an in memory representation of the 3MF keystore resourcedata element. + +--*/ + +#ifndef __NMR_KEYSTORERESOURCEDATA +#define __NMR_KEYSTORERESOURCEDATA + +#include +#include +#include +#include "Common/NMR_Types.h" +#include "Common/NMR_SecureContentTypes.h" +#include "Model/Classes/NMR_PackageResourceID.h" +#include "Model/Classes/NMR_KeyStoreCEKParams.h" +namespace NMR { + + class CKeyStoreResourceDataGroup; + using PKeyStoreResourceDataGroup = std::shared_ptr; + + class CKeyStoreResourceData: public CKeyStoreCEKParams { + PKeyStoreResourceDataGroup m_pGroup; + PPackageModelPath m_pPath; + static nfUint64 s_nfHandleCount; + public: + CKeyStoreResourceData( + PKeyStoreResourceDataGroup const & rdg, + PPackageModelPath const & path, + bool compression, + eKeyStoreEncryptAlgorithm alg, + std::vector const & iv, + std::vector const & tag, + std::vector const & aad); + + inline PPackageModelPath packagePath() const { + return m_pPath; + } + + inline PKeyStoreResourceDataGroup const & getGroup() const { + return m_pGroup; + } + + void setInitVector(std::vector const &newIV); + void setAuthTag(std::vector const & newTag); + }; + typedef std::shared_ptr PKeyStoreResourceData; +} + +#endif diff --git a/Include/Model/Classes/NMR_KeyStoreResourceDataGroup.h b/Include/Model/Classes/NMR_KeyStoreResourceDataGroup.h new file mode 100644 index 0000000..90b5358 --- /dev/null +++ b/Include/Model/Classes/NMR_KeyStoreResourceDataGroup.h @@ -0,0 +1,77 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_KeyStoreResourceData.h defines the KeyStoreResourceData Class. A ResourceData is an in memory representation of the 3MF keystore resourcedata element. + +--*/ + +#ifndef __NMR_KEYSTORERESOURCEDATAGROUP +#define __NMR_KEYSTORERESOURCEDATAGROUP + +#include +#include +#include +#include + +#include "Common/NMR_Types.h" +#include "Common/NMR_SecureContentTypes.h" +#include "Model/Classes/NMR_KeyStore.h" +#include "Model/Classes/NMR_KeyStoreAccessRight.h" +#include "Model/Classes/NMR_KeyStoreResourceData.h" +#include "Model/Classes/NMR_PackageResourceID.h" +#include "Common/NMR_UUID.h" + +namespace NMR { + + class CKeyStoreResourceDataGroup { + PUUID m_sKeyUUID; + std::vector m_AccessRights; + std::map m_ConsumerAccesstRight; + std::vector m_rgKey; + std::mutex mtx; + public: + CKeyStoreResourceDataGroup(PUUID const& keyUUID, std::vector const & key); + + PUUID getKeyUUID() const; + nfUint64 addAccessRight(PKeyStoreAccessRight const & ar); + void removeAccessRight(std::string const & consumerId); + nfUint64 getAccessRightCount(); + PKeyStoreAccessRight getAccessRight(nfUint64 index) const; + PKeyStoreAccessRight findAccessRightByConsumerID(std::string const & consumerId) const; + + std::vector const & getKey() const; + void setKey(std::vector const & key); + + inline nfBool isOpen() const { + return !m_rgKey.empty(); + } + }; + typedef std::shared_ptr PKeyStoreResourceDataGroup; +} + +#endif diff --git a/Include/Model/Classes/NMR_Model.h b/Include/Model/Classes/NMR_Model.h new file mode 100644 index 0000000..ebb1146 --- /dev/null +++ b/Include/Model/Classes/NMR_Model.h @@ -0,0 +1,335 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_Model.h defines the Model Class. A model is an in memory representation of the 3MF file. + +--*/ + +#ifndef __NMR_MODEL +#define __NMR_MODEL + +#include "Model/Classes/NMR_ModelTypes.h" +#include "Common/Platform/NMR_ImportStream.h" + +#include "Common/Math/NMR_Matrix.h" +#include "Common/Mesh/NMR_Mesh.h" + +#include "Model/Classes/NMR_PackageResourceID.h" + +#include +#include +#include +#include + +#include "Common/NMR_UUID.h" + +#include "Common/NMR_SecureContentTypes.h" + +namespace NMR { + + class CModelBuildItem; + typedef std::shared_ptr PModelBuildItem; + + class CModelResource; + typedef std::shared_ptr PModelResource; + + class CModelObject; + typedef std::shared_ptr PModelObject; + + class CModelMetaData; + typedef std::shared_ptr PModelMetaData; + + class CModelMetaDataGroup; + typedef std::shared_ptr PModelMetaDataGroup; + + class CModelAttachment; + typedef std::shared_ptr PModelAttachment; + + class CModelBaseMaterialResource; + typedef std::shared_ptr PModelBaseMaterialResource; + + class CModelColorGroupResource; + typedef std::shared_ptr PModelColorGroupResource; + + class CModelCompositeMaterialsResource; + typedef std::shared_ptr PModelCompositeMaterialsResource; + + class CModelMultiPropertyGroupResource; + typedef std::shared_ptr PModelMultiPropertyGroupResource; + + class CModelTexture2DGroupResource; + typedef std::shared_ptr PModelTexture2DGroupResource; + + class CModelTexture2DResource; + typedef std::shared_ptr PModelTexture2DResource; + + class CModelSliceStack; + typedef std::shared_ptr PModelSliceStack; + + class CKeyStore; + typedef std::shared_ptr PKeyStore; + + typedef std::map UniqueResourceIDMapping; + + // The Model class implements the unification of all model-file in a 3MF package + // It should be understood as a "MultiModel" + class CModel { + private: + PPackageModelPath m_pCurPath; + PPackageModelPath m_pPath; + + std::unordered_map usedUUIDs; // datastructure used to ensure that UUIDs within one model (package) are unique + + // map of all UniqueResourceIDs to actual object resources of the model + std::map m_ResourceMap; + CResourceHandler m_resourceHandler; + private: + std::vector m_Resources; + + // Model Build Items + std::vector m_BuildItems; + + // build's UUID. Empty if none defined + PUUID m_buildUUID; + + // Model Properties + nfUint32 m_nHandleCounter; + eModelUnit m_Unit; + std::string m_sLanguage; + // Package Thumbnail as attachment + PModelAttachment m_pPackageThumbnailAttachment; + + // Model Metadata + PModelMetaDataGroup m_MetaDataGroup; + + // Model Attachments + std::vector m_Attachments; + std::unordered_map m_AttachmentURIMap; + + // Custom Attachment Content Types + std::map m_CustomContentTypes; + + // Production Model Attachments + std::vector m_ProductionAttachments; + std::unordered_map m_ProductionAttachmentURIMap; + + // Indexed lookup lists for standard resource types + std::vector m_ObjectLookup; + std::vector m_BaseMaterialLookup; + std::vector m_TextureLookup; + std::vector m_SliceStackLookup; + std::vector m_ColorGroupLookup; + std::vector m_Texture2DGroupLookup; + std::vector m_CompositeMaterialsLookup; + std::vector m_MultiPropertyGroupLookup; + + // The KeyStore reference + PKeyStore m_pKeyStore; + + CryptoRandGenDescriptor m_sRandDescriptor; + + // Add Resource to resource lookup tables + void addResourceToLookupTable(_In_ PModelResource pResource); + + public: + CModel(); + ~CModel(); + + const std::string currentPath(); + PPackageModelPath currentModelPath(); + void setCurrentPath(const std::string sPath); + + PPackageModelPath rootModelPath(); + const std::string rootPath(); + void setRootPath(const std::string sPath); + + PPackageModelPath findOrCreateModelPath(std::string sPath); + std::vector retrieveAllModelPaths(); + + // Merge all build items into one mesh + void mergeToMesh(_In_ CMesh * pMesh); + + // Units setter/getter + void setUnit(_In_ eModelUnit Unit); + void setUnitString(_In_ std::string sUnitString); + eModelUnit getUnit(); + std::string getUnitString(); + + // Language setter/getter + void setLanguage(_In_ std::string sLanguage); + std::string getLanguage(); + + // General Resource Handling + PModelResource findResource(_In_ std::string path, ModelResourceID nID); + PModelResource findResource(_In_ UniqueResourceID nID); + PModelResource findResource(_In_ PPackageResourceID pID); + + PPackageResourceID findPackageResourceID(_In_ std::string path, ModelResourceID nID); + PPackageResourceID findPackageResourceID(_In_ UniqueResourceID nID); + + nfUint32 getResourceCount(); + PModelResource getResource(_In_ nfUint32 nIndex); + void addResource(_In_ PModelResource pResource); + + // Metadata setter/getter + PModelMetaData addMetaData(_In_ std::string sNameSpace, _In_ std::string sName, _In_ std::string sValue, _In_ std::string sType, _In_ nfBool bPreserve); + nfUint32 getMetaDataCount(); + PModelMetaData getMetaData(_In_ nfUint32 nIndex); + void removeMetaData(_In_ nfUint32 nIndex); + nfBool hasMetaData(_In_ std::string sKey); + void mergeMetaData(_In_ CModel * pSourceModel); + PModelMetaDataGroup getMetaDataGroup(); + + // Build Handling + void addBuildItem(_In_ PModelBuildItem pBuildItem); + nfUint32 getBuildItemCount(); + PModelBuildItem getBuildItem(_In_ nfUint32 nIdx); + // Removes a build item identified by its handle + void removeBuildItem(_In_ nfUint32 nHandle, _In_ nfBool bThrowExceptionIfNotFound); + + PUUID buildUUID(); + void setBuildUUID(PUUID pUUID); + void unRegisterUUID(PUUID pUUID); + void registerUUID(PUUID pUUID); + + // Package Thumbnail Attachment + PModelAttachment addPackageThumbnail(_In_ std::string sPath, _In_ PImportStream pStream); + PModelAttachment addPackageThumbnail(); + void removePackageThumbnail(); + PModelAttachment getPackageThumbnail(); + + // Retrieve a unique Resource ID + UniqueResourceID generateResourceID(); // unique per model + void updateUniqueResourceID(UniqueResourceID nOldID, UniqueResourceID nNewID); + + PPackageResourceID generatePackageResourceID(_In_ std::string path, ModelResourceID nID); // unique per package + void removePackageResourceID(PPackageResourceID pID); + + // Convenience functions for objects + _Ret_maybenull_ CModelObject * findObject(_In_ UniqueResourceID nResourceID); + nfUint32 getObjectCount(); + PModelResource getObjectResource(_In_ nfUint32 nIndex); + nfInt32 compareObjectsByResourceID(CModelResource* pObjectResourceA, CModelResource* pObjectResourceB); + CModelObject * getObject(_In_ nfUint32 nIndex); + + // Convenience functions for base materials + _Ret_maybenull_ PModelBaseMaterialResource findBaseMaterial(_In_ PPackageResourceID pID); + nfUint32 getBaseMaterialCount(); + PModelResource getBaseMaterialResource(_In_ nfUint32 nIndex); + CModelBaseMaterialResource * getBaseMaterial(_In_ nfUint32 nIndex); + void mergeBaseMaterials(_In_ CModel * pSourceModel, _In_ UniqueResourceIDMapping &oldToNewMapping); + + // Convenience functions for color groups + _Ret_maybenull_ PModelColorGroupResource findColorGroup(_In_ UniqueResourceID nResourceID); + nfUint32 getColorGroupCount(); + PModelResource getColorGroupResource(_In_ nfUint32 nIndex); + CModelColorGroupResource * getColorGroup(_In_ nfUint32 nIndex); + void mergeColorGroups(_In_ CModel * pSourceModel, _In_ UniqueResourceIDMapping &oldToNewMapping); + + // Convenience functions for texture2d groups + _Ret_maybenull_ PModelTexture2DGroupResource findTexture2DGroup(_In_ UniqueResourceID nResourceID); + nfUint32 getTexture2DGroupCount(); + PModelResource getTexture2DGroupResource(_In_ nfUint32 nIndex); + CModelTexture2DGroupResource * getTexture2DGroup(_In_ nfUint32 nIndex); + void mergeTexture2DGroups(_In_ CModel * pSourceModel, _In_ UniqueResourceIDMapping &oldToNewMapping); + + // Convenience functions for composite materials + _Ret_maybenull_ PModelCompositeMaterialsResource findCompositeMaterials(_In_ UniqueResourceID nResourceID); + nfUint32 getCompositeMaterialsCount(); + PModelResource getCompositeMaterialsResource(_In_ nfUint32 nIndex); + CModelCompositeMaterialsResource * getCompositeMaterials(_In_ nfUint32 nIndex); + void mergeCompositeMaterials(_In_ CModel * pSourceModel, _In_ UniqueResourceIDMapping &oldToNewMapping); + + // Convenience functions for multi property groups + _Ret_maybenull_ PModelMultiPropertyGroupResource findMultiPropertyGroup(_In_ UniqueResourceID nResourceID); + nfUint32 getMultiPropertyGroupCount(); + PModelResource getMultiPropertyGroupResource(_In_ nfUint32 nIndex); + CModelMultiPropertyGroupResource * getMultiPropertyGroup(_In_ nfUint32 nIndex); + void mergeMultiPropertyGroups(_In_ CModel * pSourceModel, _In_ UniqueResourceIDMapping &oldToNewMapping); + + // Convenience functions for 2D Textures + _Ret_maybenull_ PModelTexture2DResource findTexture2D(_In_ UniqueResourceID nResourceID); + nfUint32 getTexture2DCount(); + PModelResource getTexture2DResource(_In_ nfUint32 nIndex); + CModelTexture2DResource * getTexture2D(_In_ nfUint32 nIndex); + void mergeTextures2D(_In_ CModel * pSourceModel, _In_ UniqueResourceIDMapping &oldToNewMapping); + + // Clear all build items and Resources + void clearAll (); + + // Creates a unique handle for identifying child classes (e.g. build items) + nfUint32 createHandle(); + + // Custom Attachments (includes Texture Attachments) + PModelAttachment addAttachment(_In_ const std::string sPath, _In_ const std::string sRelationShipType, PImportStream pCopiedStream); + void removeAttachment(_In_ const std::string sPath); + nfUint32 getAttachmentCount(); + PModelAttachment getModelAttachment(_In_ nfUint32 nIndex); + std::string getModelAttachmentPath(_In_ nfUint32 nIndex); + PModelAttachment findModelAttachment(_In_ std::string sPath); + void mergeModelAttachments(_In_ CModel * pSourceModel); + + // Custom Content Types + std::map getCustomContentTypes(); + void addCustomContentType(_In_ const std::string sExtension, _In_ const std::string sContentType); + void removeCustomContentType(_In_ const std::string sExtension); + nfBool contentTypeIsDefault(_In_ const std::string sExtension); + + // Production Extension Attachments + PModelAttachment addProductionAttachment(_In_ const std::string sPath, _In_ const std::string sRelationShipType, PImportStream pCopiedStream, nfBool bForceUnique); + void removeProductionAttachment(_In_ const std::string sPath); + nfUint32 getProductionAttachmentCount(); + PModelAttachment getProductionModelAttachment(_In_ nfUint32 nIndex); + std::string getProductionModelAttachmentPath(_In_ nfUint32 nIndex); + PModelAttachment findProductionModelAttachment(_In_ std::string sPath); + + // Required Extension Handling + nfBool RequireExtension(_In_ const std::string sExtension); + + // Convenience functions for slice stacks + nfUint32 getSliceStackCount(); + PModelResource getSliceStackResource(_In_ nfUint32 nIndex); + + // Sorts objects by correct dependency + std::list getSortedObjectList (); + + + // Gets the KeyStore + PKeyStore getKeyStore(); + void setKeyStore(PKeyStore keyStore); + + void setCryptoRandCallback(CryptoRandGenDescriptor const & randDescriptor); + nfBool hasCryptoRandCallbak() const; + nfUint64 generateRandomBytes(nfByte *, nfUint64); + + }; + + typedef std::shared_ptr PModel; +} + +#endif // __NMR_MODEL diff --git a/Include/Model/Classes/NMR_ModelAttachment.h b/Include/Model/Classes/NMR_ModelAttachment.h new file mode 100644 index 0000000..758793d --- /dev/null +++ b/Include/Model/Classes/NMR_ModelAttachment.h @@ -0,0 +1,70 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelAttachment.h defines the Model Attachment Class. + +--*/ + +#ifndef __NMR_MODELATTACHMENT +#define __NMR_MODELATTACHMENT + +#include "Model/Classes/NMR_Model.h" +#include "Model/Classes/NMR_ModelMetaData.h" +#include "Common/NMR_Types.h" +#include "Model/Classes/NMR_ModelTypes.h" + +#include + +namespace NMR { + + class CModelAttachment { + private: + CModel * m_pModel; + PImportStream m_pStream; + std::string m_sPathURI; + std::string m_sRelationShipType; + + public: + CModelAttachment() = delete; + CModelAttachment(_In_ CModel * pModel, _In_ const std::string sPathURI, _In_ const std::string sRelationShipType, _In_ PImportStream pStream); + ~CModelAttachment(); + + _Ret_notnull_ CModel * getModel(); + std::string getPathURI(); + std::string getRelationShipType(); + PImportStream getStream (); + + void setStream(_In_ PImportStream pStream); + void setRelationShipType(_In_ const std::string sRelationShipType); + }; + + typedef std::shared_ptr PModelAttachment; + +} + +#endif // __NMR_MODELATTACHMENT diff --git a/Include/Model/Classes/NMR_ModelBaseMaterial.h b/Include/Model/Classes/NMR_ModelBaseMaterial.h new file mode 100644 index 0000000..bd7e58e --- /dev/null +++ b/Include/Model/Classes/NMR_ModelBaseMaterial.h @@ -0,0 +1,69 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelBaseMaterial.h defines the Model Base Material Resource Class. +A model material resource is an in memory representation of the 3MF +material resource object. + +--*/ + +#include "Common/NMR_Local.h" +#include "Common/NMR_Types.h" +#include "Model/Classes/NMR_ModelTypes.h" +#include +#include + +#ifndef __NMR_MODELBASEMATERIAL +#define __NMR_MODELBASEMATERIAL + +namespace NMR { + + class CModelBaseMaterial { + private: + ModelPropertyID m_nPropertyID; + std::string m_sName; + nfColor m_cDisplayColor; + public: + CModelBaseMaterial() = delete; + CModelBaseMaterial(_In_ const std::string sName, _In_ nfColor cDisplayColor, _In_ ModelPropertyID nPropertyID); + + nfColor getDisplayColor(); + void setColor(_In_ nfColor cColor); + std::string getDisplayColorString(); + + std::string getName(); + void setName(_In_ const std::string sName); + + nfUint32 getPropertyID(); + }; + + typedef std::shared_ptr PModelBaseMaterial; + +} + +#endif // __NMR_MODELBASEMATERIAL diff --git a/Include/Model/Classes/NMR_ModelBaseMaterials.h b/Include/Model/Classes/NMR_ModelBaseMaterials.h new file mode 100644 index 0000000..5a46ca4 --- /dev/null +++ b/Include/Model/Classes/NMR_ModelBaseMaterials.h @@ -0,0 +1,72 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelBaseMaterials.h defines the Model Base Material Resource Class. +A model material resource is an in memory representation of the 3MF +material resource object. + +--*/ + +#ifndef __NMR_MODELBASEMATERIALS +#define __NMR_MODELBASEMATERIALS + +#include "Model/Classes/NMR_ModelBaseMaterial.h" +#include "Model/Classes/NMR_ModelResource.h" +#include "Model/Classes/NMR_ModelTypes.h" +#include "Model/Classes/NMR_Model.h" +#include + +namespace NMR { + + class CModel; + typedef std::shared_ptr PModel; + + class CModelBaseMaterialResource : public CModelResource { + private: + std::map m_pMaterials; + ModelPropertyID m_nNextPropertyID; + + public: + CModelBaseMaterialResource() = delete; + CModelBaseMaterialResource(_In_ const ModelResourceID sID, _In_ CModel * pModel); + + nfUint32 addBaseMaterial(_In_ const std::string sName, _In_ nfColor cDisplayColor); + + nfUint32 getCount(); + PModelBaseMaterial getBaseMaterial(_In_ nfUint32 nPropertyID); + + void removeMaterial(_In_ nfUint32 nPropertyID); + void mergeFrom(_In_ CModelBaseMaterialResource * pSourceMaterial); + void buildResourceIndexMap(); + }; + + typedef std::shared_ptr PModelBaseMaterialResource; + +} + +#endif // __NMR_MODELBASEMATERIAL diff --git a/Include/Model/Classes/NMR_ModelBuildItem.h b/Include/Model/Classes/NMR_ModelBuildItem.h new file mode 100644 index 0000000..79e8e4e --- /dev/null +++ b/Include/Model/Classes/NMR_ModelBuildItem.h @@ -0,0 +1,103 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelBuildItem.h defines the Model Build Item Class. +A model build item is an in memory representation of the 3MF +build item. + +--*/ + +#ifndef __NMR_MODELBUILDITEM +#define __NMR_MODELBUILDITEM + +#include "Model/Classes/NMR_Model.h" +#include "Model/Classes/NMR_ModelObject.h" +#include "Model/Classes/NMR_ModelMetaDataGroup.h" +#include "Common/NMR_Types.h" +#include "Common/Math/NMR_Matrix.h" + +namespace NMR { + + class CModelObject; + + typedef std::shared_ptr PModelObject; + + class CModelBuildItem { + private: + CModelObject * m_pObject; + NMATRIX3 m_mTransform; + std::string m_sPartNumber; + nfUint32 m_nHandle; + + PUUID m_UUID; + std::string m_sPath; + + PModelMetaDataGroup m_MetaDataGroup; + public: + CModelBuildItem() = delete; + CModelBuildItem(_In_ CModelObject * pObject, _In_ nfUint32 nHandle); + CModelBuildItem(_In_ CModelObject * pObject, _In_ const NMATRIX3 mTransform, _In_ nfUint32 nHandle); + ~CModelBuildItem(); + + CModelObject * getObject (); + CModel * getModel(); + + // Transform getter/setter + NMATRIX3 getTransform (); + void setTransform(_In_ const NMATRIX3 mTransform); + nfBool hasTransform(); + std::string getTransformString(); + + // Item reference getter/setter + std::string getPartNumber(); + void setPartNumber(_In_ std::string sPartNumber); + + // Production extension UUID + PUUID uuid(); + void setUUID(PUUID uuid); + + // MetaDataGroup + PModelMetaDataGroup metaDataGroup(); + + std::string path(); + void setPath(std::string sPath); + + // Merge the build item to the given mesh + void mergeToMesh(_In_ CMesh * pMesh); + + // Returns a unique handle to identify the build item + nfUint32 getHandle(); + + bool isValidForSlices(); + }; + + typedef std::shared_ptr PModelBuildItem; + +} + +#endif // __NMR_MODELBUILDITEM diff --git a/Include/Model/Classes/NMR_ModelColorGroup.h b/Include/Model/Classes/NMR_ModelColorGroup.h new file mode 100644 index 0000000..ad2e67b --- /dev/null +++ b/Include/Model/Classes/NMR_ModelColorGroup.h @@ -0,0 +1,72 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelColorGroup.h defines the Model Color Group Resource Class. +A model color group resource is an in memory representation of the 3MF +color group resource object. + +--*/ + +#ifndef __NMR_MODELCOLORGROUP +#define __NMR_MODELCOLORGROUP + +#include "Model/Classes/NMR_ModelResource.h" +#include "Model/Classes/NMR_ModelTypes.h" +#include "Model/Classes/NMR_Model.h" +#include + +namespace NMR { + + class CModel; + typedef std::shared_ptr PModel; + + class CModelColorGroupResource : public CModelResource { + private: + std::map m_pColors; + ModelPropertyID m_nNextPropertyID; + + public: + CModelColorGroupResource() = delete; + CModelColorGroupResource(_In_ const ModelResourceID sID, _In_ CModel * pModel); + + nfUint32 addColor(_In_ nfColor cColor); + + nfUint32 getCount(); + nfColor getColor(_In_ ModelPropertyID nPropertyID); + void setColor(_In_ ModelPropertyID nPropertyID, _In_ nfColor cColor); + + void removeColor(_In_ ModelPropertyID nPropertyID); + void mergeFrom(_In_ CModelColorGroupResource * pSourceMaterial); + void buildResourceIndexMap(); + }; + + typedef std::shared_ptr PModelColorGroupResource; + +} + +#endif // __NMR_MODELCOLORGROUP diff --git a/Include/Model/Classes/NMR_ModelComponent.h b/Include/Model/Classes/NMR_ModelComponent.h new file mode 100644 index 0000000..b0c7c83 --- /dev/null +++ b/Include/Model/Classes/NMR_ModelComponent.h @@ -0,0 +1,76 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelComponent.h defines the Model Component Class. +A model component is an in memory representation of the 3MF component. + +--*/ + +#ifndef __NMR_MODELCOMPONENT +#define __NMR_MODELCOMPONENT + +#include "Model/Classes/NMR_ModelObject.h" +#include "Model/Classes/NMR_ModelMetaData.h" +#include "Common/NMR_Types.h" +#include "Common/Math/NMR_Matrix.h" + +namespace NMR { + + class CModelComponent { + private: + CModelObject * m_pObject; + NMATRIX3 m_mTransform; + + PUUID m_UUID; + public: + CModelComponent() = delete; + CModelComponent(_In_ CModelObject * pObject); + CModelComponent(_In_ CModelObject * pObject, _In_ const NMATRIX3 mTransform); + ~CModelComponent(); + + CModelObject * getObject(); + CModel * getModel(); + + NMATRIX3 getTransform (); + void setTransform(_In_ const NMATRIX3 mTransform); + + nfBool hasTransform(); + std::string getTransformString(); + + // Production extension UUID + PUUID uuid(); + void setUUID(PUUID uuid); + + void mergeToMesh(_In_ CMesh * pMesh, _In_ const NMATRIX3 mMatrix); + }; + + typedef std::shared_ptr PModelComponent; + +} + +#endif // __NMR_MODELCOMPONENT diff --git a/Include/Model/Classes/NMR_ModelComponentsObject.h b/Include/Model/Classes/NMR_ModelComponentsObject.h new file mode 100644 index 0000000..8b4d1f0 --- /dev/null +++ b/Include/Model/Classes/NMR_ModelComponentsObject.h @@ -0,0 +1,79 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelComponentsObject.h defines the Model Component Object Class. +A model component object is an in memory representation of the 3MF +component object. + +--*/ + +#ifndef __NMR_MODELCOMPONENTSOBJECT +#define __NMR_MODELCOMPONENTSOBJECT + +#include "Model/Classes/NMR_ModelObject.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_Model.h" +#include "Common/Mesh/NMR_Mesh.h" + +#include + +namespace NMR { + + class CModel; + typedef std::shared_ptr PModel; + + class CModelComponentsObject : public CModelObject { + private: + std::vector m_Components; + public: + CModelComponentsObject() = delete; + CModelComponentsObject(_In_ const ModelResourceID sID, _In_ CModel * pModel); + ~CModelComponentsObject(); + + void addComponent(_In_ PModelComponent pComponent); + nfUint32 getComponentCount(); + PModelComponent getComponent(_In_ nfUint32 nIdx); + + void mergeToMesh(_In_ CMesh * pMesh, _In_ const NMATRIX3 mMatrix) override; + + // check, if the object is a valid object description + nfBool isValid() override; + + nfBool hasSlices(nfBool bRecursive) override; + nfBool isValidForSlices(const NMATRIX3& totalParentMatrix) override; + + void calculateComponentDepthLevel(nfUint32 nLevel) override; + + void extendOutbox(_Out_ NOUTBOX3& vOutBox, _In_ const NMATRIX3 mAccumulatedMatrix) override; + }; + + typedef std::shared_ptr PModelComponentsObject; + +} + +#endif // __NMR_MODELCOMPONENTSOBJECT diff --git a/Include/Model/Classes/NMR_ModelCompositeMaterials.h b/Include/Model/Classes/NMR_ModelCompositeMaterials.h new file mode 100644 index 0000000..3d7bdb5 --- /dev/null +++ b/Include/Model/Classes/NMR_ModelCompositeMaterials.h @@ -0,0 +1,91 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelCompositeMaterials.h defines the Model Composite Materials Resource Class. +A model composite materials resource is an in memory representation of the 3MF +composite materials resource object. + +--*/ + +#ifndef __NMR_MODELCOMPOSITEMATERIALS +#define __NMR_MODELCOMPOSITEMATERIALS + +#include "Model/Classes/NMR_ModelBaseMaterials.h" +#include "Model/Classes/NMR_ModelResource.h" +#include "Model/Classes/NMR_ModelTypes.h" +#include "Model/Classes/NMR_Model.h" +#include + +namespace NMR { + + class CModel; + typedef std::shared_ptr PModel; + + class CModelComposite: public std::vector + { + public: + nfDouble GetMixingRatio(ModelPropertyID nPropertyID) + { + for (MODELCOMPOSITECONSTITUENT constituent : (*this)) { + if (constituent.m_nPropertyID == nPropertyID) { + return constituent.m_dMixingRatio; + } + } + return 0.0; + } + }; + typedef std::shared_ptr PModelComposite; + + class CModelCompositeMaterialsResource : public CModelResource { + private: + std::map m_pComposites; + ModelPropertyID m_nNextPropertyID; + + PModelBaseMaterialResource m_pBaseMaterialResource; + public: + CModelCompositeMaterialsResource() = delete; + CModelCompositeMaterialsResource(_In_ const ModelResourceID sID, _In_ CModel * pModel, + _In_ PModelBaseMaterialResource pBaseMaterialResource); + + nfUint32 addComposite(_In_ PModelComposite pComposite); + + nfUint32 getCount(); + PModelComposite getComposite(_In_ ModelPropertyID nPropertyID); + void setComposite(_In_ ModelPropertyID nPropertyID, _In_ PModelComposite pComposite); + + void removeComposite(_In_ ModelPropertyID nPropertyID); + void mergeFrom(_In_ CModelCompositeMaterialsResource * pSourceCompositesMaterials); + void buildResourceIndexMap(); + + PModelBaseMaterialResource getBaseMaterialResource(); + }; + + typedef std::shared_ptr PModelCompositeMaterialsResource; +} + +#endif // __NMR_MODELCOMPOSITEMATERIALS diff --git a/Include/Model/Classes/NMR_ModelConstants.h b/Include/Model/Classes/NMR_ModelConstants.h new file mode 100644 index 0000000..2119189 --- /dev/null +++ b/Include/Model/Classes/NMR_ModelConstants.h @@ -0,0 +1,427 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelConstants.h defines the 3MF Model Constants. +These are given by the 3MF Standard + +--*/ + +#ifndef __NMR_MODELCONSTANTS +#define __NMR_MODELCONSTANTS + +#define PACKAGE_3D_RELS_CONTENT_TYPE "application/vnd.openxmlformats-package.relationships+xml" +#define PACKAGE_3D_MODEL_CONTENT_TYPE "application/vnd.ms-package.3dmanufacturing-3dmodel+xml" +#define PACKAGE_TEXTURE_CONTENT_TYPE "application/vnd.ms-package.3dmanufacturing-3dmodeltexture" +#define PACKAGE_PRINT_TICKET_CONTENT_TYPE "application/vnd.ms-printing.printticket+xml" +#define PACKAGE_CORE_PROPERTIES_CONTENT_TYPE "application/vnd.openxmlformats-package.core-properties+xml" +#define PACKAGE_KEYSTORE_CONTENT_TYPE "application/vnd.ms-package.3dmanufacturing-keystore+xml" +#define PACKAGE_GIF_CONTENT_TYPE "image/gif" +#define PACKAGE_JPG_CONTENT_TYPE "image/jpeg" +#define PACKAGE_PNG_CONTENT_TYPE "image/png" + +#define PACKAGE_3D_MODEL_EXTENSION "model" +#define PACKAGE_3D_TEXTURE_EXTENSION "texture" +#define PACKAGE_3D_RELS_EXTENSION "rels" +#define PACKAGE_3D_JPG_EXTENSION "jpg" +#define PACKAGE_3D_JPEG_EXTENSION "jpeg" +#define PACKAGE_3D_PNG_EXTENSION "png" + +#define PACKAGE_3D_MODEL_URI "/3D/3dmodel.model" +#define PACKAGE_TEXTURE_URI_BASE "/3D/Texture" +#define PACKAGE_PRINT_TICKET_URI "/3D/Metadata/Model_PT.xml" +#define PACKAGE_CORE_PROPERTIES_URI "/Metadata/CoreProperties.prop" +#define PACKAGE_THUMBNAIL_URI_BASE "/Metadata" + +#define PACKAGE_3D_KEYSTORE_URI "/Secure/keystore.xml" + +#define NMR_MAXHANDLE 0xfffffffe + +#define PACKAGE_XMLNS_093 "http://schemas.microsoft.com/3dmanufacturing/2013/01" +#define PACKAGE_XMLNS_100 "http://schemas.microsoft.com/3dmanufacturing/core/2015/02" + +#define PACKAGE_START_PART_RELATIONSHIP_TYPE "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel" +#define PACKAGE_PRINT_TICKET_RELATIONSHIP_TYPE "http://schemas.microsoft.com/3dmanufacturing/2013/01/printticket" +#define PACKAGE_TEXTURE_RELATIONSHIP_TYPE "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dtexture" +#define PACKAGE_CORE_PROPERTIES_RELATIONSHIP_TYPE "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" +#define PACKAGE_THUMBNAIL_RELATIONSHIP_TYPE "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail" +#define PACKAGE_MUST_PRESERVE_RELATIONSHIP_TYPE "http://schemas.openxmlformats.org/package/2006/relationships/mustpreserve" +#define PACKAGE_KEYSTORE_RELATIONSHIP_TYPE "http://schemas.microsoft.com/3dmanufacturing/2019/04/keystore" +#define PACKAGE_ENCRYPTED_FILE_RELATIONSHIP "http://schemas.openxmlformats.org/package/2006/relationships/encryptedfile" + +#define XML_3MF_NAMESPACE_XML "http://www.w3.org/XML/1998/namespace" +#define XML_3MF_NAMESPACE_XMLNS "http://www.w3.org/2000/xmlns/" +#define XML_3MF_NAMESPACE_CORESPEC093 PACKAGE_XMLNS_093 +#define XML_3MF_NAMESPACE_CORESPEC100 PACKAGE_XMLNS_100 +#define XML_3MF_NAMESPACE_MATERIALSPEC "http://schemas.microsoft.com/3dmanufacturing/material/2015/02" +#define XML_3MF_NAMESPACE_PRODUCTIONSPEC "http://schemas.microsoft.com/3dmanufacturing/production/2015/06" +#define XML_3MF_NAMESPACE_BEAMLATTICESPEC "http://schemas.microsoft.com/3dmanufacturing/beamlattice/2017/02" +#define XML_3MF_NAMESPACE_SLICESPEC "http://schemas.microsoft.com/3dmanufacturing/slice/2015/07" +#define XML_3MF_NAMESPACE_SECURECONTENTSPEC "http://schemas.microsoft.com/3dmanufacturing/securecontent/2019/04" +#define XML_3MF_NAMESPACE_DIGITALSIGNATURESPEC "http://www.w3.org/2000/09/xmldsig#" +#define XML_3MF_NAMESPACE_CIPHERVALUESPEC "http://www.w3.org/2001/04/xmlenc#" + +#define XML_3MF_NAMESPACEPREFIX_MATERIAL "m" +#define XML_3MF_NAMESPACEPREFIX_PRODUCTION "p" +#define XML_3MF_NAMESPACEPREFIX_BEAMLATTICE "b" +#define XML_3MF_NAMESPACEPREFIX_SLICE "s" +#define XML_3MF_NAMESPACEPREFIX_SECURECONTENT "sc" + +#define XML_3MF_ATTRIBUTE_XMLNS "xmlns" +#define XML_3MF_ATTRIBUTE_PREFIX_XML "xml" +#define XML_3MF_ATTRIBUTE_MUST_UNDERSTAND "MustUnderstand" + +#define XML_3MF_ELEMENT_METADATAGROUP "metadatagroup" +#define XML_3MF_ELEMENT_METADATA "metadata" +#define XML_3MF_ELEMENT_METADATA_ENRTY "entry" +#define XML_3MF_ATTRIBUTE_METADATA_NAME "name" +#define XML_3MF_ATTRIBUTE_METADATA_PRESERVE "preserve" +#define XML_3MF_ATTRIBUTE_METADATA_TYPE "type" +#define XML_3MF_METADATA_VALUE_1 "Title" +#define XML_3MF_METADATA_VALUE_2 "Designer" +#define XML_3MF_METADATA_VALUE_3 "Description" +#define XML_3MF_METADATA_VALUE_4 "Copyright" +#define XML_3MF_METADATA_VALUE_5 "LicenseTerms" +#define XML_3MF_METADATA_VALUE_6 "Rating" +#define XML_3MF_METADATA_VALUE_7 "CreationDate" +#define XML_3MF_METADATA_VALUE_8 "ModificationDate" +#define XML_3MF_METADATA_VALUE_9 "Application" + + +// Resources element. +#define XML_3MF_ELEMENT_RESOURCES "resources" + +// Mesh element. +#define XML_3MF_ELEMENT_MESH "mesh" + +// Slices element. +#define XML_3MF_ELEMENT_SLICES "slices" +#define XML_3MF_ATTRIBUTE_SLICES_SLICEHEIGHT "sliceheight" + +// Components element. +#define XML_3MF_ELEMENT_COMPONENTS "components" + +// Vertices element. +#define XML_3MF_ELEMENT_VERTICES "vertices" + +// Texturevertices element. +#define XML_3MF_ELEMENT_TEXTUREVERTICES "texturevertices" + +// Triangles element. +#define XML_3MF_ELEMENT_TRIANGLES "triangles" + + +#define XML_3MF_ELEMENT_BEAMLATTICE "beamlattice" +#define XML_3MF_ELEMENT_BEAMS "beams" +#define XML_3MF_ELEMENT_BEAM "beam" +#define XML_3MF_ELEMENT_BALLS "balls" +#define XML_3MF_ELEMENT_BALL "ball" +#define XML_3MF_ELEMENT_BEAMSETS "beamsets" +#define XML_3MF_ELEMENT_BEAMSET "beamset" +#define XML_3MF_ELEMENT_REF "ref" +#define XML_3MF_ELEMENT_BALLREF "ballref" + +// Triangle element. +#define XML_3MF_ELEMENT_TRIANGLE "triangle" +#define XML_3MF_ATTRIBUTE_TRIANGLE_V1 "v1" +#define XML_3MF_ATTRIBUTE_TRIANGLE_V2 "v2" +#define XML_3MF_ATTRIBUTE_TRIANGLE_V3 "v3" +#define XML_3MF_ATTRIBUTE_TRIANGLE_COLORID "colorid" +#define XML_3MF_ATTRIBUTE_TRIANGLE_CV1 "cv1" +#define XML_3MF_ATTRIBUTE_TRIANGLE_CV2 "cv2" +#define XML_3MF_ATTRIBUTE_TRIANGLE_CV3 "cv3" +#define XML_3MF_ATTRIBUTE_TRIANGLE_MATERIALID "materialid" +#define XML_3MF_ATTRIBUTE_TRIANGLE_PID "pid" +#define XML_3MF_ATTRIBUTE_TRIANGLE_P1 "p1" +#define XML_3MF_ATTRIBUTE_TRIANGLE_P2 "p2" +#define XML_3MF_ATTRIBUTE_TRIANGLE_P3 "p3" +#define XML_3MF_ATTRIBUTE_BEAMLATTICE_V1 "v1" +#define XML_3MF_ATTRIBUTE_BEAMLATTICE_V2 "v2" +#define XML_3MF_ATTRIBUTE_BEAMLATTICE_NAME "name" +#define XML_3MF_ATTRIBUTE_BEAMLATTICE_IDENTIFIER "identifier" +#define XML_3MF_ATTRIBUTE_BEAMLATTICE_R1 "r1" +#define XML_3MF_ATTRIBUTE_BEAMLATTICE_R2 "r2" +#define XML_3MF_ATTRIBUTE_BEAMLATTICE_CLIPPINGMODE "clippingmode" +#define XML_3MF_ATTRIBUTE_BEAMLATTICE_CLIPPING "clipping" +#define XML_3MF_ATTRIBUTE_BEAMLATTICE_CLIPPINGMESH "clippingmesh" +#define XML_3MF_ATTRIBUTE_BEAMLATTICE_REPRESENTATIONMESH "representationmesh" +#define XML_3MF_ATTRIBUTE_BEAMLATTICE_RADIUS "radius" +#define XML_3MF_ATTRIBUTE_BEAMLATTICE_MINLENGTH "minlength" +#define XML_3MF_ATTRIBUTE_BEAMLATTICE_CAPMODE "cap" +#define XML_3MF_ATTRIBUTE_BEAMLATTICE_CAP1 "cap1" +#define XML_3MF_ATTRIBUTE_BEAMLATTICE_CAP2 "cap2" +#define XML_3MF_ATTRIBUTE_BEAMLATTICE_BALLMODE "ballmode" +#define XML_3MF_ATTRIBUTE_BEAMLATTICE_BALLRADIUS "ballradius" +#define XML_3MF_ATTRIBUTE_BEAMLATTICE_BALL_VINDEX "vindex" +#define XML_3MF_ATTRIBUTE_BEAMLATTICE_BALL_R "r" +#define XML_3MF_ATTRIBUTE_BEAMLATTICE_INDEX "index" +#define XML_3MF_ATTRIBUTE_BEAMLATTICETAG_TAG "tag" +// deprecated (has been used in draft version of the specification): +#define XML_3MF_ATTRIBUTE_BEAMLATTICE_ACCURACY "accuracy" +#define XML_3MF_ATTRIBUTE_BEAMLATTICE_PRECISION "precision" + +// Vertex element. +#define XML_3MF_ELEMENT_VERTEX "vertex" +#define XML_3MF_ATTRIBUTE_VERTEX_X "x" +#define XML_3MF_ATTRIBUTE_VERTEX_Y "y" +#define XML_3MF_ATTRIBUTE_VERTEX_Z "z" + +// Texturevertex element. +#define XML_3MF_ELEMENT_TEXTUREVERTEX "texturevertex" +#define XML_3MF_ATTRIBUTE_TEXTUREVERTEX_U "u" +#define XML_3MF_ATTRIBUTE_TEXTUREVERTEX_V "v" +#define XML_3MF_ATTRIBUTE_TEXTUREVERTEX_W "w" + +// Texture2D element +#define XML_3MF_ELEMENT_TEXTURE2D "texture2d" +#define XML_3MF_ATTRIBUTE_TEXTURE2D_ID "id" +#define XML_3MF_ATTRIBUTE_TEXTURE2D_PATH "path" +#define XML_3MF_ATTRIBUTE_TEXTURE2D_CONTENTTYPE "contenttype" +#define XML_3MF_ATTRIBUTE_TEXTURE2D_BOX "box" +#define XML_3MF_ATTRIBUTE_TEXTURE2D_TILESTYLEU "tilestyleu" +#define XML_3MF_ATTRIBUTE_TEXTURE2D_TILESTYLEV "tilestylev" +#define XML_3MF_ATTRIBUTE_TEXTURE2D_TILESTYLE_WRAP "wrap" +#define XML_3MF_ATTRIBUTE_TEXTURE2D_TILESTYLE_MIRROR "mirror" +#define XML_3MF_ATTRIBUTE_TEXTURE2D_TILESTYLE_CLAMP "clamp" +#define XML_3MF_ATTRIBUTE_TEXTURE2D_TILESTYLE_NONE "none" +#define XML_3MF_ATTRIBUTE_TEXTURE2D_FILTER "filter" +#define XML_3MF_ATTRIBUTE_TEXTURE2D_FILTER_AUTO "auto" +#define XML_3MF_ATTRIBUTE_TEXTURE2D_FILTER_LINEAR "linear" +#define XML_3MF_ATTRIBUTE_TEXTURE2D_FILTER_NEAREST "nearest" + +// Compositematerials and composite element +#define XML_3MF_ELEMENT_COMPOSITEMATERIALS "compositematerials" +#define XML_3MF_ATTRIBUTE_COMPOSITEMATERIALS_ID "id" +#define XML_3MF_ATTRIBUTE_COMPOSITEMATERIALS_MATID "matid" +#define XML_3MF_ATTRIBUTE_COMPOSITEMATERIALS_MATINDICES "matindices" +#define XML_3MF_ELEMENT_COMPOSITE "composite" +#define XML_3MF_ATTRIBUTE_COMPOSITE_VALUES "values" + +// Multiproperties +#define XML_3MF_ELEMENT_MULTIPROPERTIES "multiproperties" +#define XML_3MF_ATTRIBUTE_MULTIPROPERTIES_ID "id" +#define XML_3MF_ATTRIBUTE_MULTIPROPERTIES_PIDS "pids" +#define XML_3MF_ATTRIBUTE_MULTIPROPERTIES_BLENDMETHODS "blendmethods" +#define XML_3MF_ATTRIBUTE_MULTIPROPERTIES_BLENDMETHOD_MIX "mix" +#define XML_3MF_ATTRIBUTE_MULTIPROPERTIES_BLENDMETHOD_MULTIPLY "multiply" +#define XML_3MF_ELEMENT_MULTI "multi" +#define XML_3MF_ATTRIBUTE_MULTI_PINDICES "pindices" + +// Geometry element. +#define XML_3MF_ELEMENT_GEOMETRY "geometry" +#define XML_3MF_ATTRIBUTE_GEOMETRY_DATA "data" +#define XML_3MF_ATTRIBUTE_GEOMETRY_DEPTH "depth" +#define XML_3MF_ATTRIBUTE_GEOMETRY_SLICE "slice" +#define XML_3MF_ATTRIBUTE_GEOMETRY_OBJECTID "objectid" +#define XML_3MF_ATTRIBUTE_GEOMETRY_OBJECT_TYPE "objecttype" + +// Geometry template element. +#define XML_3MF_ELEMENT_GEOMETRY_TEMPLATE "geometrytemplate" +#define XML_3MF_ATTRIBUTE_GEOMETRY_TEMPLATE_ID "id" +#define XML_3MF_ATTRIBUTE_GEOMETRY_TEMPLATE_DATA "data" + +// Component element. +#define XML_3MF_ELEMENT_COMPONENT "component" +#define XML_3MF_ATTRIBUTE_COMPONENT_OBJECTID "objectid" +#define XML_3MF_ATTRIBUTE_COMPONENT_TRANSFORM "transform" + +// Color resource group +#define XML_3MF_ELEMENT_COLORGROUP "colorgroup" +#define XML_3MF_ATTRIBUTE_COLORS_COLOR "color" +#define XML_3MF_ATTRIBUTE_COLORS_ID "id" + +// TexCoord resource group +#define XML_3MF_ELEMENT_TEX2DGROUP "texture2dgroup" +#define XML_3MF_ATTRIBUTE_TEX2DGROUP_ID "id" +#define XML_3MF_ELEMENT_TEX2COORD "tex2coord" +#define XML_3MF_ATTRIBUTE_TEX2DGROUP_TEXTUREID "texid" + +// Object element. +#define XML_3MF_ELEMENT_OBJECT "object" +#define XML_3MF_ATTRIBUTE_OBJECT_ID "id" +#define XML_3MF_ATTRIBUTE_OBJECT_COLOR_ID "colorid" +#define XML_3MF_ATTRIBUTE_OBJECT_TYPE "type" +#define XML_3MF_ATTRIBUTE_OBJECT_FILLMATERIALID "fillmaterialid" +#define XML_3MF_ATTRIBUTE_OBJECT_MATERIALID "materialid" +#define XML_3MF_ATTRIBUTE_OBJECT_FILLTEXTUREID "filltextureid" +#define XML_3MF_ATTRIBUTE_OBJECT_MINWALLTHICKNESS "minwallthickness" +#define XML_3MF_ATTRIBUTE_OBJECT_THUMBNAIL "thumbnail" +#define XML_3MF_ATTRIBUTE_OBJECT_FIT "fit" +#define XML_3MF_ATTRIBUTE_OBJECT_NAME "name" +#define XML_3MF_ATTRIBUTE_OBJECT_PARTNUMBER "partnumber" +#define XML_3MF_ATTRIBUTE_OBJECT_PID "pid" +#define XML_3MF_ATTRIBUTE_OBJECT_PINDEX "pindex" +#define XML_3MF_ATTRIBUTE_OBJECT_SLICESTACKID "slicestackid" +#define XML_3MF_ATTRIBUTE_OBJECT_MESHRESOLUTION "meshresolution" +#define XML_3MF_VALUE_OBJECT_MESHRESOLUTION_LOW "lowres" +#define XML_3MF_VALUE_OBJECT_MESHRESOLUTION_FULL "fullres" + +// Model element. +#define XML_3MF_ELEMENT_MODEL "model" +#define XML_3MF_ATTRIBUTE_MODEL_UNIT "unit" +#define XML_3MF_ATTRIBUTE_MODEL_LANG "lang" // xml:lang +#define XML_3MF_ATTRIBUTE_MODEL_SPACE "space" // xml:space : forbidden +#define XML_3MF_ATTRIBUTE_REQUIREDEXTENSIONS "requiredextensions" + +// Build element. +#define XML_3MF_ELEMENT_BUILD "build" // was "make" +#define XML_3MF_ELEMENT_ITEM "item" +#define XML_3MF_ATTRIBUTE_ITEM_OBJECTID "objectid" +#define XML_3MF_ATTRIBUTE_ITEM_TRANSFORM "transform" +#define XML_3MF_ATTRIBUTE_ITEM_PARTNUMBER "partnumber" + +// Texture element. +#define XML_3MF_ELEMENT_TEXTURE "texture" +#define XML_3MF_ATTRIBUTE_TEXTURE_ID "id" +#define XML_3MF_ATTRIBUTE_TEXTURE_PATH "path" +#define XML_3MF_ATTRIBUTE_TEXTURE_WIDTH "width" +#define XML_3MF_ATTRIBUTE_TEXTURE_HEIGHT "height" +#define XML_3MF_ATTRIBUTE_TEXTURE_DEPTH "depth" +#define XML_3MF_ATTRIBUTE_TEXTURE_CONTENTTYPE "contenttype" +#define XML_3MF_ATTRIBUTE_TEXTURE_U "u" +#define XML_3MF_ATTRIBUTE_TEXTURE_V "v" +#define XML_3MF_ATTRIBUTE_TEXTURE_W "w" +#define XML_3MF_ATTRIBUTE_TEXTURE_SCALE "scale" +#define XML_3MF_ATTRIBUTE_TEXTURE_ROTATION "rotation" +#define XML_3MF_ATTRIBUTE_TEXTURE_TILESTYLEU "tilestyleu" +#define XML_3MF_ATTRIBUTE_TEXTURE_TILESTYLEV "tilestylev" +#define XML_3MF_ATTRIBUTE_TEXTURE_TILESTYLEW "tilestylew" + +// Color element. +#define XML_3MF_ELEMENT_COLOR "color" +#define XML_3MF_ATTRIBUTE_COLOR_ID "id" +#define XML_3MF_ATTRIBUTE_COLOR_VALUE "value" + +// Base Material element. +#define XML_3MF_ELEMENT_BASEMATERIALS "basematerials" +#define XML_3MF_ELEMENT_BASE "base" +#define XML_3MF_ATTRIBUTE_BASEMATERIALS_ID "id" +#define XML_3MF_ATTRIBUTE_BASEMATERIAL_NAME "name" +#define XML_3MF_ATTRIBUTE_BASEMATERIAL_DISPLAYCOLOR "displaycolor" + +// Material element. +#define XML_3MF_ELEMENT_MATERIAL "material" +#define XML_3MF_ATTRIBUTE_MATERIAL_ID "id" +#define XML_3MF_ATTRIBUTE_MATERIAL_COLORID "colorid" +#define XML_3MF_ATTRIBUTE_MATERIAL_NAME "name" + +#define XML_3MF_MODELUNIT_MICROMETER "micron" +#define XML_3MF_MODELUNIT_MILLIMETER "millimeter" +#define XML_3MF_MODELUNIT_CENTIMETER "centimeter" +#define XML_3MF_MODELUNIT_INCH "inch" +#define XML_3MF_MODELUNIT_FOOT "foot" +#define XML_3MF_MODELUNIT_METER "meter" + +#define XML_3MF_OBJECTTYPE_OTHER "other" +#define XML_3MF_OBJECTTYPE_MODEL "model" +#define XML_3MF_OBJECTTYPE_SUPPORT "support" +#define XML_3MF_OBJECTTYPE_SOLIDSUPPORT "solidsupport" +#define XML_3MF_OBJECTTYPE_SURFACE "surface" + +#define XML_3MF_BEAMLATTICE_CLIPMODE_NONE "none" +#define XML_3MF_BEAMLATTICE_CLIPMODE_INSIDE "inside" +#define XML_3MF_BEAMLATTICE_CLIPMODE_OUTSIDE "outside" + +#define XML_3MF_BEAMLATTICE_CAPMODE_SPHERE "sphere" +#define XML_3MF_BEAMLATTICE_CAPMODE_HEMISPHERE "hemisphere" +#define XML_3MF_BEAMLATTICE_CAPMODE_BUTT "butt" +// depricated (from a draft version of the spec): +#define XML_3MF_BEAMLATTICE_CAPMODE_ROUND "round" + +#define XML_3MF_BEAMLATTICE_BALLMODE_NONE "none" +#define XML_3MF_BEAMLATTICE_BALLMODE_MIXED "mixed" +#define XML_3MF_BEAMLATTICE_BALLMODE_ALL "all" + +// KeyStore element. +#define XML_3MF_ELEMENT_KEYSTORE "keystore" +#define XML_3MF_ELEMENT_CONSUMER "consumer" +#define XML_3MF_ELEMENT_RESOURCEDATA "resourcedata" +#define XML_3MF_ELEMENT_RESOURCEDATAGROUP "resourcedatagroup" +#define XML_3MF_ELEMENT_KEYVALUE "keyvalue" +#define XML_3MF_ELEMENT_CIPHERDATA "cipherdata" +#define XML_3MF_ELEMENT_CIPHERVALUE "CipherValue" +#define XML_3MF_ELEMENT_KEKPARAMS "kekparams" +#define XML_3MF_ELEMENT_CEKPARAMS "cekparams" +#define XML_3MF_ELEMENT_ACCESSRIGHT "accessright" +#define XML_3MF_SECURE_CONTENT_UUID "UUID" +#define XML_3MF_SECURE_CONTENT_CONSUMER_ID "consumerid" +#define XML_3MF_SECURE_CONTENT_KEY_ID "keyid" +#define XML_3MF_SECURE_CONTENT_KEY_UUID "keyuuid" +#define XML_3MF_SECURE_CONTENT_PATH "path" +#define XML_3MF_SECURE_CONTENT_ENCRYPTION_ALGORITHM "encryptionalgorithm" +#define XML_3MF_SECURE_CONTENT_COMPRESSION "compression" +#define XML_3MF_SECURE_CONTENT_COMPRESSION_DEFLATE "deflate" +#define XML_3MF_SECURE_CONTENT_COMPRESSION_NONE "none" +#define XML_3MF_SECURE_CONTENT_CONSUMER_INDEX "consumerindex" +#define XML_3MF_SECURE_CONTENT_ALGORITHM "Algorithm" +#define XML_3MF_SECURE_CONTENT_WRAPPINGALGORITHM "wrappingalgorithm" +#define XML_3MF_SECURE_CONTENT_MGFALGORITHM "mgfalgorithm" +#define XML_3MF_SECURE_CONTENT_DIGESTMETHOD "digestmethod" +#define XML_3MF_SECURE_CONTENT_IV "iv" +#define XML_3MF_SECURE_CONTENT_TAG "tag" +#define XML_3MF_SECURE_CONTENT_AAD "aad" +#define XML_3MF_SECURE_CONTENT_KEY_UUID "keyuuid" + +#define XML_3MF_SECURE_CONTENT_ENCRYPTION_AES256 "http://www.w3.org/2009/xmlenc11#aes256-gcm" +#define XML_3MF_SECURE_CONTENT_KEYWRAPPING_RSA "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" +#define XML_3MF_SECURE_CONTENT_KEYWRAPPING_RSASHORT "http://www.w3.org/2009/xmlenc11#rsa-oaep" + +#define XML_3MF_SECURE_CONTENT_MGF1_SHA1 "http://www.w3.org/2009/xmlenc11#mgf1sha1" +#define XML_3MF_SECURE_CONTENT_MGF1_SHA224 "http://www.w3.org/2009/xmlenc11#mgf1sha224" +#define XML_3MF_SECURE_CONTENT_MGF1_SHA256 "http://www.w3.org/2009/xmlenc11#mgf1sha256" +#define XML_3MF_SECURE_CONTENT_MGF1_SHA384 "http://www.w3.org/2009/xmlenc11#mgf1sha384" +#define XML_3MF_SECURE_CONTENT_MGF1_SHA512 "http://www.w3.org/2009/xmlenc11#mgf1sha512" + +#define XML_3MF_SECURE_CONTENT_MD_SHA1 "http://www.w3.org/2000/09/xmldsig#sha1" +#define XML_3MF_SECURE_CONTENT_MD_SHA256 "http://www.w3.org/2001/04/xmlenc#sha256" +#define XML_3MF_SECURE_CONTENT_MD_SHA384 "http://www.w3.org/2001/04/xmlenc#sha384" +#define XML_3MF_SECURE_CONTENT_MD_SHA512 "http://www.w3.org/2001/04/xmlenc#sha512" + +#define XML_3MF_SECURE_CONTENT_MAXELEMENTCOUNT 2147483647 + +#define XML_3MF_NAMESPACEPREFIX_DS "ds" +#define XML_3MF_NAMESPACEPREFIX_XENC "xenc" + +#define XML_3MF_PRODUCTION_PATH "path" +#define XML_3MF_PRODUCTION_UUID "UUID" + +#define XML_3MF_LANG_US "en-US" + +#define XML_3MF_MAXIMUMCOORDINATEVALUE 1000000000.0f +#define XML_3MF_MAXMODELID 2147483647 +#define XML_3MF_MAXRESOURCEINDEX 2147483647 +#define XML_3MF_MAXRESOURCEID 2147483647 +#define XML_3MF_MAXMETADATACOUNT 2147483647 +#define XML_3MF_MAXBUILDITEMCOUNT 2147483647 +#define XML_3MF_MAXRESOURCECOUNT 2147483647 +#define XML_3MF_MAXIMUMBEAMRADIUSVALUE 1000000000.0f +#define XML_3MF_MAXIMUMBALLRADIUSVALUE 1000000000.0f +#define XML_3MF_MAXIMUMSKINTHICKNESSVALUE 1000000000.0f +#define XML_3MF_MAXBEAMCOUNT 2147483647 +#define XML_3MF_MAXBALLCOUNT 2147483647 + +#endif // __NMR_MODELCONSTANTS diff --git a/Include/Model/Classes/NMR_ModelConstants_Slices.h b/Include/Model/Classes/NMR_ModelConstants_Slices.h new file mode 100644 index 0000000..0a46809 --- /dev/null +++ b/Include/Model/Classes/NMR_ModelConstants_Slices.h @@ -0,0 +1,56 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelConstants_Slices.h defines the 3MF Model Constants of the slice extension. + +--*/ + +#ifndef __NMR_MESHINFORMATION_SLICES +#define __NMR_MESHINFORMATION_SLICES + +#define XML_3MF_ELEMENT_SLICESTACKRESOURCE "slicestack" +#define XML_3MF_ELEMENT_SLICEREFRESOURCE "sliceref" +#define XML_3MF_ELEMENT_SLICE "slice" +#define XML_3MF_ELEMENT_SLICEVERTICES "vertices" +#define XML_3MF_ELEMENT_SLICEVERTEX "vertex" +#define XML_3MF_ELEMENT_SLICEPOLYGON "polygon" +#define XML_3MF_ELEMENT_SLICESEGMENT "segment" + +#define XML_3MF_ATTRIBUTE_SLICESTACKZBOTTOM "zbottom" +#define XML_3MF_ATTRIBUTE_SLICESTACKID "id" +#define XML_3MF_ATTRIBUTE_SLICEZTOP "ztop" +#define XML_3MF_ATTRIBUTE_SLICEVERTEX_X "x" +#define XML_3MF_ATTRIBUTE_SLICEVERTEX_Y "y" +#define XML_3MF_ATTRIBUTE_SLICEPOLYGON_STARTV "startv" +#define XML_3MF_ATTRIBUTE_SLICESEGMENT_V2 "v2" + +#define XML_3MF_ATTRIBUTE_SLICEREF_ID "slicestackid" +#define XML_3MF_ATTRIBUTE_SLICEREF_PATH "slicepath" + +#endif + diff --git a/Include/Model/Classes/NMR_ModelContext.h b/Include/Model/Classes/NMR_ModelContext.h new file mode 100644 index 0000000..4e584c5 --- /dev/null +++ b/Include/Model/Classes/NMR_ModelContext.h @@ -0,0 +1,94 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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 NMR_MODELCONTEXT +#define NMR_MODELCONTEXT + +#include + +#include "Common/NMR_Types.h" +#include "Common/NMR_Local.h" +#include "Common/3MF_ProgressTypes.h" + +namespace NMR { + + class CModel; + class CKeyStore; + class CSecureContext; + class CProgressMonitor; + class CModelWarnings; + + using PModel = std::shared_ptr; + using PKeyStore = std::shared_ptr; + using PSecureContext = std::shared_ptr; + using PProgressMonitor = std::shared_ptr; + using PModelWarnings = std::shared_ptr; + + class CModelContext { + private: + PModel m_pModel; + PSecureContext m_pSecureContext; + PProgressMonitor m_pProgressMonitor; + PModelWarnings m_pWarnings; + PKeyStore m_pKeystore; + + protected: + + + public: + CModelContext() = delete; + CModelContext(_In_ PModel pModel); + virtual ~CModelContext() = default; + + inline PModel const & model() const{ + return m_pModel; + } + inline PProgressMonitor const & monitor() const{ + return m_pProgressMonitor; + } + + inline PModelWarnings const & warnings() const{ + return m_pWarnings; + } + + inline PKeyStore const & keyStore() const{ + return m_pKeystore; + } + + inline PSecureContext const & secureContext() const{ + return m_pSecureContext; + } + + nfBool isComplete() const; + + void SetProgressCallback(Lib3MFProgressCallback callback, void* userData); + }; +} +#endif // !NMR_MODELCONTEXT + diff --git a/Include/Model/Classes/NMR_ModelMeshBeamLatticeAttributes.h b/Include/Model/Classes/NMR_ModelMeshBeamLatticeAttributes.h new file mode 100644 index 0000000..afdd18c --- /dev/null +++ b/Include/Model/Classes/NMR_ModelMeshBeamLatticeAttributes.h @@ -0,0 +1,61 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelMeshBeamLatticeAttributes.h defines the Model Mesh BeamLattice Attributes +class and is part of the BeamLattice extension to 3MF + +--*/ + +#ifndef __NMR_MODELMESHBEAMLATTICEATTRIBUTES +#define __NMR_MODELMESHBEAMLATTICEATTRIBUTES + +#include "Model/Classes/NMR_ModelTypes.h" +#include "Model/Classes/NMR_Model.h" +#include "Common/NMR_Types.h" +#include +#include + +namespace NMR { + class CModelMeshBeamLatticeAttributes { + private: + public: + eModelBeamLatticeClipMode m_eClipMode; + nfBool m_bHasClippingMeshID; + PPackageResourceID m_pClippingMeshUniqueID; + nfBool m_bHasRepresentationMeshID; + PPackageResourceID m_pRepresentationUniqueID; + eModelBeamLatticeBallMode m_eBallMode; + + CModelMeshBeamLatticeAttributes(); + virtual ~CModelMeshBeamLatticeAttributes(); + }; + typedef std::shared_ptr PModelMeshBeamLatticeAttributes; +} + +#endif // __NMR_MODELMESHBEAMLATTICEATTRIBUTES + diff --git a/Include/Model/Classes/NMR_ModelMeshObject.h b/Include/Model/Classes/NMR_ModelMeshObject.h new file mode 100644 index 0000000..b040a46 --- /dev/null +++ b/Include/Model/Classes/NMR_ModelMeshObject.h @@ -0,0 +1,89 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelMeshObject.h defines the Model Mesh Object Class. +A model mesh object is an in memory representation of the 3MF +mesh object. + +--*/ + +#ifndef __NMR_MODELMESHOBJECT +#define __NMR_MODELMESHOBJECT + +#include "Common/Mesh/NMR_Mesh.h" +#include "Model/Classes/NMR_ModelObject.h" +#include "Model/Classes/NMR_ModelMeshBeamLatticeAttributes.h" + +namespace NMR { + + class CModel; + typedef std::shared_ptr PModel; + + class CModelObject; + typedef std::shared_ptr PModelObject; + + class CModelMeshObject : public CModelObject { + private: + PMesh m_pMesh; + PModelMeshBeamLatticeAttributes m_pBeamLatticeAttributes; + public: + CModelMeshObject() = delete; + CModelMeshObject(_In_ const ModelResourceID sID, _In_ CModel * pModel); + CModelMeshObject(_In_ const ModelResourceID sID, _In_ CModel * pModel, _In_ PMesh pMesh); + ~CModelMeshObject(); + + _Ret_notnull_ CMesh * getMesh (); + void setMesh (_In_ PMesh pMesh); + + void mergeToMesh(_In_ CMesh * pMesh, _In_ const NMATRIX3 mMatrix) override; + + void setObjectType(_In_ eModelObjectType ObjectType) override; + + // check, if the object is a valid object description + nfBool isValid() override; + + nfBool hasSlices(nfBool bRecursive) override; + nfBool isValidForSlices(const NMATRIX3& totalParentMatrix) override; + + virtual nfBool isValidForBeamLattices(); + + // check, if the mesh is manifold and oriented + virtual nfBool isManifoldAndOriented(); + + _Ret_notnull_ PModelMeshBeamLatticeAttributes getBeamLatticeAttributes(); + void setBeamLatticeAttributes(_In_ PModelMeshBeamLatticeAttributes pBeamLatticeAttributes); + + void extendOutbox(_Out_ NOUTBOX3& vOutBox, _In_ const NMATRIX3 mAccumulatedMatrix) override; + + }; + + typedef std::shared_ptr PModelMeshObject; + +} + +#endif // __NMR_MODELMESHOBJECT diff --git a/Include/Model/Classes/NMR_ModelMetaData.h b/Include/Model/Classes/NMR_ModelMetaData.h new file mode 100644 index 0000000..4f52966 --- /dev/null +++ b/Include/Model/Classes/NMR_ModelMetaData.h @@ -0,0 +1,79 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelMetaData.h defines the Model MetaData Class. +A metadata item is an in memory representation of the 3MF +metadata, and can be attached to any 3MF model node. + +--*/ + +#ifndef __NMR_MODELMETADATA +#define __NMR_MODELMETADATA + +#include "Common/NMR_Types.h" +#include "Common/Platform/NMR_SAL.h" +#include +#include +#include + +namespace NMR { + + class CModelMetaData { + private: + std::string m_sName; + std::string m_sNameSpace; + std::string m_sValue; + std::string m_sType; + nfBool m_bPreserve; + public: + CModelMetaData() = delete; + CModelMetaData(_In_ std::string sNameSpace, _In_ std::string sName, _In_ std::string sValue, + _In_ std::string sType, _In_ nfBool bPreserve); + + std::string getName(); + std::string getNameSpace(); + std::string getValue(); + std::string getType(); + nfBool getPreserve(); + + void setName(std::string ); + void setNameSpace(std::string); + void setValue(std::string); + void setType(std::string); + void setPreserve(nfBool); + + std::string getKey(); + + static bool isValidNamespaceAndName(std::string sNameSpace, std::string sName); + }; + + typedef std::shared_ptr PModelMetaData; + +} + +#endif // __NMR_MODELMETADATA diff --git a/Include/Model/Classes/NMR_ModelMetaDataGroup.h b/Include/Model/Classes/NMR_ModelMetaDataGroup.h new file mode 100644 index 0000000..f3b719e --- /dev/null +++ b/Include/Model/Classes/NMR_ModelMetaDataGroup.h @@ -0,0 +1,67 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelMetaDataGroup.h defines the Model MetaData Group Class. + +--*/ + +#ifndef __NMR_MODELMETADATAGROUP +#define __NMR_MODELMETADATAGROUP + +#include "Common/NMR_Types.h" +#include "Common/Platform/NMR_SAL.h" +#include +#include +#include +#include +#include "Model/Classes/NMR_ModelMetaData.h" + +namespace NMR { + + class CModelMetaDataGroup { + private: + std::vector m_MetaData; + std::map m_MetaDataMap; + public: + // CModelMetaDataGroup() = delete; + CModelMetaDataGroup(); + void clear(); + + PModelMetaData addMetaData(_In_ std::string sNameSpace, _In_ std::string sName, _In_ std::string sValue, _In_ std::string sType, _In_ nfBool bPreserve); + nfUint32 getMetaDataCount(); + PModelMetaData getMetaData(_In_ nfUint32 nIndex); + void removeMetaData(_In_ nfUint32 nIndex); + nfBool hasMetaData(_In_ std::string sKey); + void mergeMetaData(_In_ CModelMetaDataGroup * pSourceMetaDataGroup); + }; + + typedef std::shared_ptr PModelMetaDataGroup; + +} + +#endif // __NMR_MODELMETADATAGROUP diff --git a/Include/Model/Classes/NMR_ModelMultiPropertyGroup.h b/Include/Model/Classes/NMR_ModelMultiPropertyGroup.h new file mode 100644 index 0000000..b4d6ef9 --- /dev/null +++ b/Include/Model/Classes/NMR_ModelMultiPropertyGroup.h @@ -0,0 +1,83 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelCompositeMaterials.h defines the Model Color Group Resource Class. +A model color group resource is an in memory representation of the 3MF +color group resource object. + +--*/ + +#ifndef __NMR_MODELMULTIPROPERTYGROUP +#define __NMR_MODELMULTIPROPERTYGROUP + +#include "Model/Classes/NMR_ModelResource.h" +#include "Model/Classes/NMR_ModelTypes.h" +#include "Model/Classes/NMR_Model.h" +#include + +namespace NMR { + + class CModel; + typedef std::shared_ptr PModel; + + typedef std::vector CModelMultiProperty; + typedef std::shared_ptr PModelMultiProperty; + + class CModelMultiPropertyGroupResource : public CModelResource { + private: + std::map m_vctMultiProperties; + std::vector m_vctLayers; + + ModelPropertyID m_nNextPropertyID; + public: + CModelMultiPropertyGroupResource() = delete; + CModelMultiPropertyGroupResource(_In_ const ModelResourceID sID, _In_ CModel * pModel); + + nfUint32 getCount(); + nfUint32 addMultiProperty(_In_ PModelMultiProperty pMultiProperty); + PModelMultiProperty getMultiProperty(_In_ ModelPropertyID nPropertyID); + void setMultiProperty(_In_ ModelPropertyID nPropertyID, _In_ PModelMultiProperty pMultiProperty); + void removeMultiProperty(_In_ ModelPropertyID nPropertyID); + + nfUint32 getLayerCount(); + nfUint32 addLayer(_In_ MODELMULTIPROPERTYLAYER sLayer); + MODELMULTIPROPERTYLAYER getLayer(_In_ nfUint32 nIndex); + void setLayer(_In_ nfUint32 nIndex, _In_ MODELMULTIPROPERTYLAYER sLayer); + void removeLayer(_In_ nfUint32 nIndex); + + void mergeFrom(_In_ CModelMultiPropertyGroupResource * pSourceMultiMaterialGroup); + void buildResourceIndexMap(); + + static std::string blendMethodToString(_In_ eModelBlendMethod eBlendMethod); + static eModelBlendMethod stringToBlendMethod(_In_ std::string sBlendMethod); + }; + + typedef std::shared_ptr PModelMultiPropertyGroupResource; +} + +#endif // __NMR_MODELMULTIPROPERTYGROUP diff --git a/Include/Model/Classes/NMR_ModelObject.h b/Include/Model/Classes/NMR_ModelObject.h new file mode 100644 index 0000000..8195083 --- /dev/null +++ b/Include/Model/Classes/NMR_ModelObject.h @@ -0,0 +1,127 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelObject.h defines the Model Object Class. +A model object is an in memory representation of the 3MF +model object. + +--*/ + +#ifndef __NMR_MODELOBJECT +#define __NMR_MODELOBJECT + +#include "Model/Classes/NMR_Model.h" +#include "Model/Classes/NMR_ModelResource.h" +#include "Model/Classes/NMR_ModelAttachment.h" +#include "Model/Classes/NMR_ModelMetaDataGroup.h" +#include "Model/Classes/NMR_ModelSliceStack.h" +#include "Common/NMR_Types.h" +#include "Common/Math/NMR_Matrix.h" + +#include + +namespace NMR { + + class CModel; + typedef std::shared_ptr PModel; + + class CModelObject : public CModelResource { + private: + std::string m_sName; + std::string m_sPartNumber; + PModelSliceStack m_pSliceStack; + eModelSlicesMeshResolution m_eSlicesMeshResolution; + PModelMetaDataGroup m_MetaDataGroup; + + nfUint32 m_nComponentDepthLevel; + + private: + PUUID m_UUID; + PModelAttachment m_pThumbnailAttachment; + eModelObjectType m_ObjectType; + public: + CModelObject() = delete; + CModelObject(_In_ const ModelResourceID sID, _In_ CModel * pModel); + + // setter/getter for name + // the name may be an arbitrary string + std::string getName(); + void setName(_In_ std::string sName); + + // setter/getter for part number + // the part number may be an arbitrary string + std::string getPartNumber(); + void setPartNumber(_In_ std::string sPartNumber); + + // Production Extension + PUUID uuid(); + void setUUID(PUUID uuid); + + // MetaDataGroup + PModelMetaDataGroup metaDataGroup(); + + // setter/getter for the object type + eModelObjectType getObjectType(); + virtual void setObjectType(_In_ eModelObjectType ObjectType); + std::string getObjectTypeString(); + nfBool setObjectTypeString(_In_ std::string sTypeString, _In_ nfBool bRaiseException); + + // Merge the object into a mesh object + virtual void mergeToMesh(_In_ CMesh * pMesh, _In_ const NMATRIX3 mMatrix); + void mergeToMesh(_In_ CMesh * pMesh); + + // check, if the object is a valid object description + virtual nfBool isValid() = 0; + + virtual nfBool hasSlices(nfBool bRecursive) = 0; + virtual nfBool isValidForSlices(const NMATRIX3& totalParentMatrix) = 0; + + void assignSliceStack(PModelSliceStack pSliceStackId); + PModelSliceStack getSliceStack(); + + void setSlicesMeshResolution(eModelSlicesMeshResolution eMeshResolution); + eModelSlicesMeshResolution slicesMeshResolution() const; + + // Set/Get Thumbnail + void clearThumbnailAttachment(); + void setThumbnailAttachment(_In_ PModelAttachment pThumbnailAttachment, bool bThrowIfIncorrect); + PModelAttachment getThumbnailAttachment(); + + // Calculates the component Depths + nfUint32 getComponentDepthLevel (); + void clearComponentDepthLevel(); + virtual void calculateComponentDepthLevel (nfUint32 nLevel); + + virtual void extendOutbox(_Out_ NOUTBOX3& vOutBox, _In_ const NMATRIX3 mAccumulatedMatrix) = 0; + + }; + + typedef std::shared_ptr PModelObject; +} + +#endif // __NMR_MODELOBJECT diff --git a/Include/Model/Classes/NMR_ModelResource.h b/Include/Model/Classes/NMR_ModelResource.h new file mode 100644 index 0000000..95eef8e --- /dev/null +++ b/Include/Model/Classes/NMR_ModelResource.h @@ -0,0 +1,78 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelResource.h defines the Model Resource Class. +A model resource is an in memory representation of the 3MF +resource object. + +--*/ + +#ifndef __NMR_MODELRESOURCE +#define __NMR_MODELRESOURCE + +#include "Model/Classes/NMR_ModelMetaData.h" +#include "Common/NMR_Types.h" +#include "Model/Classes/NMR_ModelTypes.h" +#include "Model/Classes/NMR_Model.h" + +#include + +namespace NMR { + + class CModelResource { + private: + CModel * m_pModel; + PPackageResourceID m_pPackageResourceID; + + protected: + std::vector m_ResourceIndexMap; + nfBool m_bHasResourceIndexMap; + CModel * Model(); + + public: + CModelResource() = delete; + // CModelResource(_In_ const PPackageResourceID sResourceID, _In_ CModel * pModel); + CModelResource(_In_ const ModelResourceID sResourceID, _In_ CModel * pModel); + virtual ~CModelResource(); + + virtual PPackageResourceID getPackageResourceID(); + void setPackageResourceID(PPackageResourceID pID); + + bool mapResourceIndexToPropertyID (_In_ ModelResourceIndex nPropertyIndex, _Out_ ModelPropertyID & nPropertyID); + void clearResourceIndexMap(); + virtual void buildResourceIndexMap(); + nfBool hasResourceIndexMap(); + + _Ret_notnull_ CModel * getModel(); + }; + + typedef std::shared_ptr PModelResource; + +} + +#endif // __NMR_MODELRESOURCE diff --git a/Include/Model/Classes/NMR_ModelSlice.h b/Include/Model/Classes/NMR_ModelSlice.h new file mode 100644 index 0000000..123cb37 --- /dev/null +++ b/Include/Model/Classes/NMR_ModelSlice.h @@ -0,0 +1,91 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelSlice.h: defines the Model Slice Class. +A Model Slice represents a single slice as vertices and polygons + +--*/ + +#ifndef __NMR_MODELSLICE +#define __NMR_MODELSLICE + +#include "Common/NMR_Types.h" +#include "Common/Mesh/NMR_MeshTypes.h" +#include "Model/Classes/NMR_ModelResource.h" + +#include + +namespace NMR { + class CSlice { + private: + std::vector m_Vertices; + std::vector> m_Polygons; + + nfDouble m_dZTop; + + public: + CSlice() = delete; + CSlice(nfDouble dZTop); + CSlice(CSlice&); + ~CSlice(); + + void Clear(); + + nfUint32 addVertex(nfFloat x, nfFloat y); + + void getVertex(nfUint32 nIndex, nfFloat *x, nfFloat *y); + + nfUint32 beginPolygon(); + + void addPolygonIndex(nfUint32 nPolygonIndex, nfUint32 nIndex); + + void clearPolygon(nfUint32 nPolygonIndex); + + nfUint32 getPolygonCount(); + + nfDouble getTopZ(); + + void setTopZ(nfDouble dZTop); + + _Ret_notnull_ SLICENODE *getNode(nfUint32 nIndex); + + nfUint32 getPolygonIndex(nfUint32 nPolygonIndex, nfUint32 nIndexOfIndex); + + nfUint32 getPolygonIndexCount(nfUint32 nPolygonIndex); + + nfUint32 getVertexCount(); + + bool allPolygonsAreClosed(); + + bool isPolygonValid(nfUint32 nPolygonIndex); + }; + + typedef std::shared_ptr PSlice; +} + +#endif // __NMR_MODELSLICE diff --git a/Include/Model/Classes/NMR_ModelSliceStack.h b/Include/Model/Classes/NMR_ModelSliceStack.h new file mode 100644 index 0000000..2c64a44 --- /dev/null +++ b/Include/Model/Classes/NMR_ModelSliceStack.h @@ -0,0 +1,88 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelSliceStack.h: defines the Model Slice Stack Class. +A Model Slice Stack represents a ordered list of slices. + +--*/ + +#ifndef __NMR_MODELSLICESTACK +#define __NMR_MODELSLICESTACK + +#include "Common/NMR_Types.h" +#include "Common/Mesh/NMR_MeshTypes.h" +#include "Model/Classes/NMR_ModelResource.h" +#include "Model/Classes/NMR_ModelSlice.h" + +#include + +namespace NMR { + + + class CModelSliceStack : public CModelResource { + private: + nfDouble m_dZBottom; + + std::vector m_pSliceRefs; + std::vector m_pSlices; + public: + bool AllowsGeometry() const; + bool AllowsReferences() const; + + public: + CModelSliceStack() = delete; + CModelSliceStack(_In_ const ModelResourceID sID, _In_ CModel * pModel, nfDouble dZBottom); + + ~CModelSliceStack(); + + PSlice AddSlice(const nfDouble dZTop); + void AddSliceRef(PModelSliceStack pOtherStack, bool bPedantic = true); + + nfUint32 getSliceCount(); + PSlice getSlice(nfUint32 nIndex); + + nfUint32 getSliceRefCount(); + PModelSliceStack getSliceRef(nfUint32 nIndex); + + nfDouble getZBottom(); + void setZBottom(nfDouble dBottomZ); + + nfDouble getHighestZ() const; + + void CollapseSliceReferences(); + + std::string OwnPath(); + void SetOwnPath(std::string); + + bool areAllPolygonsClosed(); + }; + + typedef std::shared_ptr PModelSliceStack; +} + +#endif // __NMR_MODELSLICESTACK diff --git a/Include/Model/Classes/NMR_ModelTexture2D.h b/Include/Model/Classes/NMR_ModelTexture2D.h new file mode 100644 index 0000000..1cae97b --- /dev/null +++ b/Include/Model/Classes/NMR_ModelTexture2D.h @@ -0,0 +1,118 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelTexture2D.h defines the Model Texture 2D Class. + +--*/ + +#ifndef __NMR_MODELTEXTURE2D +#define __NMR_MODELTEXTURE2D + +#include "Common/NMR_Types.h" + + +#include "Model/Classes/NMR_ModelResource.h" +#include "Model/Classes/NMR_Model.h" +#include +#include "Common/Platform/NMR_ImportStream.h" +#include +#include +#include + +namespace NMR { + + class CModel; + typedef std::shared_ptr PModel; + + class CModelTexture2DResource : public CModelResource { + private: + PModelAttachment m_pAttachment; + + eModelTexture2DType m_ContentType; + + nfBool m_bHasBox2D; + nfFloat m_fBox2D_U; + nfFloat m_fBox2D_V; + nfFloat m_fBox2D_Width; + nfFloat m_fBox2D_Height; + eModelTextureTileStyle m_eTileStyleU; + eModelTextureTileStyle m_eTileStyleV; + eModelTextureFilter m_eFilter; + + protected: + CModelTexture2DResource(_In_ const ModelResourceID sID, _In_ CModel * pModel, _In_ PModelAttachment pAttachment); + + public: + CModelTexture2DResource() = delete; + + static PModelTexture2DResource make(_In_ const ModelResourceID sID, _In_ CModel * pModel, _In_ PModelAttachment pAttachment); + + + PModelAttachment getAttachment(); + void setAttachment(PModelAttachment); + + // getters/setters ContentType + eModelTexture2DType getContentType(); + void setContentType(_In_ eModelTexture2DType ContentType); + std::string getContentTypeString(); + void setContentTypeString(_In_ std::string sValue, _In_ nfBool bFailIfUnknown); + void setTileStyleUString(_In_ std::string sValue); + void setTileStyleVString(_In_ std::string sValue); + void setFilterFromString(_In_ std::string sValue); + + // getters/setters Box2D + nfBool getBox2D (_Out_ nfFloat & fU, _Out_ nfFloat & fV, _Out_ nfFloat & fWidth, _Out_ nfFloat & fHeight); + void setBox2D (_In_ nfFloat fU, _In_ nfFloat fV, _In_ nfFloat fWidth, _In_ nfFloat fHeight); + void clearBox2D (); + nfBool hasBox2D(); + + // getters/setters TileStyle + eModelTextureTileStyle getTileStyleU(); + eModelTextureTileStyle getTileStyleV(); + void setTileStyleU(_In_ eModelTextureTileStyle sStyle); + void setTileStyleV(_In_ eModelTextureTileStyle sStyle); + + eModelTextureFilter getFilter(); + void setFilter(_In_ eModelTextureFilter eFilter); + + // copy all parameters from source + void copyFrom(_In_ CModelTexture2DResource * pSourceTexture, _In_ nfBool bCopyAttachment); + + static eModelTextureTileStyle tileStyleFromString(_In_ std::string sValue); + static std::string tileStyleToString(_In_ eModelTextureTileStyle eTileStyle); + + static eModelTextureFilter filterFromString(_In_ std::string sValue); + static std::string filterToString(_In_ eModelTextureFilter eFilter); + }; + + typedef std::shared_ptr PModelTexture2DResource; + +} + +#endif // __NMR_MODELTEXTURE2D + diff --git a/Include/Model/Classes/NMR_ModelTexture2DGroup.h b/Include/Model/Classes/NMR_ModelTexture2DGroup.h new file mode 100644 index 0000000..fc24686 --- /dev/null +++ b/Include/Model/Classes/NMR_ModelTexture2DGroup.h @@ -0,0 +1,75 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelTexture2DGroup.h defines the Model Texture2D Group Resource Class. +A model color group resource is an in memory representation of the 3MF +texture2d group resource object. + +--*/ + +#ifndef __NMR_TEXTURE2DGROUP +#define __NMR_TEXTURE2DGROUP + +#include "Model/Classes/NMR_ModelResource.h" +#include "Model/Classes/NMR_ModelTypes.h" +#include "Model/Classes/NMR_Model.h" +#include + +namespace NMR { + + class CModel; + typedef std::shared_ptr PModel; + + class CModelTexture2DGroupResource : public CModelResource { + private: + PModelTexture2DResource m_pTexture2D; + std::map m_pUVCoordinates; + ModelPropertyID m_nNextPropertyID; + + public: + CModelTexture2DGroupResource() = delete; + CModelTexture2DGroupResource(_In_ const ModelResourceID sID, _In_ CModel * pModel, _In_ PModelTexture2DResource pTexture2D); + + nfUint32 addUVCoordinate(_In_ MODELTEXTURE2DCOORDINATE UV); + + nfUint32 getCount(); + void removePropertyID(_In_ ModelPropertyID nPropertyID); + void setUVCoordinate(_In_ ModelPropertyID nPropertyID, _In_ MODELTEXTURE2DCOORDINATE sCoordinate); + + MODELTEXTURE2DCOORDINATE getUVCoordinate(_In_ ModelPropertyID nPropertyID); + + void mergeFrom(_In_ CModelTexture2DGroupResource * pSourceMaterial); + void buildResourceIndexMap(); + + PModelTexture2DResource getTexture2D(); + }; + + typedef std::shared_ptr PModelTexture2DGroupResource; +} + +#endif // __NMR_TEXTURE2DGROUP diff --git a/Include/Model/Classes/NMR_ModelTextureAttachment.h b/Include/Model/Classes/NMR_ModelTextureAttachment.h new file mode 100644 index 0000000..1ba25d7 --- /dev/null +++ b/Include/Model/Classes/NMR_ModelTextureAttachment.h @@ -0,0 +1,58 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelTexureAttachment.h defines the Model Texture Attachment Class. + +--*/ + +#ifndef __NMR_MODELTEXTUREATTACHMENT +#define __NMR_MODELTEXTUREATTACHMENT + +#include "Model/Classes/NMR_Model.h" +#include "Model/Classes/NMR_ModelAttachment.h" + +#include + +namespace NMR { + + class CModelTextureAttachment: public CModelAttachment { + + public: + CModelTextureAttachment() = delete; + CModelTextureAttachment(_In_ CModel * pModel, _In_ const std::wstring sPathURI, _In_ const std::wstring sRelationShipType, _In_ PImportStream pStream) = delete; + CModelTextureAttachment(_In_ CModel * pModel, _In_ const std::wstring sPathURI, _In_ PImportStream pStream); + ~CModelTextureAttachment(); + + void setRelationShipType(_In_ const std::wstring sRelationShipType) = delete; + }; + + typedef std::shared_ptr PModelTextureAttachment; + +} + +#endif // __NMR_MODELTEXTUREATTACHMENT diff --git a/Include/Model/Classes/NMR_ModelTypes.h b/Include/Model/Classes/NMR_ModelTypes.h new file mode 100644 index 0000000..a63ea06 --- /dev/null +++ b/Include/Model/Classes/NMR_ModelTypes.h @@ -0,0 +1,197 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelTypes.h defines 3MF Model Type Definitions + +--*/ + +#ifndef __NMR_MODELTYPES +#define __NMR_MODELTYPES + +#include "Common/Platform/NMR_WinTypes.h" + +#define MODELREADERCLASS_3MF "3mf" +#define MODELWRITERCLASS_3MF "3mf" + +#define MODELREADERCLASS_STL "stl" +#define MODELWRITERCLASS_STL "stl" + +#define MODEL_MAXSTRINGBUFFERLENGTH 1073741823 // (Safe margin for buffer overflows: 2^30 - 1) + +namespace NMR { + +#pragma pack (1) + + typedef struct { + FLOAT m_fPosition[3]; + } MODELMESHVERTEX; + + typedef struct { + DWORD m_nIndices[3]; + } MODELMESHTRIANGLE; + + enum eModelBeamLatticeClipMode { + MODELBEAMLATTICECLIPMODE_NONE = 0, + MODELBEAMLATTICECLIPMODE_INSIDE = 1, + MODELBEAMLATTICECLIPMODE_OUTSIDE = 2 + }; + + enum eModelSlicesMeshResolution { + MODELSLICESMESHRESOLUTION_FULL = 0, + MODELSLICESMESHRESOLUTION_LOW = 1 + }; + + enum eModelBeamLatticeCapMode { + MODELBEAMLATTICECAPMODE_SPHERE = 0, + MODELBEAMLATTICECAPMODE_HEMISPHERE = 1, + MODELBEAMLATTICECAPMODE_BUTT = 2 + }; + + enum eModelBeamLatticeBallMode { + MODELBEAMLATTICEBALLMODE_NONE = 0, + MODELBEAMLATTICEBALLMODE_MIXED = 1, + MODELBEAMLATTICEBALLMODE_ALL = 2 + }; + + typedef struct MODELMESHBEAM { + DWORD m_nIndices[2]; + DOUBLE m_dRadius[2]; // the radius of end 0 or 1 of this beam + eModelBeamLatticeCapMode m_eCapMode[2]; + MODELMESHBEAM() { + m_eCapMode[0] = MODELBEAMLATTICECAPMODE_SPHERE; + m_eCapMode[1] = MODELBEAMLATTICECAPMODE_SPHERE; + } + } MODELMESHBEAM; + + typedef struct MODELMESHBALL { + DWORD m_nIndex; + DOUBLE m_dRadius; // the radius of this ball + MODELMESHBALL() { + } + } MODELMESHBALL; + + typedef struct { + FLOAT m_fFields[3][4]; + } MODELTRANSFORM; + + typedef struct { + BYTE m_Red; + BYTE m_Green; + BYTE m_Blue; + BYTE m_Alpha; + } MODELMESHCOLOR_SRGB; + + typedef struct { + DWORD m_nTextureID; + FLOAT m_fU[3]; + FLOAT m_fV[3]; + } MODELMESHTEXTURE2D; + + typedef struct { + DOUBLE m_dU; + DOUBLE m_dV; + } MODELTEXTURE2DCOORDINATE; + + typedef struct { + MODELMESHCOLOR_SRGB m_Colors[3]; + } MODELMESH_TRIANGLECOLOR_SRGB; + +#pragma pack() + + typedef DWORD ModelPropertyID; + typedef DWORD ModelResourceID; + typedef DWORD UniqueResourceID; + typedef DWORD ModelResourceIndex; + + enum eModelUnit { + MODELUNIT_MICROMETER = 0, + MODELUNIT_MILLIMETER = 1, + MODELUNIT_CENTIMETER = 2, + MODELUNIT_INCH = 3, + MODELUNIT_FOOT = 4, + MODELUNIT_METER = 5 + }; + + enum eModelObjectType { + MODELOBJECTTYPE_OTHER = 0, + MODELOBJECTTYPE_MODEL = 1, + MODELOBJECTTYPE_SUPPORT = 2, + MODELOBJECTTYPE_SOLIDSUPPORT = 3, + MODELOBJECTTYPE_SURFACE = 4 + }; + + enum eModelPropertyType { + MODELPROPERTYTYPE_NONE = 0, + MODELPROPERTYTYPE_BASEMATERIALS = 1, + MODELPROPERTYTYPE_COLOR = 2, + MODELPROPERTYTYPE_TEXCOORD2D = 3, + MODELPROPERTYTYPE_COMPOSITE = 4, + }; + + enum eModelTexture2DType { + MODELTEXTURETYPE_UNKNOWN = 0, + MODELTEXTURETYPE_PNG = 1, + MODELTEXTURETYPE_JPEG = 2, + }; + + enum eModelTextureTileStyle { + MODELTEXTURETILESTYLE_WRAP = 0, + MODELTEXTURETILESTYLE_MIRROR = 1, + MODELTEXTURETILESTYLE_CLAMP = 2, + MODELTEXTURETILESTYLE_NONE = 3 + }; + + enum eModelTextureFilter { + MODELTEXTUREFILTER_AUTO = 0, + MODELTEXTUREFILTER_LINEAR = 1, + MODELTEXTUREFILTER_NEAREST = 2 + }; + + enum eModelBlendMethod { + MODELBLENDMETHOD_NONE = 0, + MODELBLENDMETHOD_MIX = 1, + MODELBLENDMETHOD_MULTIPLY = 2 + }; + + typedef struct { + FLOAT m_fPosition[2]; + } MODELSLICEVERTEX; + + typedef struct { + DOUBLE m_dMixingRatio; + ModelPropertyID m_nPropertyID; + } MODELCOMPOSITECONSTITUENT; + + typedef struct { + UniqueResourceID m_nUniqueResourceID; + eModelBlendMethod m_nMethod; + } MODELMULTIPROPERTYLAYER; + +} + +#endif // __NMR_MODELTYPES diff --git a/Include/Model/Classes/NMR_PackageResourceID.h b/Include/Model/Classes/NMR_PackageResourceID.h new file mode 100644 index 0000000..78dfe42 --- /dev/null +++ b/Include/Model/Classes/NMR_PackageResourceID.h @@ -0,0 +1,124 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_PackageResourceID.h defines the UniqueResourceID Class. + +--*/ + +#ifndef __NMR_PACKAGERESOURCEID +#define __NMR_PACKAGERESOURCEID + +#include "Model/Classes/NMR_ModelTypes.h" +#include + +#include +#include +#include +#include + +namespace NMR { + + class CResourceHandler; + + + class CPackageModelPath { + private: + CResourceHandler* m_pResourceHandler; + std::string m_sPath; + + public: + CPackageModelPath(CResourceHandler* pResourceHandler, std::string sPath); + + friend class CResourceHandler; + + std::string getPath(); + void setPath(std::string sPath); + }; + typedef std::shared_ptr PPackageModelPath; + + + class CPackageResourceID { + private: + CResourceHandler* m_pResourceHandler; + // combination of those two must be unique + PPackageModelPath m_pModelPath; + ModelResourceID m_id; + + // the unique Identifier that MUST not be persistent into a .3mf-file. + // it is only valid thoughout the lifetime of a NMR::CModel + UniqueResourceID m_uniqueID; + + void setUniqueID(UniqueResourceID id); + + public: + CPackageResourceID(CResourceHandler* pResourceHandler, PPackageModelPath pModelPath, ModelResourceID nID); + + friend class CResourceHandler; + + std::string getPath(); + PPackageModelPath getPackageModelPath(); + ModelResourceID getModelResourceID(); + UniqueResourceID getUniqueID(); + + static void setModelPath(std::shared_ptr pPackageResourceID, PPackageModelPath pPath); + CResourceHandler * getResourceHandler(); + }; + typedef std::shared_ptr PPackageResourceID; + + + using UniqueIDPackageIdMap = std::unordered_map; + using UniqueIdPackageIdPair = std::pair; + + class CResourceHandler { + private: + // getPath-strings to ModelPaths + std::unordered_map m_PathToModelPath; + + // unique IDs to CPackageResourceID + UniqueIDPackageIdMap m_resourceIDs; + std::map, PPackageResourceID> m_IdAndPathToPackageResourceIDs; + public: + PPackageResourceID makePackageResourceID(std::string path, ModelResourceID id); // this is supposed to be the only way to generate a CPackageResourceID + + PPackageResourceID findResourceIDByUniqueID(UniqueResourceID id); + PPackageResourceID findResourceIDByPair(std::string path, ModelResourceID id); + + PPackageModelPath findPackageModelPath(std::string sPath); + PPackageModelPath makePackageModelPath(std::string sPath); + + void updateModelPath(PPackageResourceID pPackageResourceID, PPackageModelPath pNewPath); + std::vector retrieveAllModelPaths(); + + void removePackageResourceID(PPackageResourceID pPackageResourceID); + + void clear(); + }; + +} + +#endif // __NMR_PACKAGERESOURCEID diff --git a/Include/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Ball.h b/Include/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Ball.h new file mode 100644 index 0000000..ec2b9f1 --- /dev/null +++ b/Include/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Ball.h @@ -0,0 +1,67 @@ +/*++ + +Copyright (C) 2020 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: +NMR_ModelReaderNode_BeamLattice1702_Ball.h covers the official 3MF beamlattice extension. + +--*/ + +#ifndef __NMR_MODELREADERNODE_BEAMLATTICE1702_BALL +#define __NMR_MODELREADERNODE_BEAMLATTICE1702_BALL + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Model/Classes/NMR_ModelObject.h" + +namespace NMR { + eModelBeamLatticeBallMode stringToBallMode(const nfChar * ballModeStr); + + class CModelReaderNode_BeamLattice1702_Ball : public CModelReaderNode { + private: + nfInt32 m_nIndex; + nfBool m_bHasRadius; + nfDouble m_dRadius; + nfBool m_bHasTag; + nfInt32 m_nTag; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue, _In_z_ const nfChar * pNameSpace); + public: + CModelReaderNode_BeamLattice1702_Ball() = delete; + CModelReaderNode_BeamLattice1702_Ball(_In_ CModel * pModel, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + + void retrieveIndex(_Out_ nfInt32 & nIndex, nfInt32 nNodeCount); + void retrieveRadius(_Out_ nfBool & bHasRadius, _Out_ nfDouble & dRadius); + void retrieveTag(_Out_ nfBool & bHasTag, _Out_ nfInt32 & tag); + }; + + typedef std::shared_ptr PModelReaderNode_BeamLattice1702_Ball; +} + +#endif // __NMR_MODELREADERNODE_BEAMLATTICE1702_BALL \ No newline at end of file diff --git a/Include/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BallRef.h b/Include/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BallRef.h new file mode 100644 index 0000000..fab2b2c --- /dev/null +++ b/Include/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BallRef.h @@ -0,0 +1,59 @@ +/*++ + +Copyright (C) 2020 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: +NMR_ModelReaderNode_BeamLattice1702_BallRef.h covers the official 3MF beamlattice extension. + +--*/ + +#ifndef __NMR_MODELREADERNODE_BEAMLATTICE1702_BALLREF +#define __NMR_MODELREADERNODE_BEAMLATTICE1702_BALLREF + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Model/Classes/NMR_ModelObject.h" + +namespace NMR { + + class CModelReaderNode_BeamLattice1702_BallRef : public CModelReaderNode { + private: + nfInt32 m_nIndex; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + public: + CModelReaderNode_BeamLattice1702_BallRef() = delete; + CModelReaderNode_BeamLattice1702_BallRef(_In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + void retrieveIndex(_Out_ nfInt32 & nIndex); + }; + + typedef std::shared_ptr PModelReaderNode_BeamLattice1702_BallRef; + +} + +#endif // __NMR_MODELREADERNODE_BEAMLATTICE1702_BALLREF diff --git a/Include/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Balls.h b/Include/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Balls.h new file mode 100644 index 0000000..6ccc664 --- /dev/null +++ b/Include/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Balls.h @@ -0,0 +1,61 @@ +/*++ + +Copyright (C) 2020 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_BeamLattice1702_Balls.h covers the official 3MF beamlattice extension. + +--*/ + +#ifndef __NMR_MODELREADERNODE_BEAMLATTICE1702_BALLS +#define __NMR_MODELREADERNODE_BEAMLATTICE1702_BALLS + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelObject.h" + +namespace NMR { + + class CModelReaderNode_BeamLattice1702_Balls : public CModelReaderNode { + protected: + CMesh* m_pMesh; + CModel* m_pModel; + + nfDouble m_dDefaultBallRadius; + + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode_BeamLattice1702_Balls() = delete; + CModelReaderNode_BeamLattice1702_Balls(_In_ CModel * pModel, _In_ CMesh * pMesh, _In_ nfDouble defaultBallRadius, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + + typedef std::shared_ptr PModelReaderNode_BeamLattice1702_Balls; +} + +#endif // __NMR_MODELREADERNODE_BEAMLATTICE1702_BALLS \ No newline at end of file diff --git a/Include/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Beam.h b/Include/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Beam.h new file mode 100644 index 0000000..35aa181 --- /dev/null +++ b/Include/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Beam.h @@ -0,0 +1,77 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: +NMR_ModelReaderNode_BeamLattice1702_Beam.h covers the official 3MF beamlattice extension. +(Initial version based on private beam extension) + +--*/ + +#ifndef __NMR_MODELREADERNODE_BEAMLATTICE1702_BEAM +#define __NMR_MODELREADERNODE_BEAMLATTICE1702_BEAM + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Model/Classes/NMR_ModelObject.h" + +namespace NMR { + eModelBeamLatticeCapMode stringToCapMode(const nfChar * capModeStr); + + class CModelReaderNode_BeamLattice1702_Beam : public CModelReaderNode { + private: + nfInt32 m_nIndex1; + nfInt32 m_nIndex2; + nfBool m_bHasRadius1; + nfBool m_bHasRadius2; + nfDouble m_dRadius1; + nfDouble m_dRadius2; + nfBool m_bHasTag; + nfInt32 m_nTag; + nfBool m_bHasCap1; + nfBool m_bHasCap2; + eModelBeamLatticeCapMode m_eCapMode1; + eModelBeamLatticeCapMode m_eCapMode2; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue, _In_z_ const nfChar * pNameSpace); + public: + CModelReaderNode_BeamLattice1702_Beam() = delete; + CModelReaderNode_BeamLattice1702_Beam(_In_ CModel * pModel, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + + void retrieveIndices(_Out_ nfInt32 & nIndex1, _Out_ nfInt32 & nIndex2, nfInt32 nNodeCount); + void retrieveRadii(_Out_ nfBool & bHasRadius1, _Out_ nfDouble & dRadius1, _Out_ nfBool & bHasRadius2, _Out_ nfDouble & dRadius2); + void retrieveCapModes(_Out_ nfBool & bHasCapMode1, _Out_ eModelBeamLatticeCapMode & eCapMode1, _Out_ nfBool & bHasCapMode2, _Out_ eModelBeamLatticeCapMode & eCapMode2); + void retrieveTag(_Out_ nfBool & bHasTag, _Out_ nfInt32 & nTag); + }; + + typedef std::shared_ptr PModelReaderNode_BeamLattice1702_Beam; + +} + +#endif // __NMR_MODELREADERNODE_BEAMLATTICE1702_BEAM diff --git a/Include/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BeamLattice.h b/Include/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BeamLattice.h new file mode 100644 index 0000000..f909ed3 --- /dev/null +++ b/Include/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BeamLattice.h @@ -0,0 +1,77 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: +NMR_ModelReaderNode_BeamLattice1702_BeamLattice.h covers the official 3MF beamlattice extension. +(Initial version based on private beam extension) + + +--*/ + +#ifndef __NMR_MODELREADERNODE_BEAMLATTICE1702_BEAMLATTICE +#define __NMR_MODELREADERNODE_BEAMLATTICE1702_BEAMLATTICE + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Model/Classes/NMR_ModelObject.h" + +namespace NMR { + + class CModelReaderNode_BeamLattice1702_BeamLattice : public CModelReaderNode { + private: + CModel * m_pModel; + CMesh * m_pMesh; + + eModelBeamLatticeClipMode m_eClipMode; + nfBool m_bHasClippingMeshID; + ModelResourceID m_nClippingMeshID; + nfBool m_bHasRepresentationMeshID; + ModelResourceID m_nRepresentationMeshID; + nfDouble m_dDefaultRadius; + eModelBeamLatticeCapMode m_eDefaultCapMode; + nfDouble m_dDefaultBallRadius; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue, _In_z_ const nfChar * pNameSpace); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode_BeamLattice1702_BeamLattice() = delete; + CModelReaderNode_BeamLattice1702_BeamLattice(_In_ CModel * pModel, _In_ CMesh * pMesh, _In_ PModelWarnings pWarnings); + + void retrieveClippingInfo(_Out_ eModelBeamLatticeClipMode &eClipMode, _Out_ nfBool & bHasClippingMode, _Out_ ModelResourceID & nClippingMeshID); + void retrieveRepresentationInfo(_Out_ nfBool & bHasRepresentation, _Out_ ModelResourceID & nRepresentationMeshID); + void validateBallOptions(_In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + + }; + + typedef std::shared_ptr PModelReaderNode_BeamLattice1702_BeamLattice; + +} + +#endif // __NMR_MODELREADERNODE_BEAMLATTICE1702_BEAMLATTICE diff --git a/Include/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BeamSet.h b/Include/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BeamSet.h new file mode 100644 index 0000000..14cd3f9 --- /dev/null +++ b/Include/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BeamSet.h @@ -0,0 +1,66 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: +NMR_ModelReaderNode_BeamLattice1702_BeamSet.h covers the official 3MF beamlattice extension. + +--*/ + +#ifndef __NMR_MODELREADERNODE_BEAMLATTICE1702_BEAMSET +#define __NMR_MODELREADERNODE_BEAMLATTICE1702_BEAMSET + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Model/Classes/NMR_ModelObject.h" + +#include + +namespace NMR { + + class CModelReaderNode_BeamLattice1702_BeamSet : public CModelReaderNode { + private: + BEAMSET * m_pBeamSet; + + std::unordered_set * m_pUniqueIdentifiers; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue, _In_z_ const nfChar * pNameSpace); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode_BeamLattice1702_BeamSet() = delete; + CModelReaderNode_BeamLattice1702_BeamSet(_In_ BEAMSET * pBeamSet, _In_ std::unordered_set * pUniqueIdentifiers, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + + // void retrieveId(_Out_ nfInt32 & nIndex1, _Out_ nfInt32 & nIndex2, nfInt32 nNodeCount); + }; + + typedef std::shared_ptr PModelReaderNode_BeamLattice1702_BeamSet; + +} + +#endif // __NMR_MODELREADERNODE_BEAMLATTICE1702_BEAMSET diff --git a/Include/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BeamSets.h b/Include/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BeamSets.h new file mode 100644 index 0000000..3257753 --- /dev/null +++ b/Include/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BeamSets.h @@ -0,0 +1,63 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_BeamLattice1702_BeamSets.h covers the official 3MF beamlattice extension. + +--*/ + +#ifndef __NMR_MODELREADERNODE_BEAMLATTICE1702_BEAMSETS +#define __NMR_MODELREADERNODE_BEAMLATTICE1702_BEAMSETS + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelObject.h" + +#include + +namespace NMR { + + class CModelReaderNode_BeamLattice1702_BeamSets : public CModelReaderNode { + private: + std::unordered_set m_uniqueIdentifiers; // Data structure used to ensure beamsets have unique identifiers + protected: + CMesh * m_pMesh; + + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode_BeamLattice1702_BeamSets() = delete; + CModelReaderNode_BeamLattice1702_BeamSets(_In_ CMesh * pMesh, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + + typedef std::shared_ptr PModelReaderNode_BeamLattice1702_BeamSets; + +} + +#endif // __NMR_MODELREADERNODE_BEAMLATTICE1702_BEAMSETS diff --git a/Include/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Beams.h b/Include/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Beams.h new file mode 100644 index 0000000..b379491 --- /dev/null +++ b/Include/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Beams.h @@ -0,0 +1,65 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_BeamLattice1702_Beams.h covers the official 3MF beamlattice extension. +(Initial version based on private beam extension) + + +--*/ + +#ifndef __NMR_MODELREADERNODE_BEAMLATTICE1702_BEAMS +#define __NMR_MODELREADERNODE_BEAMLATTICE1702_BEAMS + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelObject.h" + +namespace NMR { + + class CModelReaderNode_BeamLattice1702_Beams : public CModelReaderNode { + protected: + CMesh * m_pMesh; + CModel * m_pModel; + + nfDouble m_dDefaultRadius; + eModelBeamLatticeCapMode m_eDefaultCapMode; + + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode_BeamLattice1702_Beams() = delete; + CModelReaderNode_BeamLattice1702_Beams(_In_ CModel * pModel, _In_ CMesh * pMesh, _In_ nfDouble defaultRadius, _In_ eModelBeamLatticeCapMode defaultCapMode, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + + typedef std::shared_ptr PModelReaderNode_BeamLattice1702_Beams; + +} + +#endif // __NMR_MODELREADERNODE_BEAMLATTICE1702_BEAMS diff --git a/Include/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Ref.h b/Include/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Ref.h new file mode 100644 index 0000000..936bd2e --- /dev/null +++ b/Include/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Ref.h @@ -0,0 +1,59 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: +NMR_ModelReaderNode_BeamLattice1702_Ref.h covers the official 3MF beamlattice extension. + +--*/ + +#ifndef __NMR_MODELREADERNODE_BEAMLATTICE1702_REF +#define __NMR_MODELREADERNODE_BEAMLATTICE1702_REF + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Model/Classes/NMR_ModelObject.h" + +namespace NMR { + + class CModelReaderNode_BeamLattice1702_Ref : public CModelReaderNode { + private: + nfInt32 m_nIndex; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + public: + CModelReaderNode_BeamLattice1702_Ref() = delete; + CModelReaderNode_BeamLattice1702_Ref(_In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + void retrieveIndex(_Out_ nfInt32 & nIndex); + }; + + typedef std::shared_ptr PModelReaderNode_BeamLattice1702_Ref; + +} + +#endif // __NMR_MODELREADERNODE_BEAMLATTICE1702_REF diff --git a/Include/Model/Reader/NMR_KeyStoreOpcPackageReader.h b/Include/Model/Reader/NMR_KeyStoreOpcPackageReader.h new file mode 100644 index 0000000..41f7d34 --- /dev/null +++ b/Include/Model/Reader/NMR_KeyStoreOpcPackageReader.h @@ -0,0 +1,76 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_KeyStoreOpcPackageReader.h defines an OPC Package reader in a portable way. + +--*/ + +#ifndef NMR_KEYSTOREOPCPACKAGEREADER +#define NMR_KEYSTOREOPCPACKAGEREADER + +#include +#include +#include + +#include "Common/NMR_SecureContentTypes.h" +#include "Common/OPC/NMR_IOpcPackageReader.h" +#include "Common/Platform/NMR_ImportStream.h" +#include "Common/3MF_ProgressMonitor.h" +#include "Common/NMR_ModelWarnings.h" + +namespace NMR { + + class CModelContext; + + + class CKeyStoreOpcPackageReader: public IOpcPackageReader { + private: + CModelContext const & m_pContext; + PIOpcPackageReader m_pPackageReader; + std::map m_encryptedParts; + protected: + NMR::PImportStream findKeyStoreStream(); + void parseKeyStore(NMR::PImportStream keyStoreStream); + void openAllResourceDataGroups(); + void checkAuthenticatedTags(); + public: + CKeyStoreOpcPackageReader(_In_ PImportStream pImportStream, _In_ CModelContext const & context); + + // Inherited via IOpcPackageReader + virtual COpcPackageRelationship * findRootRelation(std::string sRelationType, nfBool bMustBeUnique) override; + virtual POpcPackagePart createPart(std::string sPath) override; + virtual nfUint64 getPartSize(std::string sPath) override; + + void close() override; + }; + + using PKeyStoreOpcPackageReader = std::shared_ptr; + +} + +#endif // !NMR_KEYSTOREOPCPACKAGEREADER diff --git a/Include/Model/Reader/NMR_ModelReader.h b/Include/Model/Reader/NMR_ModelReader.h new file mode 100644 index 0000000..5f0b95b --- /dev/null +++ b/Include/Model/Reader/NMR_ModelReader.h @@ -0,0 +1,70 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReader.h defines the Model Reader Class. +A model reader reads in a model file and generates an in-memory representation of it. + +--*/ + +#ifndef __NMR_MODELREADER +#define __NMR_MODELREADER + +#include "Model/Classes/NMR_ModelContext.h" +#include "Common/NMR_ModelWarnings.h" +#include "Common/MeshImport/NMR_MeshImporter.h" + +#include +#include + +namespace NMR { + + class CModelReader : public CModelContext { + protected: + PImportStream m_pPrintTicketStream; + std::string m_sPrintTicketContentType; + std::set m_RelationsToRead; + + + void readFromMeshImporter(_In_ CMeshImporter * pImporter); + public: + CModelReader() = delete; + CModelReader(_In_ PModel pModel); + virtual ~CModelReader() = default; + + virtual void readStream(_In_ PImportStream pStream) = 0; + PImportStream retrievePrintTicket(_Out_ std::string & sContentType); + + void addRelationToRead(_In_ std::string sRelationShipType); + void removeRelationToRead(_In_ std::string sRelationShipType); + }; + + typedef std::shared_ptr PModelReader; + +} + +#endif // __NMR_MODELREADER diff --git a/Include/Model/Reader/NMR_ModelReaderNode.h b/Include/Model/Reader/NMR_ModelReaderNode.h new file mode 100644 index 0000000..9e634ea --- /dev/null +++ b/Include/Model/Reader/NMR_ModelReaderNode.h @@ -0,0 +1,80 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode.h defines the Model Reader Node Class. +A model reader node is an abstract base class for all XML nodes of a 3MF Model Stream. + +--*/ + +#ifndef __NMR_MODELREADERNODE +#define __NMR_MODELREADERNODE + +#include "Model/Classes/NMR_Model.h" +#include "Common/NMR_ModelWarnings.h" +#include "Common/Platform/NMR_XmlReader.h" +#include "Common/3MF_ProgressMonitor.h" + +namespace NMR { + + class CModelReaderNode { + private: + std::string m_sName; + nfBool m_bParsedAttributes; + nfBool m_bParsedContent; + nfBool m_bIsEmptyElement; + + protected: + PProgressMonitor m_pProgressMonitor; + PModelWarnings m_pWarnings; + + void parseName(_In_ CXmlReader * pXMLReader); + void parseAttributes(_In_ CXmlReader * pXMLReader); + void parseContent(_In_ CXmlReader * pXMLReader); + + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnText(_In_z_ const nfChar * pText, _In_ CXmlReader * pXMLReader); + virtual void OnEndElement(_In_ CXmlReader * pXMLReader); + + virtual void OnNSAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue, _In_z_ const nfChar * pNameSpace); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode() = delete; + CModelReaderNode(_In_ PModelWarnings pWarnings, _In_ PProgressMonitor pProgressMonitor = nullptr); + virtual ~CModelReaderNode() = default; + + std::string getName(); + PModelWarnings getWarnings() const; + + virtual void parseXML(_In_ CXmlReader * pXMLReader) = 0; + }; + + typedef std::shared_ptr PModelReaderNode; + +} + +#endif // __NMR_MODELREADERNODE diff --git a/Include/Model/Reader/NMR_ModelReaderNode_KeyStoreBase.h b/Include/Model/Reader/NMR_ModelReaderNode_KeyStoreBase.h new file mode 100644 index 0000000..6b076bd --- /dev/null +++ b/Include/Model/Reader/NMR_ModelReaderNode_KeyStoreBase.h @@ -0,0 +1,66 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_KeyStoreBase.h defines the base class for all Model Reader Node classes that are related to . + +--*/ + +#ifndef __NMR_MODELREADERNODE_KEYSTOREBASE +#define __NMR_MODELREADERNODE_KEYSTOREBASE + +#include "Common/NMR_Local.h" +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_Model.h" +#include "Model/Classes/NMR_KeyStore.h" +#include +namespace NMR { + + class CModelReaderNode_KeyStoreBase : public CModelReaderNode { + protected: + CKeyStore * const m_pKeyStore; + CModel * const m_pModel; + + public: + CModelReaderNode_KeyStoreBase() = delete; + CModelReaderNode_KeyStoreBase(_In_ CModel * const pModel, _In_ CKeyStore * const pKeyStore, _In_ PModelWarnings pWarnings); + + inline CKeyStore * const keystore() const { + return m_pKeyStore; + } + + inline CModel * const model() const { + return m_pModel; + } + + template std::shared_ptr extractCopy() const { + return std::make_shared(model(), keystore(), getWarnings()); + } + }; +} + +#endif // __NMR_MODELREADERNODE_KEYSTOREBASE diff --git a/Include/Model/Reader/NMR_ModelReaderNode_ModelBase.h b/Include/Model/Reader/NMR_ModelReaderNode_ModelBase.h new file mode 100644 index 0000000..8b23493 --- /dev/null +++ b/Include/Model/Reader/NMR_ModelReaderNode_ModelBase.h @@ -0,0 +1,83 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_ModelBase.h defines the Model Reader Model Node Class. +A model reader model node is a parser for the root node of an XML Model Stream. + +--*/ + +#ifndef __NMR_MODELREADERNODE_MODELBASE +#define __NMR_MODELREADERNODE_MODELBASE + +#include "Model/Reader/NMR_ModelReaderNode.h" + +namespace NMR { + + class CModelReaderNode_ModelBase : public CModelReaderNode { + protected: + CModel * m_pModel; + std::string m_sRequiredExtensions; + std::map m_ListedExtensions; + + std::string m_sPath; + nfBool m_bHasResources; + nfBool m_bHasBuild; + + nfBool m_bWithinIgnoredElement; + nfBool m_bIgnoreBuild; + nfBool m_bIgnoreMetaData; + + nfBool m_bHaveWarnedAboutV093; + + void ReadMetaDataNode(_In_ CXmlReader * pXMLReader); + + virtual void CheckRequiredExtensions(); + + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue, _In_z_ const nfChar * pNameSpace); + public: + CModelReaderNode_ModelBase() = delete; + CModelReaderNode_ModelBase(_In_ CModel *pModel, _In_ PModelWarnings pWarnings, const std::string sPath, _In_ PProgressMonitor pProgressMonitor); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + + nfBool getHasResources(); + nfBool getHasBuild(); + + nfBool ignoreBuild(); + void setIgnoreBuild(bool bIgnoreBuild); + nfBool ignoreMetaData(); + void setIgnoreMetaData(bool bIgnoreMetaData); + }; + + typedef std::shared_ptr PModelReaderNode_ModelBase; + +} + +#endif // __NMR_MODELREADERNODE_MODELBASE diff --git a/Include/Model/Reader/NMR_ModelReaderNode_StringValue.h b/Include/Model/Reader/NMR_ModelReaderNode_StringValue.h new file mode 100644 index 0000000..5226e6d --- /dev/null +++ b/Include/Model/Reader/NMR_ModelReaderNode_StringValue.h @@ -0,0 +1,39 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_KeyStoreKeyValue.h defines the Model Reader Node class that is related to . + +--*/ + +#pragma once +#if defined( _WIN64) + #include "NMR_ModelReaderNode_StringValue_x64.h" +#else + #include "NMR_ModelReaderNode_StringValue_x32.h" +#endif + diff --git a/Include/Model/Reader/NMR_ModelReaderNode_StringValue_x32.h b/Include/Model/Reader/NMR_ModelReaderNode_StringValue_x32.h new file mode 100644 index 0000000..999ed42 --- /dev/null +++ b/Include/Model/Reader/NMR_ModelReaderNode_StringValue_x32.h @@ -0,0 +1,62 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_KeyStoreKeyValue.h defines the Model Reader Node class that is related to . + +--*/ + +#ifndef __NMR_MODELREADERNODE_KEYSTOREKEYVALUE +#define __NMR_MODELREADERNODE_KEYSTOREKEYVALUE + +#include "Model/Reader/NMR_ModelReaderNode_KeyStoreBase.h" +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_KeyStore.h" +#include "Common/NMR_Local.h" +namespace NMR { + + class CModelReaderNode_StringValue: public CModelReaderNode { + private: + std::string m_sKeyValue; + protected: + void OnText(_In_z_ const nfChar * pText, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode_StringValue() = delete; + using CModelReaderNode::CModelReaderNode; + + CModelReaderNode_StringValue(_In_ PModelWarnings pWarnings, _In_ PProgressMonitor pProgressMonitor = nullptr): + CModelReaderNode( pWarnings, pProgressMonitor){}; + + std::string const & getValue() const; + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + + typedef std::shared_ptr PModelReaderNode_StringValue; +} + +#endif // __NMR_MODELREADERNODE_KEYSTOREKEYVALUE diff --git a/Include/Model/Reader/NMR_ModelReaderNode_StringValue_x64.h b/Include/Model/Reader/NMR_ModelReaderNode_StringValue_x64.h new file mode 100644 index 0000000..2a2e515 --- /dev/null +++ b/Include/Model/Reader/NMR_ModelReaderNode_StringValue_x64.h @@ -0,0 +1,59 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_KeyStoreKeyValue.h defines the Model Reader Node class that is related to . + +--*/ + +#ifndef __NMR_MODELREADERNODE_KEYSTOREKEYVALUE +#define __NMR_MODELREADERNODE_KEYSTOREKEYVALUE + +#include "Model/Reader/NMR_ModelReaderNode_KeyStoreBase.h" +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_KeyStore.h" +#include "Common/NMR_Local.h" +namespace NMR { + + class CModelReaderNode_StringValue: public CModelReaderNode { + private: + std::string m_sKeyValue; + protected: + void OnText(_In_z_ const nfChar * pText, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode_StringValue() = delete; + using CModelReaderNode::CModelReaderNode; + + std::string const & getValue() const; + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + + typedef std::shared_ptr PModelReaderNode_StringValue; +} + +#endif // __NMR_MODELREADERNODE_KEYSTOREKEYVALUE diff --git a/Include/Model/Reader/NMR_ModelReader_3MF.h b/Include/Model/Reader/NMR_ModelReader_3MF.h new file mode 100644 index 0000000..dc799de --- /dev/null +++ b/Include/Model/Reader/NMR_ModelReader_3MF.h @@ -0,0 +1,61 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReader_3MF.h defines the Model Reader Class for +3MF Files. A 3MF model reader reads in a 3MF file and generates an in-memory representation of it. + +--*/ + +#ifndef __NMR_MODELREADER_3MF +#define __NMR_MODELREADER_3MF + +#include "Model/Reader/NMR_ModelReader.h" +#include "Common/NMR_SecureContentTypes.h" +#include +#include + +namespace NMR { + + class CModelReader_3MF : public CModelReader { + protected: + virtual PImportStream extract3MFOPCPackage(_In_ PImportStream pPackageStream) = 0; + virtual void release3MFOPCPackage() = 0; + + public: + CModelReader_3MF() = delete; + CModelReader_3MF(_In_ PModel pModel); + + virtual void readStream(_In_ PImportStream pStream); + virtual void addTextureAttachment(_In_ std::string sPath, _In_ PImportStream pStream); + }; + + typedef std::shared_ptr PModelReader_3MF; + +} + +#endif // __NMR_MODELREADER_3MF diff --git a/Include/Model/Reader/NMR_ModelReader_3MF_Native.h b/Include/Model/Reader/NMR_ModelReader_3MF_Native.h new file mode 100644 index 0000000..c7c26fa --- /dev/null +++ b/Include/Model/Reader/NMR_ModelReader_3MF_Native.h @@ -0,0 +1,70 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReader_3MF_Native.h implements the Model Reader Class. +A model reader reads in a 3MF file and generates an in-memory representation of it. +It uses libzip and irrxml to parse the OPC package. + +--*/ + +#ifndef __NMR_MODELREADER_3MF_NATIVE +#define __NMR_MODELREADER_3MF_NATIVE + +#include "Model/Reader/NMR_ModelReader_3MF.h" +#include "Model/Reader/NMR_ModelReader.h" +#include "Model/Classes/NMR_Model.h" +#include "Common/Platform/NMR_XmlReader.h" +#include "Model/Reader/NMR_KeyStoreOpcPackageReader.h" +#include "Common/OPC/NMR_OpcPackagePart.h" +#include + +namespace NMR { + + class CModelReader_3MF_Native : public CModelReader_3MF { + private: + PKeyStoreOpcPackageReader m_pPackageReader; + + protected: + void extractCustomDataFromRelationships(_In_ std::string& sTargetPartURIDir, _In_ COpcPackagePart * pModelPart); + void extractTexturesFromRelationships(_In_ std::string& sTargetPartURIDir, _In_ COpcPackagePart * pModelPart); + void extractModelDataFromRelationships(_In_ std::string& sTargetPartURIDir, _In_ COpcPackagePart * pModelPart); + void checkContentTypes(); + + virtual PImportStream extract3MFOPCPackage(_In_ PImportStream pPackageStream); + virtual void release3MFOPCPackage(); + + public: + CModelReader_3MF_Native() = delete; + CModelReader_3MF_Native(_In_ PModel pModel); + }; + + typedef std::shared_ptr PModelReader_3MF_Native; + +} + +#endif // __NMR_MODELREADER_3MF_NATIVE diff --git a/Include/Model/Reader/NMR_ModelReader_ColorMapping.h b/Include/Model/Reader/NMR_ModelReader_ColorMapping.h new file mode 100644 index 0000000..8f338d7 --- /dev/null +++ b/Include/Model/Reader/NMR_ModelReader_ColorMapping.h @@ -0,0 +1,83 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReader_ColorMapping.h defines the Model Reader Color Mapping Class. + +--*/ + +#ifndef __NMR_MODELREADER_COLORMAPPING +#define __NMR_MODELREADER_COLORMAPPING + +#include "Common/NMR_Types.h" +#include "Common/NMR_Local.h" +#include "Model/Classes/NMR_ModelTypes.h" + +#include +#include + +namespace NMR { + + typedef struct { + ModelResourceID m_nResourceID; + ModelResourceIndex m_nResourceIndex; + } READERCOLORMAPPINGTREEENTRY; + + bool operator< (_In_ const READERCOLORMAPPINGTREEENTRY & entry1, _In_ const READERCOLORMAPPINGTREEENTRY & entry2); + + class CModelReader_ColorMapping { + protected: + std::map m_ColorEntries; + std::map m_ResourceIDs; + std::map m_TextureMappings; + std::map m_MaterialMappings; + public: + CModelReader_ColorMapping(); + + void registerColor(_In_ ModelResourceID nResourceID, _In_ ModelResourceIndex nResourceIndex, _In_ nfColor cColor); + nfBool findColor(_In_ ModelResourceID nResourceID, _In_ ModelResourceIndex nResourceIndex, _Out_ nfColor & cColor); + + nfBool hasResource(_In_ ModelResourceID nResourceID); + + void registerTextureReference(_In_ ModelResourceID nResourceID, _In_ ModelResourceID nTextureID); + nfBool hasTextureReference(_In_ ModelResourceID nResourceID); + ModelResourceID getTextureReference(_In_ ModelResourceID nResourceID); + + void registerMaterialReference(_In_ ModelResourceID nResourceID, _In_ ModelResourceIndex nMaterialIndex); + nfBool hasMaterialReference(_In_ ModelResourceID nResourceID); + nfBool getMaterialReference(_In_ ModelResourceID nResourceID, _Out_ ModelResourceIndex & nMaterialIndex); + + nfBool retrieveAResource(_Out_ ModelResourceID& nResourceID); + }; + + typedef std::shared_ptr PModelReader_ColorMapping; + +} + +#endif // __NMR_MODELREADER_COLORMAPPING + + diff --git a/Include/Model/Reader/NMR_ModelReader_InstructionElement.h b/Include/Model/Reader/NMR_ModelReader_InstructionElement.h new file mode 100644 index 0000000..38b5491 --- /dev/null +++ b/Include/Model/Reader/NMR_ModelReader_InstructionElement.h @@ -0,0 +1,58 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReader_InstructionElement.h defines a reader for an instruction element + +--*/ + +#ifndef __NMR_MODELREADER_INSTRUCTIONELEMENT +#define __NMR_MODELREADER_INSTRUCTIONELEMENT + +#include "Model/Reader/NMR_ModelReaderNode.h" + +namespace NMR { + + class CModelReader_InstructionElement : public CModelReaderNode { + private: + std::string m_sEncoding; + std::string m_sName; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + public: + CModelReader_InstructionElement() = delete; + CModelReader_InstructionElement(_In_ PModelWarnings pWarnings); + + virtual void parseName(_In_ CXmlReader * pXMLReader); + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + + typedef std::shared_ptr PModelReader_InstructionElement; + +} + +#endif // __NMR_MODELREADER_INSTRUCTIONELEMENT diff --git a/Include/Model/Reader/NMR_ModelReader_STL.h b/Include/Model/Reader/NMR_ModelReader_STL.h new file mode 100644 index 0000000..43baf7f --- /dev/null +++ b/Include/Model/Reader/NMR_ModelReader_STL.h @@ -0,0 +1,58 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReader_STL.h defines the Model Reader Class for +STL Files. A STL model reader reads in a STL file and generates an in-memory representation of it. + +--*/ + +#ifndef __NMR_MODELREADER_STL +#define __NMR_MODELREADER_STL + +#include "Model/Reader/NMR_ModelReader.h" +#include "Common/MeshImport/NMR_MeshImporter.h" + +#include + +namespace NMR { + + class CModelReader_STL : public CModelReader { + protected: + + public: + CModelReader_STL() = delete; + CModelReader_STL(_In_ PModel pModel); + + virtual void readStream(_In_ PImportStream pStream); + }; + + typedef std::shared_ptr PModelReader_STL; + +} + +#endif // __NMR_MODELREADER diff --git a/Include/Model/Reader/NMR_ModelReader_TexCoordMapping.h b/Include/Model/Reader/NMR_ModelReader_TexCoordMapping.h new file mode 100644 index 0000000..4a243b1 --- /dev/null +++ b/Include/Model/Reader/NMR_ModelReader_TexCoordMapping.h @@ -0,0 +1,77 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReader_TexcoordMapping.h defines the Model Reader Texture Mapping Class. + +--*/ + +#ifndef __NMR_MODELREADER_TEXCOORDMAPPING +#define __NMR_MODELREADER_TEXCOORDMAPPING + +#include "Common/NMR_Types.h" +#include "Common/NMR_Local.h" +#include "Model/Classes/NMR_ModelTypes.h" + +#include +#include + +namespace NMR { + + typedef struct { + ModelResourceID m_nResourceID; + ModelResourceIndex m_nResourceIndex; + } READERTEXCOORDMAPPINGTREEENTRY; + + typedef struct { + ModelResourceID m_nTextureID; + nfFloat m_fU; + nfFloat m_fV; + } READERTEXCOORDMAPPINGVALUE; + + bool operator< (_In_ const READERTEXCOORDMAPPINGTREEENTRY & entry1, _In_ const READERTEXCOORDMAPPINGTREEENTRY & entry2); + + class CModelReader_TexCoordMapping { + protected: + std::map m_TexCoordEntries; + std::map m_ResourceIDs; + public: + CModelReader_TexCoordMapping(); + + void registerTexCoords(_In_ ModelResourceID nResourceID, _In_ ModelResourceIndex nResourceIndex, _In_ ModelResourceID nTextureID, _In_ nfFloat fU, _In_ nfFloat fV); + nfBool findTexCoords(_In_ ModelResourceID nResourceID, _In_ ModelResourceIndex nResourceIndex, _Out_ ModelResourceID & nTextureID, _Out_ nfFloat & fU, _Out_ nfFloat & fV); + + nfBool hasResource(_In_ ModelResourceID nResourceID); + nfBool retrieveAResource(_Out_ ModelResourceID& nResourceID); + }; + + typedef std::shared_ptr PModelReader_TexCoordMapping; + +} + +#endif // __NMR_MODELREADER_TEXCOORDMAPPING + diff --git a/Include/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStore.h b/Include/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStore.h new file mode 100644 index 0000000..8110bb6 --- /dev/null +++ b/Include/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStore.h @@ -0,0 +1,61 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_KeyStore.h defines the Model Reader Node class that is related to . + +--*/ + +#ifndef __NMR_MODELREADERNODE_KEYSTORE +#define __NMR_MODELREADERNODE_KEYSTORE + +#include "Model/Reader/NMR_ModelReaderNode_KeyStoreBase.h" +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_KeyStore.h" + +namespace NMR { + + class CModelReaderNode_KeyStore: public CModelReaderNode_KeyStoreBase { + private: + PUUID m_UUID; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode_KeyStore() = delete; + using CModelReaderNode_KeyStoreBase::CModelReaderNode_KeyStoreBase; + + CModelReaderNode_KeyStore(_In_ CModel * const pModel, _In_ CKeyStore * const pKeyStore, _In_ PModelWarnings pWarnings): + CModelReaderNode_KeyStoreBase( pModel,pKeyStore, pWarnings){}; + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + + typedef std::shared_ptr PModelReaderNode_KeyStore; +} + +#endif // __NMR_MODELREADERNODE_KEYSTORE diff --git a/Include/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreAccessRight.h b/Include/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreAccessRight.h new file mode 100644 index 0000000..73960cd --- /dev/null +++ b/Include/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreAccessRight.h @@ -0,0 +1,70 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_KeyStoreDecryptRight.h defines the Model Reader Node class that is related to . + +--*/ + +#ifndef __NMR_MODELREADERNODE_KEYSTOACCESSRIGHT +#define __NMR_MODELREADERNODE_KEYSTOACCESSRIGHT + +#include "Model/Reader/NMR_ModelReaderNode_KeyStoreBase.h" +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_KeyStore.h" +#include "Model/Classes/NMR_KeyStoreAccessRight.h" +#include "Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreKEKParams.h" + +namespace NMR { + + class CModelReaderNode_KeyStoreAccessRight : public CModelReaderNode_KeyStoreBase { + private: + nfBool m_bHasParams = false; + nfBool m_bHasConsumerIndex = false; + nfBool m_bHasCipherData = false; + nfUint64 m_nConsumerIndex = 0; + KEKPARAMS m_sParams; + std::vector m_rgCipherValue; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode_KeyStoreAccessRight() = delete; + using CModelReaderNode_KeyStoreBase::CModelReaderNode_KeyStoreBase; + + CModelReaderNode_KeyStoreAccessRight(_In_ CModel * const pModel, _In_ CKeyStore * const pKeyStore, _In_ PModelWarnings pWarnings): + CModelReaderNode_KeyStoreBase( pModel, pKeyStore, pWarnings){}; + + PKeyStoreAccessRight getAccessRight(); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + + typedef std::shared_ptr PModelReaderNode_KeyStoreAccessRight; +} + +#endif // __NMR_MODELREADERNODE_KEYSTOACCESSRIGHT diff --git a/Include/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreCEKParams.h b/Include/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreCEKParams.h new file mode 100644 index 0000000..9c2f588 --- /dev/null +++ b/Include/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreCEKParams.h @@ -0,0 +1,71 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_KeyStoreCipherValue.h defines the Model Reader Node class that is related to . + +--*/ + +#ifndef __NMR_MODELREADERNODE_KEYSTORECEKPARAMS +#define __NMR_MODELREADERNODE_KEYSTORECEKPARAMS + +#include "Model/Reader/NMR_ModelReaderNode_KeyStoreBase.h" +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_KeyStore.h" +#include "Model/Classes/NMR_KeyStoreAccessRight.h" +#include "Model/Classes/NMR_KeyStoreCEKParams.h" + +namespace NMR { + + class CModelReaderNode_KeyStoreCEKParams: public CModelReaderNode_KeyStoreBase { + private: + nfBool m_bCompressed = false; + eKeyStoreEncryptAlgorithm m_eAlgorithm = eKeyStoreEncryptAlgorithm::AES256_GCM; + std::vector m_iv; + std::vector m_tag; + std::vector m_aad; + nfBool m_bHasAlgorithm = false; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + + public: + CModelReaderNode_KeyStoreCEKParams() = delete; + using CModelReaderNode_KeyStoreBase::CModelReaderNode_KeyStoreBase; + + CModelReaderNode_KeyStoreCEKParams(_In_ CModel * const pModel, _In_ CKeyStore * const pKeyStore, _In_ PModelWarnings pWarnings): + CModelReaderNode_KeyStoreBase( pModel, pKeyStore, pWarnings){}; + + PKeyStoreCEKParams getCEKParams(); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + typedef std::shared_ptr PModelReaderNode_KeyStoreCEKParams; + +} + +#endif // __NMR_MODELREADERNODE_KEYSTORECEKPARAMS diff --git a/Include/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreCipherValue.h b/Include/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreCipherValue.h new file mode 100644 index 0000000..3e99a72 --- /dev/null +++ b/Include/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreCipherValue.h @@ -0,0 +1,64 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_KeyStoreCipherValue.h defines the Model Reader Node class that is related to . + +--*/ + +#ifndef __NMR_MODELREADERNODE_KEYSTORECIPHERVALUE +#define __NMR_MODELREADERNODE_KEYSTORECIPHERVALUE + +#include "Model/Reader/NMR_ModelReaderNode_KeyStoreBase.h" +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_KeyStore.h" +#include "Model/Classes/NMR_KeyStoreAccessRight.h" + +namespace NMR { + + class CModelReaderNode_KeyStoreCipherValue: public CModelReaderNode_KeyStoreBase { + private: + std::vector m_sCipherValue; + protected: + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode_KeyStoreCipherValue() = delete; + using CModelReaderNode_KeyStoreBase::CModelReaderNode_KeyStoreBase; + + CModelReaderNode_KeyStoreCipherValue(_In_ CModel * const pModel, _In_ CKeyStore * const pKeyStore, _In_ PModelWarnings pWarnings) : + CModelReaderNode_KeyStoreBase( pModel, pKeyStore, pWarnings) {}; + + + std::vector const & getCipherValue() const; + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + + typedef std::shared_ptr PModelReaderNode_KeyStoreCipherValue; +} + +#endif // __NMR_MODELREADERNODE_KEYSTORECIPHERVALUE diff --git a/Include/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreConsumer.h b/Include/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreConsumer.h new file mode 100644 index 0000000..1780173 --- /dev/null +++ b/Include/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreConsumer.h @@ -0,0 +1,63 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_KeyStoreConsumer.h defines the Model Reader Node class that is related to . + +--*/ + +#ifndef __NMR_MODELREADERNODE_KEYSTORECONSUMER +#define __NMR_MODELREADERNODE_KEYSTORECONSUMER + +#include "Model/Reader/NMR_ModelReaderNode_KeyStoreBase.h" +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_KeyStore.h" + +namespace NMR { + + class CModelReaderNode_KeyStoreConsumer: public CModelReaderNode_KeyStoreBase { + private: + std::string m_sConsumerID; + std::string m_sKeyID; + std::string m_sKeyValue; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode_KeyStoreConsumer() = delete; + using CModelReaderNode_KeyStoreBase::CModelReaderNode_KeyStoreBase; + + CModelReaderNode_KeyStoreConsumer(_In_ CModel * const pModel, _In_ CKeyStore * const pKeyStore, _In_ PModelWarnings pWarnings) : + CModelReaderNode_KeyStoreBase( pModel, pKeyStore, pWarnings){}; + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + + typedef std::shared_ptr PModelReaderNode_KeyStoreConsumer; +} + +#endif // __NMR_MODELREADERNODE_KEYSTORECONSUMER diff --git a/Include/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreKEKParams.h b/Include/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreKEKParams.h new file mode 100644 index 0000000..4db32ad --- /dev/null +++ b/Include/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreKEKParams.h @@ -0,0 +1,77 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_KeyStoreCipherValue.h defines the Model Reader Node class that is related to . + +--*/ + +#ifndef __NMR_MODELREADERNODE_KEYSTOREKEKPARAMS +#define __NMR_MODELREADERNODE_KEYSTOREKEKPARAMS + +#include "Model/Reader/NMR_ModelReaderNode_KeyStoreBase.h" +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_KeyStore.h" +#include "Common/NMR_SecureContentTypes.h" + +namespace NMR { + + namespace ParserUtils { + eKeyStoreWrapAlgorithm parseWrapAlgorithm(std::string const & value, bool & hasMgf1); + eKeyStoreMaskGenerationFunction parseMgf(std::string const & value); + eKeyStoreMessageDigest parseMessageDigest(std::string const & value); + } + + struct KEKPARAMS { + eKeyStoreWrapAlgorithm m_eAlgorithm; + eKeyStoreMaskGenerationFunction m_eMgf; + eKeyStoreMessageDigest m_eDigest; + }; + + class CModelReaderNode_KeyStoreKEKParams: public CModelReaderNode_KeyStoreBase { + private: + KEKPARAMS m_sKekParams = KEKPARAMS{ eKeyStoreWrapAlgorithm::RSA_OAEP, eKeyStoreMaskGenerationFunction::MGF1_SHA1, eKeyStoreMessageDigest::SHA1 }; + nfBool m_bAlgHasMgf = false; + nfBool m_bHasAlgorithm = false; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + public: + CModelReaderNode_KeyStoreKEKParams() = delete; + using CModelReaderNode_KeyStoreBase::CModelReaderNode_KeyStoreBase; + + CModelReaderNode_KeyStoreKEKParams(_In_ CModel * const pModel, _In_ CKeyStore * const pKeyStore, _In_ PModelWarnings pWarnings): + CModelReaderNode_KeyStoreBase( pModel, pKeyStore, pWarnings) {}; + + KEKPARAMS getKekParams(); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + + typedef std::shared_ptr PModelReaderNode_KeyStoreKEKParams; +} + +#endif // __NMR_MODELREADERNODE_KEYSTOREKEKPARAMS diff --git a/Include/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreResourceData.h b/Include/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreResourceData.h new file mode 100644 index 0000000..a4817c9 --- /dev/null +++ b/Include/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreResourceData.h @@ -0,0 +1,68 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_KeyStoreResourceData.h defines the Model Reader Node class that is related to . + +--*/ + +#ifndef __NMR_MODELREADERNODE_KEYSTORERESOURCEDATA +#define __NMR_MODELREADERNODE_KEYSTORERESOURCEDATA + +#include "Model/Classes/NMR_KeyStoreResourceData.h" +#include "Model/Classes/NMR_KeyStoreCEKParams.h" +#include "Model/Reader/NMR_ModelReaderNode_KeyStoreBase.h" +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_KeyStore.h" +#include "Model/Classes/NMR_KeyStoreResourceDataGroup.h" + + + +namespace NMR { + + class CModelReaderNode_KeyStoreResourceData : public CModelReaderNode_KeyStoreBase { + private: + std::string m_sPath; + PKeyStoreCEKParams m_pCekParams; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode_KeyStoreResourceData() = delete; + using CModelReaderNode_KeyStoreBase::CModelReaderNode_KeyStoreBase; + + CModelReaderNode_KeyStoreResourceData(_In_ CModel * const pModel, _In_ CKeyStore * const pKeyStore, _In_ PModelWarnings pWarnings): + CModelReaderNode_KeyStoreBase( pModel, pKeyStore, pWarnings) {}; + + PKeyStoreResourceData getResourceData(PKeyStoreResourceDataGroup const & rdg); + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + + typedef std::shared_ptr PModelReaderNode_KeyStoreResourceData; +} + +#endif // __NMR_MODELREADERNODE_KEYSTORERESOURCEDATA diff --git a/Include/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreResourceDataGroup.h b/Include/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreResourceDataGroup.h new file mode 100644 index 0000000..fb7c474 --- /dev/null +++ b/Include/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreResourceDataGroup.h @@ -0,0 +1,68 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_KeyStoreResourceData.h defines the Model Reader Node class that is related to . + +--*/ + +#ifndef __NMR_MODELREADERNODE_KEYSTORERESOURCEDATAGROUP +#define __NMR_MODELREADERNODE_KEYSTORERESOURCEDATAGROUP + +#include "Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreAccessRight.h" +#include "Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreResourceData.h" +#include "Model/Reader/NMR_ModelReaderNode_KeyStoreBase.h" +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_KeyStore.h" +#include "Model/Classes/NMR_KeyStoreAccessRight.h" +#include "Model/Classes/NMR_KeyStoreResourceData.h" +#include "Model/Classes/NMR_KeyStoreResourceDataGroup.h" + + +namespace NMR { + + class CModelReaderNode_KeyStoreResourceDataGroup : public CModelReaderNode_KeyStoreBase { + private: + PKeyStoreResourceDataGroup m_pGroup; + nfBool m_bHasUuid = false; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode_KeyStoreResourceDataGroup() = delete; + using CModelReaderNode_KeyStoreBase::CModelReaderNode_KeyStoreBase; + + CModelReaderNode_KeyStoreResourceDataGroup(_In_ CModel * const pModel, _In_ CKeyStore * const pKeyStore, _In_ PModelWarnings pWarnings) : + CModelReaderNode_KeyStoreBase( pModel, pKeyStore, pWarnings) {}; + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + + typedef std::shared_ptr PModelReaderNode_KeyStoreResourceDataGroup; +} + +#endif // __NMR_MODELREADERNODE_KEYSTORERESOURCEDATAGROUP diff --git a/Include/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Polygon.h b/Include/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Polygon.h new file mode 100644 index 0000000..fba08ab --- /dev/null +++ b/Include/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Polygon.h @@ -0,0 +1,62 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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 __NMR_MODELREADERNODE_SLICE1507_POLYGON +#define __NMR_MODELREADERNODE_SLICE1507_POLYGON + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Model/Classes/NMR_ModelObject.h" + +#include "Model/Classes/NMR_ModelConstants_Slices.h" + +namespace NMR { + + class CModelReaderNode_Slices1507_Polygon : public CModelReaderNode { + private: + CSlice *m_pSlice; + + nfUint32 m_PolygonIndex; + nfUint32 m_StartV; + + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + + public: + CModelReaderNode_Slices1507_Polygon() = delete; + CModelReaderNode_Slices1507_Polygon(_In_ CSlice *pSlice, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + + typedef std::shared_ptr PModelReaderNode_Slices1507_Polygon; +} + +#endif \ No newline at end of file diff --git a/Include/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Segment.h b/Include/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Segment.h new file mode 100644 index 0000000..8540bbc --- /dev/null +++ b/Include/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Segment.h @@ -0,0 +1,63 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_slice1507_Segment.h covers the segments of the private 3MF slice extension. + +--*/ + +#ifndef __NMR_MODELREADERNODE_SLICE1507_SEGMENT +#define __NMR_MODELREADERNODE_SLICE1507_SEGMENT + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Model/Classes/NMR_ModelObject.h" +#include "Model/Classes/NMR_ModelConstants_Slices.h" + +namespace NMR { + + class CModelReaderNode_Slices1507_Segment : public CModelReaderNode { + private: + CSlice *m_pSlice; + nfUint32 m_PolygonIndex; + + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + + public: + CModelReaderNode_Slices1507_Segment() = delete; + CModelReaderNode_Slices1507_Segment(_In_ CSlice *pSlice, nfUint32 nPolygonIndex, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + + typedef std::shared_ptr PModelReaderNode_Slices1507_Segment; +} + +#endif \ No newline at end of file diff --git a/Include/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Slice.h b/Include/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Slice.h new file mode 100644 index 0000000..7999124 --- /dev/null +++ b/Include/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Slice.h @@ -0,0 +1,65 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_slice1507_Segment.h covers the slices of the private 3MF slice extension. + +--*/ + +#ifndef __NMR_MODELREADERNODE_SLICE1507_SLICE +#define __NMR_MODELREADERNODE_SLICE1507_SLICE + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Model/Classes/NMR_ModelObject.h" +#include "Model/Classes/NMR_ModelConstants_Slices.h" + +namespace NMR { + class CModelReaderNode_Slices1507_Slice : public CModelReaderNode { + private: + CModelSliceStack *m_pSliceStack; + PSlice m_Slice; + + nfFloat m_TopZ; + bool m_bHasZTop; + + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + + public: + CModelReaderNode_Slices1507_Slice() = delete; + CModelReaderNode_Slices1507_Slice(_In_ CModelSliceStack *pSliceStack, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + + typedef std::shared_ptr PModelReaderNode_Slices1507_Slice; +} + +#endif \ No newline at end of file diff --git a/Include/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceRef.h b/Include/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceRef.h new file mode 100644 index 0000000..c766715 --- /dev/null +++ b/Include/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceRef.h @@ -0,0 +1,66 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_slice1507_Segment.h covers the slices of the private 3MF slice extension. + +--*/ + +#ifndef __NMR_MODELREADERNODE_SLICE1507_SLICEREF +#define __NMR_MODELREADERNODE_SLICE1507_SLICEREF + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Model/Classes/NMR_ModelObject.h" +#include "Model/Classes/NMR_ModelConstants_Slices.h" + +namespace NMR { + class CModelReaderNode_Slice1507_SliceRef : public CModelReaderNode { + private: + nfUint32 m_SliceStackId; + std::string m_Path; + + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + + public: + CModelReaderNode_Slice1507_SliceRef() = delete; + CModelReaderNode_Slice1507_SliceRef(_In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + + std::string Path(); + nfUint32 SliceStackId(); + + }; + + typedef std::shared_ptr PModelReaderNode_Slice1507_SliceRef; +} + +#endif \ No newline at end of file diff --git a/Include/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceRefModel.h b/Include/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceRefModel.h new file mode 100644 index 0000000..2a7a73b --- /dev/null +++ b/Include/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceRefModel.h @@ -0,0 +1,62 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_slice1507.h covers the private 3MF slice extension. + +--*/ + +#ifndef __NMR_MODELREADERNODE_SLICE1507_SLICEREFMODEL +#define __NMR_MODELREADERNODE_SLICE1507_SLICEREFMODEL + +#include "Model/Reader/NMR_ModelReaderNode_ModelBase.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Model/Classes/NMR_ModelObject.h" +#include "Model/Classes/NMR_ModelConstants_Slices.h" + +namespace NMR { + + class CModelReader_Slice1507_SliceRefModel : public CModelReaderNode_ModelBase { + private: + std::string m_sSliceRefPath; + + protected: + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + + public: + CModelReader_Slice1507_SliceRefModel() = delete; + CModelReader_Slice1507_SliceRefModel(_In_ CModel *pModel, _In_ PModelWarnings pWarnings, _In_z_ const std::string sSliceRefPath); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + + typedef std::shared_ptr PModelReader_Slice1507_SliceRefModel; + +} + +#endif diff --git a/Include/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceRefResources.h b/Include/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceRefResources.h new file mode 100644 index 0000000..beee4c9 --- /dev/null +++ b/Include/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceRefResources.h @@ -0,0 +1,61 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_slice1507_Segment.h covers the sliceref resources of the private 3MF slice extension. + +--*/ + +#ifndef __NMR_MODELREADERNODE_SLICE1507_SLICEREFRESOURCES +#define __NMR_MODELREADERNODE_SLICE1507_SLICEREFRESOURCES + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Model/Classes/NMR_ModelObject.h" +#include "Model/Classes/NMR_ModelConstants_Slices.h" + +namespace NMR { + class CModelReader_Slice1507_SliceRefResources : public CModelReaderNode { + private: + CModel *m_pModel; + std::string m_sSliceRefPath; + + protected: + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + + public: + CModelReader_Slice1507_SliceRefResources() = delete; + CModelReader_Slice1507_SliceRefResources(_In_ CModel *pModel, _In_ PModelWarnings pWarnings, _In_z_ const std::string sSliceRefPath); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + + typedef std::shared_ptr PModelReader_Slice1507_SliceRefResources; +} + +#endif \ No newline at end of file diff --git a/Include/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceStack.h b/Include/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceStack.h new file mode 100644 index 0000000..e60aac7 --- /dev/null +++ b/Include/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceStack.h @@ -0,0 +1,66 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_slice1507_Segment.h covers the slicestack of the private 3MF slice extension. + +--*/ + +#ifndef __NMR_MODELREADERNODE_SLICE1507_SLICESTACK +#define __NMR_MODELREADERNODE_SLICE1507_SLICESTACK + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Model/Classes/NMR_ModelObject.h" +#include "Model/Classes/NMR_ModelConstants_Slices.h" + +namespace NMR { + class CModelReaderNode_Slice1507_SliceStack : public CModelReaderNode { + private: + CModel *m_pModel; + + nfFloat m_BottomZ; + nfUint32 m_Id; + + PModelSliceStack m_pSliceStackResource; + std::string m_sSlicePath; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + + public: + CModelReaderNode_Slice1507_SliceStack() = delete; + CModelReaderNode_Slice1507_SliceStack(_In_ CModel *pModel, _In_ PModelWarnings pWarnings, _In_ PProgressMonitor pProgressMonitor, _In_ const std::string sSlicePath); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + + typedef std::shared_ptr PModelReaderNode_Slice1507_SliceStack; +} + +#endif \ No newline at end of file diff --git a/Include/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Vertex.h b/Include/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Vertex.h new file mode 100644 index 0000000..b7d1d95 --- /dev/null +++ b/Include/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Vertex.h @@ -0,0 +1,64 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_slice1507_Segment.h covers the segments of the private 3MF slice extension. + +--*/ + +#ifndef __NMR_MODELREADERNODE_SLICE1507_VERTEX +#define __NMR_MODELREADERNODE_SLICE1507_VERTEX + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Model/Classes/NMR_ModelObject.h" +#include "Model/Classes/NMR_ModelConstants_Slices.h" + +namespace NMR { + class CModelReaderNode_Slices1507_Vertex : public CModelReaderNode { + private: + nfFloat m_x; + nfFloat m_y; + + CSlice *m_pSlice; + + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + + public: + CModelReaderNode_Slices1507_Vertex() = delete; + CModelReaderNode_Slices1507_Vertex(_In_ CSlice *pSlice, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + + typedef std::shared_ptr PModelReaderNode_Slices1507_Vertex; +} + +#endif \ No newline at end of file diff --git a/Include/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Vertices.h b/Include/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Vertices.h new file mode 100644 index 0000000..3fbd90c --- /dev/null +++ b/Include/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Vertices.h @@ -0,0 +1,61 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_slice1507_Segment.h covers the vertices of the private 3MF slice extension. + +--*/ + +#ifndef __NMR_MODELREADERNODE_SLICE1507_VERTICES +#define __NMR_MODELREADERNODE_SLICE1507_VERTICES + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Model/Classes/NMR_ModelObject.h" +#include "Model/Classes/NMR_ModelConstants_Slices.h" + +namespace NMR { + class CModelReaderNode_Slices1507_Vertices : public CModelReaderNode { + private: + CSlice *m_pSlice; + + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + + public: + CModelReaderNode_Slices1507_Vertices() = delete; + CModelReaderNode_Slices1507_Vertices(_In_ CSlice *pSlice, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + + typedef std::shared_ptr PModelReaderNode_Slices1507_Vertices; +} + +#endif \ No newline at end of file diff --git a/Include/Model/Reader/v093/NMR_ModelReaderNode093_Build.h b/Include/Model/Reader/v093/NMR_ModelReaderNode093_Build.h new file mode 100644 index 0000000..3f33473 --- /dev/null +++ b/Include/Model/Reader/v093/NMR_ModelReaderNode093_Build.h @@ -0,0 +1,55 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode093_Build.h defines the Model Reader Build Node Class. +A build reader model node is a parser for the build node of an XML Model Stream. + +--*/ +#ifndef __NMR_MODELREADERNODE093_BUILD +#define __NMR_MODELREADERNODE093_BUILD + +#include "Model/Reader/NMR_ModelReaderNode.h" + +namespace NMR { + + class CModelReaderNode093_Build : public CModelReaderNode { + protected: + CModel * m_pModel; + + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode093_Build() = delete; + CModelReaderNode093_Build(_In_ CModel * pModel, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + +} + +#endif // __NMR_MODELREADERNODE093_BUILD diff --git a/Include/Model/Reader/v093/NMR_ModelReaderNode093_BuildItem.h b/Include/Model/Reader/v093/NMR_ModelReaderNode093_BuildItem.h new file mode 100644 index 0000000..f8053d8 --- /dev/null +++ b/Include/Model/Reader/v093/NMR_ModelReaderNode093_BuildItem.h @@ -0,0 +1,58 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode093_BuildItem.h defines the Model Reader BuildItem Node Class. +A builditem reader model node is a parser for the builditem node of an XML Model Stream. + +--*/ + +#ifndef __NMR_MODELREADERNODE093_BUILDITEM +#define __NMR_MODELREADERNODE093_BUILDITEM + +#include "Model/Reader/NMR_ModelReaderNode.h" + +namespace NMR { + + class CModelReaderNode093_BuildItem : public CModelReaderNode { + private: + CModel * m_pModel; + nfInt32 m_ObjectID; + nfBool m_bHasID; + NMATRIX3 m_mTransform; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + public: + CModelReaderNode093_BuildItem() = delete; + CModelReaderNode093_BuildItem(_In_ CModel * pModel, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + +} + +#endif // __NMR_MODELREADERNODE093_BUILDITEM diff --git a/Include/Model/Reader/v093/NMR_ModelReaderNode093_Color.h b/Include/Model/Reader/v093/NMR_ModelReaderNode093_Color.h new file mode 100644 index 0000000..eee96c4 --- /dev/null +++ b/Include/Model/Reader/v093/NMR_ModelReaderNode093_Color.h @@ -0,0 +1,68 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode093_Color.h defines the Model Reader Color Node Class. +A color reader model node is a parser for the vertex node of an XML Model Stream. + +--*/ + +#ifndef __NMR_MODELREADERNODE093_COLOR +#define __NMR_MODELREADERNODE093_COLOR + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelObject.h" + +namespace NMR { + + class CModelReaderNode093_Color : public CModelReaderNode { + private: + ModelResourceID m_nTextureID; + std::string m_sColorString; + ModelResourceID m_nResourceID; + nfColor m_cColor; + + void parseColor(); + public: + CModelReaderNode093_Color() = delete; + CModelReaderNode093_Color(_In_ PModelWarnings pWarnings); + + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + + nfColor retrieveColor(); + ModelResourceID retrieveID(); + ModelResourceID retrieveTextureID(); + }; + + typedef std::shared_ptr PModelReaderNode093_Color; + +} + +#endif // __NMR_MODELREADERNODE093_COLOR diff --git a/Include/Model/Reader/v093/NMR_ModelReaderNode093_Component.h b/Include/Model/Reader/v093/NMR_ModelReaderNode093_Component.h new file mode 100644 index 0000000..9201f69 --- /dev/null +++ b/Include/Model/Reader/v093/NMR_ModelReaderNode093_Component.h @@ -0,0 +1,63 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReader093_Component.h defines the Model Component Reader Node Class. + +--*/ + +#ifndef __NMR_MODELREADERNODE093_COMPONENT +#define __NMR_MODELREADERNODE093_COMPONENT + +#include "Model/Reader/NMR_ModelReaderNode.h" + +namespace NMR { + + class CModelReaderNode093_Component : public CModelReaderNode { + protected: + CModel * m_pModel; + ModelResourceID m_ObjectID; + nfBool m_bHasID; + NMATRIX3 m_mTransform; + + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + public: + CModelReaderNode093_Component() = delete; + CModelReaderNode093_Component(_In_ CModel * pModel, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + + CModelObject * getObject(); + NMATRIX3 getTransform(); + + }; + + typedef std::shared_ptr PModelReaderNode093_Component; + +} + +#endif // __NMR_MODELREADERNODE093_COMPONENT diff --git a/Include/Model/Reader/v093/NMR_ModelReaderNode093_Components.h b/Include/Model/Reader/v093/NMR_ModelReaderNode093_Components.h new file mode 100644 index 0000000..ca9e179 --- /dev/null +++ b/Include/Model/Reader/v093/NMR_ModelReaderNode093_Components.h @@ -0,0 +1,57 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_Components.h defines the Model Components Reader Node Class. + +--*/ + +#ifndef __NMR_MODELREADERNODE100_COMPONENTS +#define __NMR_MODELREADERNODE100_COMPONENTS + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" + +namespace NMR { + + class CModelReaderNode093_Components : public CModelReaderNode { + private: + protected: + CModelComponentsObject * m_pComponentsObject; + + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode093_Components() = delete; + CModelReaderNode093_Components(_In_ CModelComponentsObject * pComponentsObject, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + +} + +#endif // __NMR_MODELREADERNODE093_COMPONENTS diff --git a/Include/Model/Reader/v093/NMR_ModelReaderNode093_Material.h b/Include/Model/Reader/v093/NMR_ModelReaderNode093_Material.h new file mode 100644 index 0000000..fd3ef16 --- /dev/null +++ b/Include/Model/Reader/v093/NMR_ModelReaderNode093_Material.h @@ -0,0 +1,65 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode093_Color.h defines the Model Reader Material Node Class. +A color reader material node is a parser for the material node of an XML Model Stream. + +--*/ + +#ifndef __NMR_MODELREADERNODE093_MATERIAL +#define __NMR_MODELREADERNODE093_MATERIAL + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelObject.h" + +namespace NMR { + + class CModelReaderNode093_Material : public CModelReaderNode { + private: + std::string m_sName; + ModelResourceID m_nResourceID; + ModelResourceID m_nColorID; + public: + CModelReaderNode093_Material() = delete; + CModelReaderNode093_Material(_In_ PModelWarnings pWarnings); + + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + + std::string retrieveName(); + ModelResourceID retrieveID(); + ModelResourceID retrieveColorID(); + }; + + typedef std::shared_ptr PModelReaderNode093_Material; + +} + +#endif // __NMR_MODELREADERNODE093_MATERIAL diff --git a/Include/Model/Reader/v093/NMR_ModelReaderNode093_Mesh.h b/Include/Model/Reader/v093/NMR_ModelReaderNode093_Mesh.h new file mode 100644 index 0000000..02cfd7c --- /dev/null +++ b/Include/Model/Reader/v093/NMR_ModelReaderNode093_Mesh.h @@ -0,0 +1,65 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode093_Mesh.h defines the Model Reader Mesh Node Class. +A mesh reader model node is a parser for the mesh node of an XML Model Stream. + +--*/ + +#ifndef __NMR_MODELREADERNODE093_MESH +#define __NMR_MODELREADERNODE093_MESH + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Reader/NMR_ModelReader_TexCoordMapping.h" +#include "Model/Reader/NMR_ModelReader_ColorMapping.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelObject.h" +#include "Model/Classes/NMR_ModelBaseMaterials.h" + +namespace NMR { + + class CModelReaderNode093_Mesh : public CModelReaderNode { + private: + CMesh * m_pMesh; + CModel * m_pModel; + PModelReader_TexCoordMapping m_pTexCoordMapping; + PModelReader_ColorMapping m_pColorMapping; + PModelBaseMaterialResource m_pMaterialResource; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode093_Mesh() = delete; + CModelReaderNode093_Mesh(_In_ CModel * pModel, _In_ CMesh * pMesh, _In_ PModelReader_ColorMapping pColorMapping, _In_ PModelBaseMaterialResource pMaterialResource, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + +} + +#endif // __NMR_MODELREADERNODE093_MESH diff --git a/Include/Model/Reader/v093/NMR_ModelReaderNode093_Object.h b/Include/Model/Reader/v093/NMR_ModelReaderNode093_Object.h new file mode 100644 index 0000000..f67caf6 --- /dev/null +++ b/Include/Model/Reader/v093/NMR_ModelReaderNode093_Object.h @@ -0,0 +1,73 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode093_Object.h defines the Model Reader Object Node Class. +A object reader model node is a parser for the object node of an XML Model Stream. + +--*/ + +#ifndef __NMR_MODELREADERNODE093_OBJECT +#define __NMR_MODELREADERNODE093_OBJECT + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Model/Classes/NMR_ModelObject.h" +#include "Model/Classes/NMR_ModelBaseMaterials.h" + +#include "Model/Reader/NMR_ModelReader_ColorMapping.h" +#include "Model/Reader/NMR_ModelReader_TexCoordMapping.h" + +namespace NMR { + + class CModelReaderNode093_Object : public CModelReaderNode { + private: + CModel * m_pModel; + ModelResourceID m_nID; + std::string m_sThumbnail; + std::string m_sName; + std::string m_sType; + nfBool m_bHasType; + PModelObject m_pObject; + PModelReader_ColorMapping m_pColorMapping; + nfInt32 m_nObjectLevelColorID; + nfInt32 m_nObjectLevelMaterialID; + + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode093_Object() = delete; + CModelReaderNode093_Object(_In_ CModel * pModel, _In_ PModelReader_ColorMapping pColorMapping, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + +} + +#endif // __NMR_MODELREADERNODE093_OBJECT diff --git a/Include/Model/Reader/v093/NMR_ModelReaderNode093_Resources.h b/Include/Model/Reader/v093/NMR_ModelReaderNode093_Resources.h new file mode 100644 index 0000000..8c2792a --- /dev/null +++ b/Include/Model/Reader/v093/NMR_ModelReaderNode093_Resources.h @@ -0,0 +1,62 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode093_Resources.h defines the Model Reader Resources Node Class. +A resources reader model node is a parser for the resources node of an XML Model Stream. + +--*/ + +#ifndef __NMR_MODELREADERNODE093_RESOURCES +#define __NMR_MODELREADERNODE093_RESOURCES + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Reader/NMR_ModelReader_ColorMapping.h" +#include "Model/Reader/NMR_ModelReader_TexCoordMapping.h" + +#include "Model/Classes/NMR_ModelResource.h" +#include "Model/Classes/NMR_ModelBaseMaterial.h" +#include "Model/Classes/NMR_ModelBaseMaterials.h" + +namespace NMR { + + class CModelReaderNode093_Resources : public CModelReaderNode { + protected: + PModelReader_ColorMapping m_pColorMapping; + + CModel * m_pModel; + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode093_Resources() = delete; + CModelReaderNode093_Resources(_In_ CModel * pModel, _In_ PModelWarnings pWarnings); + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + +} + +#endif // __NMR_MODELREADERNODE093_RESOURCES diff --git a/Include/Model/Reader/v093/NMR_ModelReaderNode093_Texture.h b/Include/Model/Reader/v093/NMR_ModelReaderNode093_Texture.h new file mode 100644 index 0000000..08a5298 --- /dev/null +++ b/Include/Model/Reader/v093/NMR_ModelReaderNode093_Texture.h @@ -0,0 +1,77 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode093_Texture.h defines the Model Reader Texture Class. + +--*/ + +#ifndef __NMR_MODELREADERNODE093_TEXTURE +#define __NMR_MODELREADERNODE093_TEXTURE + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Model/Classes/NMR_ModelObject.h" + +namespace NMR { + + class CModelReaderNode093_Texture : public CModelReaderNode { + private: + CModel * m_pModel; + ModelResourceID m_nID; + + std::string m_sPath; + std::string m_sContentType; + std::string m_sTileStyleU; + std::string m_sTileStyleV; + std::string m_sFilter; + + PModelTexture2DResource m_pTexture2DResource; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + public: + CModelReaderNode093_Texture() = delete; + CModelReaderNode093_Texture(_In_ CModel * pModel, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + + ModelResourceID getID (); + + std::string getPath(); + std::string getContentType(); + std::string getTileStyleU(); + std::string getTileStyleV(); + }; + + typedef std::shared_ptr PModelReaderNode093_Texture; + + +} + +#endif // __NMR_MODELREADERNODE093_TEXTURE + diff --git a/Include/Model/Reader/v093/NMR_ModelReaderNode093_TextureVertex.h b/Include/Model/Reader/v093/NMR_ModelReaderNode093_TextureVertex.h new file mode 100644 index 0000000..77e5daa --- /dev/null +++ b/Include/Model/Reader/v093/NMR_ModelReaderNode093_TextureVertex.h @@ -0,0 +1,64 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_TextureVertex.h defines the Model Reader Texture Vertex Node Class. +A texture vertex reader model node is a parser for the texture vertex node of an XML Model Stream. + +--*/ + +#ifndef __NMR_MODELREADERNODE093_TEXTUREVERTEX +#define __NMR_MODELREADERNODE093_TEXTUREVERTEX + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelObject.h" + +namespace NMR { + + class CModelReaderNode093_TextureVertex : public CModelReaderNode { + private: + nfFloat m_fU; + nfFloat m_fV; + nfBool m_bHasU; + nfBool m_bHasV; + public: + CModelReaderNode093_TextureVertex() = delete; + CModelReaderNode093_TextureVertex(_In_ PModelWarnings pWarnings); + + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + + void retrieveTexCoords(_Out_ nfFloat & fU, _Out_ nfFloat & fV); + }; + + typedef std::shared_ptr PModelReaderNode093_TextureVertex; + +} + +#endif // __NMR_MODELREADERNODE093_TEXTUREVERTEX diff --git a/Include/Model/Reader/v093/NMR_ModelReaderNode093_TextureVertices.h b/Include/Model/Reader/v093/NMR_ModelReaderNode093_TextureVertices.h new file mode 100644 index 0000000..e5e0762 --- /dev/null +++ b/Include/Model/Reader/v093/NMR_ModelReaderNode093_TextureVertices.h @@ -0,0 +1,63 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode093_TextureVertices.h defines the Model Reader Texture Vertices Node Class. +A vertices reader model node is a parser for the vertices node of an XML Model Stream. + +--*/ + +#ifndef __NMR_MODELREADERNODE093_TEXTUREVERTICES +#define __NMR_MODELREADERNODE093_TEXTUREVERTICES + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Reader/NMR_ModelReader_TexCoordMapping.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelObject.h" + +namespace NMR { + + class CModelReaderNode093_TextureVertices : public CModelReaderNode { + private: + CMesh * m_pMesh; + PModelReader_TexCoordMapping m_pTexCoordMapping; + ModelResourceIndex m_nTexCoordIndex; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode093_TextureVertices() = delete; + CModelReaderNode093_TextureVertices(_In_ CMesh * pMesh, _In_ PModelWarnings pWarnings, _In_ PModelReader_TexCoordMapping pTexCoordMapping); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + + typedef std::shared_ptr PModelReaderNode093_TextureVertices; + +} + +#endif // __NMR_MODELREADERNODE093_TEXTUREVERTICES diff --git a/Include/Model/Reader/v093/NMR_ModelReaderNode093_Triangle.h b/Include/Model/Reader/v093/NMR_ModelReaderNode093_Triangle.h new file mode 100644 index 0000000..33456f6 --- /dev/null +++ b/Include/Model/Reader/v093/NMR_ModelReaderNode093_Triangle.h @@ -0,0 +1,75 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode093_Triangle.h defines the Model Reader Triangle Node Class. +A triangle reader model node is a parser for the triangle node of an XML Model Stream. + +--*/ + +#ifndef __NMR_MODELREADERNODE093_TRIANGLE +#define __NMR_MODELREADERNODE093_TRIANGLE + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelObject.h" + +namespace NMR { + + class CModelReaderNode093_Triangle : public CModelReaderNode { + protected: + nfInt32 m_nIndex1; + nfInt32 m_nIndex2; + nfInt32 m_nIndex3; + nfInt32 m_nTextureIndex1; + nfInt32 m_nTextureIndex2; + nfInt32 m_nTextureIndex3; + nfInt32 m_nColorID1; + nfInt32 m_nColorID2; + nfInt32 m_nColorID3; + nfInt32 m_nMaterialID; + nfInt32 m_nTextureID; + + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + public: + CModelReaderNode093_Triangle() = delete; + CModelReaderNode093_Triangle(_In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + void retrieveIndices(_Out_ nfInt32 & nIndex1, _Out_ nfInt32 & nIndex2, _Out_ nfInt32 & nIndex3, nfInt32 nNodeCount); + nfBool retrieveTextureIndices(_Out_ nfInt32 & nIndex1, _Out_ nfInt32 & nIndex2, _Out_ nfInt32 & nIndex3); + + nfBool retrieveColorIDs(_Out_ nfInt32 & nColorID1, _Out_ nfInt32 & nColorID2, _Out_ nfInt32 & nColorID3); + nfInt32 retrieveTextureID(); + nfInt32 retrieveMaterialID(); + }; + + typedef std::shared_ptr PModelReaderNode093_Triangle; + +} + +#endif // __NMR_MODELREADERNODE093_TRIANGLE diff --git a/Include/Model/Reader/v093/NMR_ModelReaderNode093_Triangles.h b/Include/Model/Reader/v093/NMR_ModelReaderNode093_Triangles.h new file mode 100644 index 0000000..9d297c3 --- /dev/null +++ b/Include/Model/Reader/v093/NMR_ModelReaderNode093_Triangles.h @@ -0,0 +1,72 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_Triangles.h defines the Model Reader Triangles Node Class. +A triangles reader model node is a parser for the triangles node of an XML Model Stream. + +--*/ + +#ifndef __NMR_MODELREADERNODE093_TRIANGLES +#define __NMR_MODELREADERNODE093_TRIANGLES + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Reader/NMR_ModelReader_ColorMapping.h" +#include "Model/Reader/NMR_ModelReader_TexCoordMapping.h" + +#include "Common/MeshInformation/NMR_MeshInformation_Properties.h" + +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelObject.h" +#include "Model/Classes/NMR_ModelBaseMaterials.h" + +namespace NMR { + + class CModelReaderNode093_Triangles : public CModelReaderNode { + protected: + CMesh * m_pMesh; + CModel * m_pModel; + PModelReader_ColorMapping m_pColorMapping; + PModelReader_TexCoordMapping m_pTexCoordMapping; + PModelBaseMaterialResource m_pDefaultMaterialResource; + + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + + _Ret_notnull_ CMeshInformation_Properties * createPropertiesInformation(); + public: + CModelReaderNode093_Triangles() = delete; + CModelReaderNode093_Triangles(_In_ CModel * pModel, _In_ CMesh * pMesh, _In_ PModelReader_ColorMapping pColorMapping, _In_ PModelReader_TexCoordMapping pTexCoordMapping, PModelBaseMaterialResource pMaterialResource, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + + typedef std::shared_ptr PModelReaderNode093_Triangles; + +} + +#endif // __NMR_MODELREADERNODE093_TRIANGLES diff --git a/Include/Model/Reader/v093/NMR_ModelReaderNode093_Vertex.h b/Include/Model/Reader/v093/NMR_ModelReaderNode093_Vertex.h new file mode 100644 index 0000000..79d6575 --- /dev/null +++ b/Include/Model/Reader/v093/NMR_ModelReaderNode093_Vertex.h @@ -0,0 +1,66 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_Vertex.h defines the Model Reader Vertex Node Class. +A vertex reader model node is a parser for the vertex node of an XML Model Stream. + +--*/ + +#ifndef __NMR_MODELREADERNODE093_VERTEX +#define __NMR_MODELREADERNODE093_VERTEX + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelObject.h" + +namespace NMR { + + class CModelReaderNode093_Vertex : public CModelReaderNode { + private: + nfFloat m_fX; + nfFloat m_fY; + nfFloat m_fZ; + nfBool m_bHasX; + nfBool m_bHasY; + nfBool m_bHasZ; + public: + CModelReaderNode093_Vertex() = delete; + CModelReaderNode093_Vertex(_In_ PModelWarnings pWarnings); + + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + + void retrievePosition(_Out_ nfFloat & fX, _Out_ nfFloat & fY, _Out_ nfFloat & fZ); + }; + + typedef std::shared_ptr PModelReaderNode093_Vertex; + +} + +#endif // __NMR_MODELREADERNODE093_VERTEX diff --git a/Include/Model/Reader/v093/NMR_ModelReaderNode093_Vertices.h b/Include/Model/Reader/v093/NMR_ModelReaderNode093_Vertices.h new file mode 100644 index 0000000..e95b739 --- /dev/null +++ b/Include/Model/Reader/v093/NMR_ModelReaderNode093_Vertices.h @@ -0,0 +1,60 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode093_Vertices.h defines the Model Reader Vertices Node Class. +A vertices reader model node is a parser for the vertices node of an XML Model Stream. + +--*/ + +#ifndef __NMR_MODELREADERNODE093_VERTICES +#define __NMR_MODELREADERNODE093_VERTICES + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelObject.h" + +namespace NMR { + + class CModelReaderNode093_Vertices : public CModelReaderNode { + private: + CMesh * m_pMesh; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode093_Vertices() = delete; + CModelReaderNode093_Vertices(_In_ CMesh * pMesh, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + + typedef std::shared_ptr PModelReaderNode093_Vertices; + +} + +#endif // __NMR_MODELREADERNODE093_VERTICES diff --git a/Include/Model/Reader/v100/NMR_ModelReaderNode100_BaseMaterial.h b/Include/Model/Reader/v100/NMR_ModelReaderNode100_BaseMaterial.h new file mode 100644 index 0000000..6a971ee --- /dev/null +++ b/Include/Model/Reader/v100/NMR_ModelReaderNode100_BaseMaterial.h @@ -0,0 +1,71 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_BaseMaterial.h defines the Model Reader Base Material Node Class. + +--*/ + +#ifndef __NMR_MODELREADERNODE100_BASEMATERIAL +#define __NMR_MODELREADERNODE100_BASEMATERIAL + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Model/Classes/NMR_ModelObject.h" + +namespace NMR { + + class CModelReaderNode100_BaseMaterial : public CModelReaderNode { + private: + CModel * m_pModel; + + nfBool m_bHasName; + std::string m_sName; + + nfBool m_bHasDisplayColor; + nfColor m_cDisplayColor; + + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + public: + CModelReaderNode100_BaseMaterial() = delete; + CModelReaderNode100_BaseMaterial(_In_ CModel * pModel, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + + nfBool hasDisplayColor(); + nfBool hasName(); + nfColor getDisplayColor(); + std::string getMaterialName(); + }; + + typedef std::shared_ptr PModelReaderNode100_BaseMaterial; + +} + +#endif // __NMR_MODELREADERNODE100_BASEMATERIAL diff --git a/Include/Model/Reader/v100/NMR_ModelReaderNode100_BaseMaterials.h b/Include/Model/Reader/v100/NMR_ModelReaderNode100_BaseMaterials.h new file mode 100644 index 0000000..0e6234e --- /dev/null +++ b/Include/Model/Reader/v100/NMR_ModelReaderNode100_BaseMaterials.h @@ -0,0 +1,61 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_BaseMaterials.h defines the Model Reader Base Materials Class. + +--*/ + +#ifndef __NMR_MODELREADERNODE100_BASEMATERIALS +#define __NMR_MODELREADERNODE100_BASEMATERIALS + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Model/Classes/NMR_ModelObject.h" + +namespace NMR { + + class CModelReaderNode100_BaseMaterials : public CModelReaderNode { + private: + CModel * m_pModel; + ModelResourceID m_nID; + + PModelBaseMaterialResource m_pBaseMaterialResource; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode100_BaseMaterials() = delete; + CModelReaderNode100_BaseMaterials(_In_ CModel * pModel, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + +} + +#endif // __NMR_MODELREADERNODE100_BASEMATERIALS diff --git a/Include/Model/Reader/v100/NMR_ModelReaderNode100_Build.h b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Build.h new file mode 100644 index 0000000..712b3cd --- /dev/null +++ b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Build.h @@ -0,0 +1,57 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_Build.h defines the Model Reader Build Node Class. +A build reader model node is a parser for the build node of an XML Model Stream. + +--*/ +#ifndef __NMR_MODELREADERNODE100_BUILD +#define __NMR_MODELREADERNODE100_BUILD + +#include "Model/Reader/NMR_ModelReaderNode.h" + +namespace NMR { + + class CModelReaderNode100_Build : public CModelReaderNode { + protected: + CModel * m_pModel; + PUUID m_UUID; + + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue, _In_z_ const nfChar * pNameSpace); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode100_Build() = delete; + CModelReaderNode100_Build(_In_ CModel * pModel, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + +} + +#endif // __NMR_MODELREADERNODE100_BUILD diff --git a/Include/Model/Reader/v100/NMR_ModelReaderNode100_BuildItem.h b/Include/Model/Reader/v100/NMR_ModelReaderNode100_BuildItem.h new file mode 100644 index 0000000..f2af2c4 --- /dev/null +++ b/Include/Model/Reader/v100/NMR_ModelReaderNode100_BuildItem.h @@ -0,0 +1,69 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_BuildItem.h defines the Model Reader BuildItem Node Class. +A builditem reader model node is a parser for the builditem node of an XML Model Stream. + +--*/ + +#ifndef __NMR_MODELREADERNODE100_BUILDITEM +#define __NMR_MODELREADERNODE100_BUILDITEM + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelMetaDataGroup.h" + +namespace NMR { + + class CModelReaderNode100_BuildItem : public CModelReaderNode { + private: + CModel * m_pModel; + nfInt32 m_ObjectID; + nfBool m_bHasID; + std::string m_sPartNumber; + NMATRIX3 m_mTransform; + + // Production Extension + std::string m_sPath; + PUUID m_UUID; + + bool m_hasPath; + PModelMetaDataGroup m_MetaDataGroup; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue, _In_z_ const nfChar * pNameSpace); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode100_BuildItem() = delete; + CModelReaderNode100_BuildItem(_In_ CModel * pModel, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + +} + +#endif // __NMR_MODELREADERNODE100_BUILDITEM diff --git a/Include/Model/Reader/v100/NMR_ModelReaderNode100_Color.h b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Color.h new file mode 100644 index 0000000..28ebd7e --- /dev/null +++ b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Color.h @@ -0,0 +1,66 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_Color.h defines the Model Reader Color Node Class. + +--*/ + +#ifndef __NMR_MODELREADERNODE100_COLOR +#define __NMR_MODELREADERNODE100_COLOR + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Model/Classes/NMR_ModelObject.h" + +namespace NMR { + + class CModelReaderNode100_Color : public CModelReaderNode { + private: + CModel * m_pModel; + + nfBool m_bHasColor; + nfColor m_cColor; + + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + public: + CModelReaderNode100_Color() = delete; + CModelReaderNode100_Color(_In_ CModel * pModel, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + + nfBool hasColor(); + nfColor getColor(); + }; + + typedef std::shared_ptr PModelReaderNode100_Color; + +} + +#endif // __NMR_MODELREADERNODE100_COLOR diff --git a/Include/Model/Reader/v100/NMR_ModelReaderNode100_Colors.h b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Colors.h new file mode 100644 index 0000000..194cbf5 --- /dev/null +++ b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Colors.h @@ -0,0 +1,62 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_BaseMaterials.h defines the Model Reader Colors Class. + +--*/ + +#ifndef __NMR_MODELREADERNODE100_COLORS +#define __NMR_MODELREADERNODE100_COLORS + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Model/Classes/NMR_ModelObject.h" + +namespace NMR { + + class CModelReaderNode100_Colors : public CModelReaderNode { + private: + CModel * m_pModel; + ModelResourceID m_nID; + ModelResourceIndex m_nColorIndex; + PModelColorGroupResource m_pColorGroup; + + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode100_Colors() = delete; + CModelReaderNode100_Colors(_In_ CModel * pModel, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + +} + +#endif // __NMR_MODELREADERNODE100_COLORS diff --git a/Include/Model/Reader/v100/NMR_ModelReaderNode100_Component.h b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Component.h new file mode 100644 index 0000000..bb981b2 --- /dev/null +++ b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Component.h @@ -0,0 +1,70 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReader100_Component.h defines the Model Component Reader Node Class. + +--*/ + +#ifndef __NMR_MODELREADERNODE100_COMPONENT +#define __NMR_MODELREADERNODE100_COMPONENT + +#include "Model/Reader/NMR_ModelReaderNode.h" + +namespace NMR { + + class CModelReaderNode100_Component : public CModelReaderNode { + protected: + CModel * m_pModel; + ModelResourceID m_ObjectID; + nfBool m_bHasID; + NMATRIX3 m_mTransform; + + nfBool m_bHasPath; + PUUID m_UUID; + std::string m_sPath; + + virtual void OnNSAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue, _In_z_ const nfChar * pNameSpace); + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + public: + CModelReaderNode100_Component() = delete; + CModelReaderNode100_Component(_In_ CModel * pModel, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + + CModelObject * getObject(); + NMATRIX3 getTransform(); + + PUUID uuid(); + + }; + + typedef std::shared_ptr PModelReaderNode100_Component; + +} + +#endif // __NMR_MODELREADERNODE100_COMPONENT diff --git a/Include/Model/Reader/v100/NMR_ModelReaderNode100_Components.h b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Components.h new file mode 100644 index 0000000..d9896bc --- /dev/null +++ b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Components.h @@ -0,0 +1,58 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_Components.h defines the Model Components Reader Node Class. + +--*/ + +#ifndef __NMR_MODELREADERNODE100_COMPONENTS +#define __NMR_MODELREADERNODE100_COMPONENTS + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Model/Classes/NMR_ModelMetaData.h" + +namespace NMR { + + class CModelReaderNode100_Components : public CModelReaderNode { + private: + protected: + CModelComponentsObject * m_pComponentsObject; + + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode100_Components() = delete; + CModelReaderNode100_Components(_In_ CModelComponentsObject * pComponentsObject, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + +} + +#endif // __NMR_MODELREADERNODE100_COMPONENTS diff --git a/Include/Model/Reader/v100/NMR_ModelReaderNode100_Composite.h b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Composite.h new file mode 100644 index 0000000..d45892a --- /dev/null +++ b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Composite.h @@ -0,0 +1,66 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_Composite.h defines the Model Reader Tex2Coord Node Class. + +--*/ + +#ifndef __NMR_MODELREADERNODE100_COMPOSITE +#define __NMR_MODELREADERNODE100_COMPOSITE + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelObject.h" +#include "Model/Classes/NMR_ModelCompositeMaterials.h" +#include "Model/Classes/NMR_ModelTypes.h" + +namespace NMR { + + class CModelReaderNode100_Composite : public CModelReaderNode { + private: + CModel * m_pModel; + + PModelComposite m_pModelComposite; + const std::vector& m_vctBaseMaterialPropertyIds; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + public: + CModelReaderNode100_Composite() = delete; + CModelReaderNode100_Composite(_In_ CModel * pModel, _In_ PModelWarnings pWarnings, _In_z_ const std::vector& baseMaterialPropertyIds); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + + PModelComposite getComposite(); + }; + + typedef std::shared_ptr PModelReaderNode100_Composite; + +} + +#endif // __NMR_MODELREADERNODE100_COMPOSITE + + diff --git a/Include/Model/Reader/v100/NMR_ModelReaderNode100_CompositeMaterials.h b/Include/Model/Reader/v100/NMR_ModelReaderNode100_CompositeMaterials.h new file mode 100644 index 0000000..a393d1a --- /dev/null +++ b/Include/Model/Reader/v100/NMR_ModelReaderNode100_CompositeMaterials.h @@ -0,0 +1,67 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_CompositeMaterials.h defines the Model Reader CompositeMaterials Class. + +--*/ + +#ifndef __NMR_MODELREADERNODE100_COMPOSITEMATERIALS +#define __NMR_MODELREADERNODE100_COMPOSITEMATERIALS + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Model/Classes/NMR_ModelObject.h" +#include "Model/Classes/NMR_ModelCompositeMaterials.h" + +namespace NMR { + + class CModelReaderNode100_CompositeMaterials : public CModelReaderNode { + private: + CModel * m_pModel; + ModelResourceID m_nID; + ModelResourceID m_nBaseMaterialID; + std::shared_ptr> m_pMatIndices; + std::vector m_vctMaterialPropertyIDs; + + PModelCompositeMaterialsResource m_pCompositeMaterials; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode100_CompositeMaterials() = delete; + CModelReaderNode100_CompositeMaterials(_In_ CModel * pModel, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + +} + +#endif // __NMR_MODELREADERNODE100_COMPOSITEMATERIALS + + diff --git a/Include/Model/Reader/v100/NMR_ModelReaderNode100_Mesh.h b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Mesh.h new file mode 100644 index 0000000..573f7f8 --- /dev/null +++ b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Mesh.h @@ -0,0 +1,71 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_Mesh.h defines the Model Reader Mesh Node Class. +A mesh reader model node is a parser for the mesh node of an XML Model Stream. + +--*/ + +#ifndef __NMR_MODELREADERNODE100_MESH +#define __NMR_MODELREADERNODE100_MESH + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Reader/NMR_ModelReader_TexCoordMapping.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelObject.h" + +namespace NMR { + + class CModelReaderNode100_Mesh : public CModelReaderNode { + private: + CMesh * m_pMesh; + CModel * m_pModel; + + PPackageResourceID m_pObjectLevelPropertyID; + ModelResourceIndex m_nObjectLevelPropertyIndex; + + eModelBeamLatticeClipMode m_eClipMode; + nfBool m_bHasClippingMeshID; + ModelResourceID m_nClippingMeshID; + nfBool m_bHasRepresentationMeshID; + ModelResourceID m_nRepresentationMeshID; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode100_Mesh() = delete; + CModelReaderNode100_Mesh(_In_ CModel * pModel, _In_ CMesh * pMesh, _In_ PModelWarnings pWarnings, _In_ PProgressMonitor pProgressMonitor, _In_ PPackageResourceID m_pObjectLevelPropertyID, _In_ ModelResourceIndex nDefaultPropertyIndex); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + void retrieveClippingInfo(_Out_ eModelBeamLatticeClipMode &eClipMode, _Out_ nfBool & bHasClippingMode, _Out_ ModelResourceID & nClippingMeshID); + void retrieveRepresentationInfo(_Out_ nfBool & bHasRepresentation, _Out_ ModelResourceID & nRepresentationMeshID); + }; + typedef std::shared_ptr PModelReaderNode100_Mesh; +} + +#endif // __NMR_MODELREADERNODE100_MESH diff --git a/Include/Model/Reader/v100/NMR_ModelReaderNode100_MetaData.h b/Include/Model/Reader/v100/NMR_ModelReaderNode100_MetaData.h new file mode 100644 index 0000000..609f98b --- /dev/null +++ b/Include/Model/Reader/v100/NMR_ModelReaderNode100_MetaData.h @@ -0,0 +1,66 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_MetaData.h defines the Model Reader MetaData Node Class. +A metadata reader model node is a parser for the triangle node of an XML Model Stream. + +--*/ + +#ifndef __NMR_MODELREADERNODE100_METADATA +#define __NMR_MODELREADERNODE100_METADATA + +#include "Model/Reader/NMR_ModelReaderNode.h" + +namespace NMR { + + class CModelReaderNode100_MetaData : public CModelReaderNode { + private: + std::string m_sKey; + std::string m_sValue; + std::string m_sType; + nfBool m_bPreserve; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnText(_In_z_ const nfChar * pText, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode100_MetaData() = delete; + CModelReaderNode100_MetaData(_In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + + std::string getKey(); + std::string getValue(); + std::string getType(); + nfBool getPreserve(); + }; + + typedef std::shared_ptr PModelReaderNode100_MetaData; + +} + +#endif // __NMR_MODELREADERNODE100_METADATA diff --git a/Include/Model/Reader/v100/NMR_ModelReaderNode100_MetaDataGroup.h b/Include/Model/Reader/v100/NMR_ModelReaderNode100_MetaDataGroup.h new file mode 100644 index 0000000..b48182e --- /dev/null +++ b/Include/Model/Reader/v100/NMR_ModelReaderNode100_MetaDataGroup.h @@ -0,0 +1,62 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_MetaDataGroup.h defines the Model Reader MetaDataGroup Node Class. +A metadatagroup reader node is a parser for the metadatagroup node of an XML Model Stream. + +--*/ + +#ifndef __NMR_MODELREADERNODE100_METADATAGROUP +#define __NMR_MODELREADERNODE100_METADATAGROUP + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelMetaDataGroup.h" + +namespace NMR { + + class CModelReaderNode100_MetaDataGroup : public CModelReaderNode { + private: + PModelMetaDataGroup m_MetaDataGroup; + protected: + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnText(_In_z_ const nfChar * pText, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode100_MetaDataGroup() = delete; + CModelReaderNode100_MetaDataGroup(_In_ PModelWarnings pWarnings); + + PModelMetaDataGroup getMetaDataGroup(); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + + typedef std::shared_ptr PModelReaderNode100_MetaDataGroup; + +} + +#endif // __NMR_MODELREADERNODE100_METADATAGROUP diff --git a/Include/Model/Reader/v100/NMR_ModelReaderNode100_Multi.h b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Multi.h new file mode 100644 index 0000000..75d9f8a --- /dev/null +++ b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Multi.h @@ -0,0 +1,65 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_Multi.h defines the Model Reader Multi Node Class. + +--*/ + +#ifndef __NMR_MODELREADERNODE100_MULTI +#define __NMR_MODELREADERNODE100_MULTI + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelObject.h" +#include "Model/Classes/NMR_ModelTypes.h" + +namespace NMR { + + class CModelReaderNode100_Multi : public CModelReaderNode { + private: + CModel * m_pModel; + + nfBool m_bHasPIndices; + std::vector m_vctPIndices; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + public: + CModelReaderNode100_Multi() = delete; + CModelReaderNode100_Multi(_In_ CModel * pModel, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + + std::vector& getPIndices(); + }; + + typedef std::shared_ptr PModelReaderNode100_Multi; + +} + +#endif // __NMR_MODELREADERNODE100_MULTI + + diff --git a/Include/Model/Reader/v100/NMR_ModelReaderNode100_MultiProperties.h b/Include/Model/Reader/v100/NMR_ModelReaderNode100_MultiProperties.h new file mode 100644 index 0000000..d3476e7 --- /dev/null +++ b/Include/Model/Reader/v100/NMR_ModelReaderNode100_MultiProperties.h @@ -0,0 +1,63 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_MultiProperties.h defines the Model Reader MultiProperties Class. + +--*/ + +#ifndef __NMR_MODELREADERNODE100_MULTIPROPERTIES +#define __NMR_MODELREADERNODE100_MULTIPROPERTIES + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelMultiPropertyGroup.h" + +namespace NMR { + + class CModelReaderNode100_MultiProperties : public CModelReaderNode { + private: + CModel * m_pModel; + ModelResourceID m_nID; + std::shared_ptr> m_pPIDs; + std::shared_ptr> m_pBlendMethods; + PModelMultiPropertyGroupResource m_pMultiPropertyGroup; + + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode100_MultiProperties() = delete; + CModelReaderNode100_MultiProperties(_In_ CModel * pModel, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + +} + +#endif // __NMR_MODELREADERNODE100_MULTIPROPERTIES + + diff --git a/Include/Model/Reader/v100/NMR_ModelReaderNode100_Object.h b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Object.h new file mode 100644 index 0000000..7ec4450 --- /dev/null +++ b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Object.h @@ -0,0 +1,87 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_Object.h defines the Model Reader Object Node Class. +A object reader model node is a parser for the object node of an XML Model Stream. + +--*/ + +#ifndef __NMR_MODELREADERNODE100_OBJECT +#define __NMR_MODELREADERNODE100_OBJECT + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Reader/v100/NMR_ModelReaderNode100_Mesh.h" +#include "Model/Reader/NMR_ModelReader_TexCoordMapping.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Model/Classes/NMR_ModelMetaDataGroup.h" +#include "Model/Classes/NMR_ModelObject.h" + + +namespace NMR { + + class CModelReaderNode100_Object : public CModelReaderNode { + private: + CModel * m_pModel; + ModelResourceID m_nID; + nfBool m_bHasThumbnail; + std::string m_sThumbnailPath; + std::string m_sPartNumber; + std::string m_sName; + PUUID m_UUID; + std::string m_sType; + nfBool m_bHasType; + PModelObject m_pObject; + nfBool m_bHasDefaultPropertyID; + nfBool m_bHasDefaultPropertyIndex; + ModelResourceID m_nObjectLevelPropertyModelID; + PPackageResourceID m_pObjectLevelPropertyID; + ModelResourceIndex m_nObjectLevelPropertyIndex; + + nfUint32 m_nSliceStackId; + eModelSlicesMeshResolution m_eSlicesMeshResolution; + nfBool m_bHasMeshResolution; + + PModelMetaDataGroup m_MetaDataGroup; + + void createDefaultProperties(); + void handleBeamLatticeExtension(CModelReaderNode100_Mesh* pXMLNode); + protected: + virtual void OnNSAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue, _In_z_ const nfChar * pNameSpace); + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode100_Object() = delete; + CModelReaderNode100_Object(_In_ CModel * pModel, _In_ PModelWarnings pWarnings, _In_ PProgressMonitor pProgressMonitor); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + +} + +#endif // __NMR_MODELREADERNODE100_OBJECT diff --git a/Include/Model/Reader/v100/NMR_ModelReaderNode100_Resources.h b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Resources.h new file mode 100644 index 0000000..ba7d362 --- /dev/null +++ b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Resources.h @@ -0,0 +1,59 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_Resources.h defines the Model Reader Resources Node Class. +A resources reader model node is a parser for the resources node of an XML Model Stream. + +--*/ + +#ifndef __NMR_MODELREADERNODE100_RESOURCES +#define __NMR_MODELREADERNODE100_RESOURCES + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelTexture2DGroup.h" + +namespace NMR { + + class CModelReaderNode100_Resources : public CModelReaderNode { + protected: + CModel * m_pModel; + std::string m_sPath; + + int m_nProgressCount; + + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode100_Resources() = delete; + CModelReaderNode100_Resources(_In_ CModel * pModel, _In_ PModelWarnings pWarnings, _In_z_ const std::string sPath, _In_ PProgressMonitor pProgressMonitor); + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + +} + +#endif // __NMR_MODELREADERNODE100_RESOURCES diff --git a/Include/Model/Reader/v100/NMR_ModelReaderNode100_Tex2Coord.h b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Tex2Coord.h new file mode 100644 index 0000000..86be8e5 --- /dev/null +++ b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Tex2Coord.h @@ -0,0 +1,70 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_Tex2Coord.h defines the Model Reader Tex2Coord Node Class. + +--*/ + +#ifndef __NMR_MODELREADERNODE100_TEX2COORD +#define __NMR_MODELREADERNODE100_TEX2COORD + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Model/Classes/NMR_ModelObject.h" + +namespace NMR { + + class CModelReaderNode100_Tex2Coord : public CModelReaderNode { + private: + CModel * m_pModel; + + nfBool m_bHasU; + nfBool m_bHasV; + MODELTEXTURE2DCOORDINATE m_sUVCoordinate; + + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + public: + CModelReaderNode100_Tex2Coord() = delete; + CModelReaderNode100_Tex2Coord(_In_ CModel * pModel, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + + nfBool hasU(); + nfBool hasV(); + MODELTEXTURE2DCOORDINATE getUV(); + }; + + typedef std::shared_ptr PModelReaderNode100_Tex2Coord; + +} + +#endif // __NMR_MODELREADERNODE100_TEX2COORD + + diff --git a/Include/Model/Reader/v100/NMR_ModelReaderNode100_Tex2DGroup.h b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Tex2DGroup.h new file mode 100644 index 0000000..32c6689 --- /dev/null +++ b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Tex2DGroup.h @@ -0,0 +1,65 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_Tex2DGroup.h defines the Model Reader Tex2DGroup Class. + +--*/ + +#ifndef __NMR_MODELREADERNODE100_TEX2DGROUP +#define __NMR_MODELREADERNODE100_TEX2DGROUP + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Model/Classes/NMR_ModelObject.h" +#include "Model/Classes/NMR_ModelTexture2DGroup.h" + +namespace NMR { + + class CModelReaderNode100_Tex2DGroup : public CModelReaderNode { + private: + CModel * m_pModel; + ModelResourceID m_nID; + ModelResourceID m_nTextureID; + + PModelTexture2DGroupResource m_pTexture2DGroup; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode100_Tex2DGroup() = delete; + CModelReaderNode100_Tex2DGroup(_In_ CModel * pModel, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + +} + +#endif // __NMR_MODELREADERNODE100_TEX2DGROUP + + diff --git a/Include/Model/Reader/v100/NMR_ModelReaderNode100_Texture2D.h b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Texture2D.h new file mode 100644 index 0000000..c07bd60 --- /dev/null +++ b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Texture2D.h @@ -0,0 +1,73 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_Texture2D.h defines the Model Reader Texture 2D Class. + +--*/ + +#ifndef __NMR_MODELREADERNODE100_TEXTURE2D +#define __NMR_MODELREADERNODE100_TEXTURE2D + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Model/Classes/NMR_ModelObject.h" + +namespace NMR { + + class CModelReaderNode100_Texture2D : public CModelReaderNode { + private: + CModel * m_pModel; + ModelResourceID m_nID; + + std::string m_sPath; + std::string m_sContentType; + std::string m_sTileStyleU; + std::string m_sTileStyleV; + std::string m_sFilter; + + nfBool m_hasBox; + nfFloat m_fU; + nfFloat m_fV; + nfFloat m_fWidth; + nfFloat m_fHeight; + + PModelTexture2DResource m_pTexture2DResource; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + public: + CModelReaderNode100_Texture2D() = delete; + CModelReaderNode100_Texture2D(_In_ CModel * pModel, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + +} + +#endif // __NMR_MODELREADERNODE100_TEXTURE2D + diff --git a/Include/Model/Reader/v100/NMR_ModelReaderNode100_Triangle.h b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Triangle.h new file mode 100644 index 0000000..8912f17 --- /dev/null +++ b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Triangle.h @@ -0,0 +1,67 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_Triangle.h defines the Model Reader Triangle Node Class. +A triangle reader model node is a parser for the triangle node of an XML Model Stream. + +--*/ + +#ifndef __NMR_MODELREADERNODE100_TRIANGLE +#define __NMR_MODELREADERNODE100_TRIANGLE + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelObject.h" + +namespace NMR { + + class CModelReaderNode100_Triangle : public CModelReaderNode { + protected: + nfInt32 m_nPropertyID; + nfInt32 m_nPropertyIndex1; + nfInt32 m_nPropertyIndex2; + nfInt32 m_nPropertyIndex3; + nfInt32 m_nIndex1; + nfInt32 m_nIndex2; + nfInt32 m_nIndex3; + + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + public: + CModelReaderNode100_Triangle() = delete; + CModelReaderNode100_Triangle(_In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + void retrieveIndices(_Out_ nfInt32 & nIndex1, _Out_ nfInt32 & nIndex2, _Out_ nfInt32 & nIndex3, nfInt32 nNodeCount); + nfBool retrieveProperties(_Inout_ ModelResourceID & nPropertyID, _Inout_ ModelResourceIndex & nPropertyIndex1, _Inout_ ModelResourceIndex & nPropertyIndex2, _Inout_ ModelResourceIndex & nPropertyIndex3); + }; + + typedef std::shared_ptr PModelReaderNode100_Triangle; + +} + +#endif // __NMR_MODELREADERNODE100_TRIANGLE diff --git a/Include/Model/Reader/v100/NMR_ModelReaderNode100_Triangles.h b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Triangles.h new file mode 100644 index 0000000..b6ba9f4 --- /dev/null +++ b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Triangles.h @@ -0,0 +1,71 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_Triangles.h defines the Model Reader Triangles Node Class. +A triangles reader model node is a parser for the triangles node of an XML Model Stream. + +--*/ + +#ifndef __NMR_MODELREADERNODE100_TRIANGLES +#define __NMR_MODELREADERNODE100_TRIANGLES + +#include "Common/MeshInformation/NMR_MeshInformation_Properties.h" +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Reader/NMR_ModelReader_TexCoordMapping.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelObject.h" + +namespace NMR { + + class CModelReaderNode100_Triangles : public CModelReaderNode { + protected: + CMesh * m_pMesh; + CModel * m_pModel; + + PPackageResourceID m_pObjectLevelPropertyID; + ModelResourceIndex m_nDefaultResourceIndex; + ModelResourceID m_nUsedResourceID; + + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + + _Ret_notnull_ CMeshInformation_Properties * createPropertiesInformation(); + public: + CModelReaderNode100_Triangles() = delete; + CModelReaderNode100_Triangles(_In_ CModel * pModel, _In_ CMesh * pMesh, _In_ PModelWarnings pWarnings, + _In_ PPackageResourceID pObjectLevelPropertyID, _In_ ModelResourceIndex nDefaultPropertyIndex); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + ModelResourceID getUsedPropertyID() const; + }; + + typedef std::shared_ptr PModelReaderNode100_Triangles; + +} + +#endif // __NMR_MODELREADERNODE100_TRIANGLES diff --git a/Include/Model/Reader/v100/NMR_ModelReaderNode100_Vertex.h b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Vertex.h new file mode 100644 index 0000000..34c02f4 --- /dev/null +++ b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Vertex.h @@ -0,0 +1,66 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_Vertex.h defines the Model Reader Vertex Node Class. +A vertex reader model node is a parser for the vertex node of an XML Model Stream. + +--*/ + +#ifndef __NMR_MODELREADERNODE100_VERTEX +#define __NMR_MODELREADERNODE100_VERTEX + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelObject.h" + +namespace NMR { + + class CModelReaderNode100_Vertex : public CModelReaderNode { + private: + nfFloat m_fX; + nfFloat m_fY; + nfFloat m_fZ; + nfBool m_bHasX; + nfBool m_bHasY; + nfBool m_bHasZ; + public: + CModelReaderNode100_Vertex() = delete; + CModelReaderNode100_Vertex(_In_ PModelWarnings pWarnings); + + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + + void retrievePosition(_Out_ nfFloat & fX, _Out_ nfFloat & fY, _Out_ nfFloat & fZ); + }; + + typedef std::shared_ptr PModelReaderNode100_Vertex; + +} + +#endif // __NMR_MODELREADERNODE100_VERTEX diff --git a/Include/Model/Reader/v100/NMR_ModelReaderNode100_Vertices.h b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Vertices.h new file mode 100644 index 0000000..2750074 --- /dev/null +++ b/Include/Model/Reader/v100/NMR_ModelReaderNode100_Vertices.h @@ -0,0 +1,60 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_Vertices.h defines the Model Reader Vertices Node Class. +A vertices reader model node is a parser for the vertices node of an XML Model Stream. + +--*/ + +#ifndef __NMR_MODELREADERNODE100_VERTICES +#define __NMR_MODELREADERNODE100_VERTICES + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelComponent.h" +#include "Model/Classes/NMR_ModelObject.h" + +namespace NMR { + + class CModelReaderNode100_Vertices : public CModelReaderNode { + private: + CMesh * m_pMesh; + protected: + virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); + public: + CModelReaderNode100_Vertices() = delete; + CModelReaderNode100_Vertices(_In_ CMesh * pMesh, _In_ PModelWarnings pWarnings); + + virtual void parseXML(_In_ CXmlReader * pXMLReader); + }; + + typedef std::shared_ptr PModelReaderNode100_Vertices; + +} + +#endif // __NMR_MODELREADERNODE100_VERTICES diff --git a/Include/Model/Writer/NMR_KeyStoreOpcPackageWriter.h b/Include/Model/Writer/NMR_KeyStoreOpcPackageWriter.h new file mode 100644 index 0000000..83a50e9 --- /dev/null +++ b/Include/Model/Writer/NMR_KeyStoreOpcPackageWriter.h @@ -0,0 +1,81 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_KeyStoreOpcPackageWriter.h defines an OPC Package writer in a portable way. + +--*/ + +#ifndef NMR_KEYSTOREOPCPACKAGEWRITER +#define NMR_KEYSTOREOPCPACKAGEWRITER + +#include + +#include "Common/OPC/NMR_IOpcPackageWriter.h" +#include "Common/Platform/NMR_ExportStream.h" + +namespace NMR { + + class CModelContext; + class CKeyStoreResourceData; + class CKeyStoreAccessRight; + class CXmlWriter; + + using PKeyStoreResourceData = std::shared_ptr; + using PKeyStoreAccessRight = std::shared_ptr; + + class CKeyStoreOpcPackageWriter : public IOpcPackageWriter { + private: + bool pathIsEncrypted(_In_ std::string sPath); + protected: + CModelContext const & m_pContext; + PIOpcPackageWriter m_pPackageWriter; + + void writeKeyStoreStream(_In_ CXmlWriter * pXMLWriter); + void refreshAllResourceDataGroups(); + POpcPackagePart wrapPartStream(PKeyStoreResourceData rd, POpcPackagePart part); + void refreshResourceDataTag(PKeyStoreResourceData rd); + void refreshAccessRight(PKeyStoreAccessRight ar, std::vector const & key); + public: + CKeyStoreOpcPackageWriter( + _In_ PExportStream pImportStream, + _In_ CModelContext const & context); + + POpcPackagePart addPart(_In_ std::string sPath) override; + void close() override; + void addContentType(std::string sExtension, std::string sContentType) override; + void addContentType(_In_ POpcPackagePart pOpcPackagePart, _In_ std::string sContentType) override; + POpcPackageRelationship addRootRelationship(std::string sType, COpcPackagePart * pTargetPart) override; + POpcPackageRelationship addPartRelationship(_In_ POpcPackagePart pOpcPackagePart, _In_ std::string sType, _In_ COpcPackagePart * pTargetPart) override; + std::list addWriterSpecificRelationships(_In_ POpcPackagePart pOpcPackagePart, _In_ COpcPackagePart* pTargetPart) override; + }; + + using PKeyStoreOpcPackageWriter = std::shared_ptr; + +} + +#endif // !NMR_KEYSTOREOPCPACKAGEWRITER diff --git a/Include/Model/Writer/NMR_ModelWriter.h b/Include/Model/Writer/NMR_ModelWriter.h new file mode 100644 index 0000000..295d2ee --- /dev/null +++ b/Include/Model/Writer/NMR_ModelWriter.h @@ -0,0 +1,63 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelWriter.h defines the Model Writer Class. +A model writer exports the in memory represenation into the 3MF file. + +--*/ + +#ifndef __NMR_MODELWRITER +#define __NMR_MODELWRITER + +#include "Model/Classes/NMR_Model.h" +#include "Model/Classes/NMR_ModelContext.h" +#include "Common/Platform/NMR_ExportStream.h" +#include "Common/3MF_ProgressMonitor.h" +#include + +namespace NMR { + + class CModelWriter : public CModelContext{ + private: + nfUint32 m_nDecimalPrecision; + public: + CModelWriter() = delete; + CModelWriter(_In_ PModel pModel); + virtual ~CModelWriter() = default; + + virtual void exportToStream(_In_ PExportStream pStream) = 0; + + void SetDecimalPrecision(nfUint32); + nfUint32 GetDecimalPrecision(); + }; + + typedef std::shared_ptr PModelWriter; + +} + +#endif // __NMR_MODELWRITER diff --git a/Include/Model/Writer/NMR_ModelWriterNode.h b/Include/Model/Writer/NMR_ModelWriterNode.h new file mode 100644 index 0000000..0a3caee --- /dev/null +++ b/Include/Model/Writer/NMR_ModelWriterNode.h @@ -0,0 +1,72 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelWriterNode.h defines the Model Writer Node Class. +This is the abstract base class for all 3MF model stream exporters. + +--*/ + +#ifndef __NMR_MODELWRITERNODE +#define __NMR_MODELWRITERNODE + +#include "Common/Platform/NMR_XmlWriter.h" +#include "Common/3MF_ProgressMonitor.h" + +namespace NMR { + + class CModelWriterNode { + protected: + CXmlWriter * m_pXMLWriter; + PProgressMonitor m_pProgressMonitor; + + void writeStringAttribute(_In_z_ const nfChar * pAttributeName, _In_ std::string sAttributeValue); + void writePrefixedStringAttribute(_In_z_ const nfChar * pPrefix, _In_ const nfChar * pAttributeName, std::string sAttributeValue); + + void writeConstStringAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + void writeConstPrefixedStringAttribute(_In_z_ const nfChar * pPrefix, _In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); + + void writeIntAttribute(_In_z_ const nfChar * pAttributeName, _In_ nfInt32 nAttributeValue); + void writeUintAttribute(_In_z_ const nfChar * pAttributeName, _In_ nfUint32 nAttributeValue); + void writeFloatAttribute(_In_z_ const nfChar * pAttributeName, _In_ nfFloat fAttributeValue); + + void writeStartElement(_In_z_ const nfChar * pElementName); + void writeStartElementWithNamespace(_In_z_ const nfChar * pElementName, _In_z_ const nfChar * pNameSpace); + void writeStartElementWithPrefix(_In_z_ const nfChar * pElementName, _In_z_ const nfChar * pPrefix); + void writeEndElement(); + void writeFullEndElement(); + void writeText(_In_z_ const nfChar * pwszText, _In_ nfUint32 cbLength); + public: + CModelWriterNode() = delete; + CModelWriterNode(_In_ CXmlWriter * pXMLWriter, _In_ PProgressMonitor pProgressMonitor); + + virtual void writeToXML () = 0; + }; + +} + +#endif // __NMR_MODELWRITERNODE diff --git a/Include/Model/Writer/NMR_ModelWriterNode_KeyStoreBase.h b/Include/Model/Writer/NMR_ModelWriterNode_KeyStoreBase.h new file mode 100644 index 0000000..69b4010 --- /dev/null +++ b/Include/Model/Writer/NMR_ModelWriterNode_KeyStoreBase.h @@ -0,0 +1,55 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelWriterNode_KeyStoreBase.h defines the base class for all Model Writer Node classes that are related to . + +--*/ + +#ifndef __NMR_MODELWRITERNODE_KEYSTOREBASE +#define __NMR_MODELWRITERNODE_KEYSTOREBASE + +#include "Common/Platform/NMR_XmlWriter.h" +#include "Common/3MF_ProgressMonitor.h" +#include "Model/Classes/NMR_KeyStore.h" +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Writer/NMR_ModelWriterNode.h" + +namespace NMR { + + class CModelWriterNode_KeyStoreBase : public CModelWriterNode { + protected: + PKeyStore m_pKeyStore; + + public: + CModelWriterNode_KeyStoreBase() = delete; + CModelWriterNode_KeyStoreBase(_In_ CXmlWriter * pXMLWriter, _In_ PProgressMonitor pProgressMonitor, _In_ PKeyStore pKeyStore); + }; + +} + +#endif // __NMR_MODELWRITERNODE_KEYSTOREBASE \ No newline at end of file diff --git a/Include/Model/Writer/NMR_ModelWriterNode_ModelBase.h b/Include/Model/Writer/NMR_ModelWriterNode_ModelBase.h new file mode 100644 index 0000000..a3b03d7 --- /dev/null +++ b/Include/Model/Writer/NMR_ModelWriterNode_ModelBase.h @@ -0,0 +1,57 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelWriterNode_ModelBase.h defines the Base class for all Model Writer Node classes that are related to . +This is the abstract base class for all 3MF model stream exporters. + +--*/ + +#ifndef __NMR_MODELWRITERNODE_MODELBASE +#define __NMR_MODELWRITERNODE_MODELBASE + +#include "Common/Platform/NMR_XmlWriter.h" +#include "Common/3MF_ProgressMonitor.h" +#include "Model/Classes/NMR_Model.h" +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Writer/NMR_ModelWriterNode.h" + +namespace NMR { + + class CModelWriterNode_ModelBase : public CModelWriterNode { + protected: + CModel * m_pModel; + + void assertResourceIsInCurrentPath(PPackageResourceID pID); + public: + CModelWriterNode_ModelBase() = delete; + CModelWriterNode_ModelBase(_In_ CModel * pModel, _In_ CXmlWriter * pXMLWriter, _In_ PProgressMonitor pProgressMonitor); + }; + +} + +#endif // __NMR_MODELWRITERNODE_MODELBASE \ No newline at end of file diff --git a/Include/Model/Writer/NMR_ModelWriter_3MF.h b/Include/Model/Writer/NMR_ModelWriter_3MF.h new file mode 100644 index 0000000..7c6e8a9 --- /dev/null +++ b/Include/Model/Writer/NMR_ModelWriter_3MF.h @@ -0,0 +1,64 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelWriter_3MF.h defines the 3MF Model Writer Class. +A model writer exports the in memory represenation into a 3MF file. + +--*/ + +#ifndef __NMR_MODELWRITER_3MF +#define __NMR_MODELWRITER_3MF + +#include "Model/Classes/NMR_KeyStore.h" +#include "Model/Writer/NMR_ModelWriter.h" +#include "Common/Platform/NMR_XmlWriter.h" + +namespace NMR { + + class CModelWriter_3MF : public CModelWriter { + protected: + // Creates a model stream + void writeModelStream(_In_ CXmlWriter * pXMLWriter, _In_ CModel * pModel); + + // Creates a slicestack attachment stream + void writeNonRootModelStream(_In_ CXmlWriter *pXMLWriter); + + // These are OPC dependent functions + virtual void createPackage(_In_ CModel * pModel) = 0; + virtual void writePackageToStream(_In_ PExportStream pStream) = 0; + virtual void releasePackage() = 0; + public: + CModelWriter_3MF() = delete; + CModelWriter_3MF(_In_ PModel pModel); + + virtual void exportToStream(_In_ PExportStream pStream); + }; + +} + +#endif // __NMR_MODELWRITER_3MF diff --git a/Include/Model/Writer/NMR_ModelWriter_3MF_Native.h b/Include/Model/Writer/NMR_ModelWriter_3MF_Native.h new file mode 100644 index 0000000..77a2953 --- /dev/null +++ b/Include/Model/Writer/NMR_ModelWriter_3MF_Native.h @@ -0,0 +1,67 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelWriter_3MF_Native.h defines the platform independent 3MF Model Writer Class. +This model writer exports the in memory represenation into a 3MF file, +using LibZ and a native XML writer implementation. + +--*/ + +#ifndef __NMR_MODELWRITER_3MF_NATIVE +#define __NMR_MODELWRITER_3MF_NATIVE + +#include "Common/OPC/NMR_OpcPackageWriter.h" +#include "Model/Writer/NMR_ModelWriter_3MF.h" +#include "Model/Writer/NMR_KeyStoreOpcPackageWriter.h" + +#define MODELWRITER_NATIVE_BUFFERSIZE 65536 + +namespace NMR { + + class CModelWriter_3MF_Native : public CModelWriter_3MF { + protected: + std::shared_ptr m_pPackageWriter; + CModel * m_pOtherModel; + + // These are OPC dependent functions + virtual void createPackage(_In_ CModel * pModel); + virtual void writePackageToStream(_In_ PExportStream pStream); + virtual void releasePackage(); + + void addAttachments(_In_ CModel * pModel, _In_ POpcPackagePart pModelPart); + + void addNonRootModels(); + + public: + CModelWriter_3MF_Native() = delete; + CModelWriter_3MF_Native(_In_ PModel pModel); + }; + +} + +#endif // __NMR_MODELWRITER_3MF_NATIVE diff --git a/Include/Model/Writer/NMR_ModelWriter_ColorMapping.h b/Include/Model/Writer/NMR_ModelWriter_ColorMapping.h new file mode 100644 index 0000000..212c886 --- /dev/null +++ b/Include/Model/Writer/NMR_ModelWriter_ColorMapping.h @@ -0,0 +1,71 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelWriter.h defines the Model Writer Class. +A model writer exports the in memory represenation into the 3MF file. + +--*/ + +#ifndef __NMR_MODELWRITER_COLORMAPPING +#define __NMR_MODELWRITER_COLORMAPPING + +#include "Model/Classes/NMR_ModelTypes.h" +#include "Common/NMR_Types.h" +#include "Common/NMR_PagedVector.h" + +#include +#include + +namespace NMR { + + class CModelWriter_ColorMapping { + private: + protected: + ModelResourceIndex m_nCurrentIndex; + std::map m_IndexMap; + std::vector m_ColorVector; + ModelResourceID m_ResourceID; + + public: + CModelWriter_ColorMapping() = delete; + CModelWriter_ColorMapping(_In_ ModelResourceID ResourceID); + + void registerColor(_In_ nfColor cColor); + nfBool findColor(_In_ nfColor cColor, _Out_ ModelResourceIndex & nResourceIndex); + + nfUint32 getCount(); + nfColor getColor(_In_ nfUint32 nIndex); + + ModelResourceID getResourceID(); + }; + + typedef std::shared_ptr PModelWriter_ColorMapping; + +} + +#endif // __NMR_MODELWRITER diff --git a/Include/Model/Writer/NMR_ModelWriter_STL.h b/Include/Model/Writer/NMR_ModelWriter_STL.h new file mode 100644 index 0000000..b54273b --- /dev/null +++ b/Include/Model/Writer/NMR_ModelWriter_STL.h @@ -0,0 +1,52 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelWriter_STL.h defines the Native Model Writer Class. +A model writer exports the in memory represenation into a binary STL file. + +--*/ + +#ifndef __NMR_MODELWRITER_STL +#define __NMR_MODELWRITER_STL + +#include "Model/Writer/NMR_ModelWriter.h" + +namespace NMR { + + class CModelWriter_STL : public CModelWriter { + protected: + public: + CModelWriter_STL() = delete; + CModelWriter_STL(_In_ PModel pModel); + + virtual void exportToStream(_In_ PExportStream pStream); + }; + +} + +#endif // __NMR_MODELWRITER_STL diff --git a/Include/Model/Writer/NMR_ModelWriter_TexCoordMapping.h b/Include/Model/Writer/NMR_ModelWriter_TexCoordMapping.h new file mode 100644 index 0000000..13c7c8d --- /dev/null +++ b/Include/Model/Writer/NMR_ModelWriter_TexCoordMapping.h @@ -0,0 +1,80 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelWriter.h defines the Model Writer Class. +A model writer exports the in memory represenation into the 3MF file. + +--*/ + +#ifndef __NMR_MODELWRITER_TEXCOORDMAPPING +#define __NMR_MODELWRITER_TEXCOORDMAPPING + +#include "Model/Classes/NMR_ModelTypes.h" +#include "Common/NMR_Types.h" +#include "Common/NMR_Local.h" + +#include +#include +#include + +namespace NMR { + + typedef struct { + nfFloat m_fU; + nfFloat m_fV; + } WRITERTEXCOORDMAPPINGTREEENTRY; + + bool operator< (_In_ const WRITERTEXCOORDMAPPINGTREEENTRY & entry1, _In_ const WRITERTEXCOORDMAPPINGTREEENTRY & entry2); + + class CModelWriter_TexCoordMapping { + private: + ModelResourceIndex m_nCurrentIndex; + std::map m_IndexMap; + std::vector m_TexCoordVector; + ModelResourceID m_ResourceID; + ModelResourceID m_TextureID; + + public: + CModelWriter_TexCoordMapping() = delete; + CModelWriter_TexCoordMapping(_In_ ModelResourceID ResourceID, _In_ ModelResourceID TextureID); + + void registerTexCoords(_In_ nfFloat fU, _In_ nfFloat fV); + nfBool findTexCoords(_In_ nfFloat fU, _In_ nfFloat fV, _Out_ ModelResourceIndex & nResourceIndex); + + ModelResourceID getResourceID(); + ModelResourceID getTextureID(); + + nfUint32 getCount(); + void getTexCoords(_In_ nfUint32 nIndex, _Out_ nfFloat & fU, _Out_ nfFloat & fV); + }; + + typedef std::shared_ptr PModelWriter_TexCoordMapping; + +} + +#endif // __NMR_MODELWRITER_TEXCOORDMAPPING diff --git a/Include/Model/Writer/NMR_ModelWriter_TexCoordMappingContainer.h b/Include/Model/Writer/NMR_ModelWriter_TexCoordMappingContainer.h new file mode 100644 index 0000000..4b9f33f --- /dev/null +++ b/Include/Model/Writer/NMR_ModelWriter_TexCoordMappingContainer.h @@ -0,0 +1,67 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +Model Writer TexCoordMapping Container + +--*/ + +#ifndef __NMR_MODELWRITER_TEXCOORDMAPPINGCONTAINER +#define __NMR_MODELWRITER_TEXCOORDMAPPINGCONTAINER + +#include "Model/Writer/NMR_ModelWriter_TexCoordMapping.h" +#include "Common/NMR_Types.h" +#include "Common/NMR_Local.h" + +#include +#include +#include + +namespace NMR { + + class CModelWriter_TexCoordMappingContainer { + private: + std::map m_TextureMappings; + std::vector m_TextureMappingVector; + public: + CModelWriter_TexCoordMappingContainer(); + ~CModelWriter_TexCoordMappingContainer(); + + nfBool hasTexture(_In_ ModelResourceID nTextureID); + PModelWriter_TexCoordMapping findTexture(_In_ ModelResourceID nTextureID); + PModelWriter_TexCoordMapping addTexture(_In_ ModelResourceID nTextureID, _In_ ModelResourceID nResourceID); + + nfUint32 getCount(); + PModelWriter_TexCoordMapping getMapping(_In_ nfUint32 nIndex); + + }; + + typedef std::shared_ptr PModelWriter_TexCoordMappingContainer; + +} + +#endif // __NMR_MODELWRITER_TEXCOORDMAPPINGCONTAINER diff --git a/Include/Model/Writer/SecureContent101/NMR_ModelWriterNode_KeyStore.h b/Include/Model/Writer/SecureContent101/NMR_ModelWriterNode_KeyStore.h new file mode 100644 index 0000000..85c5a9e --- /dev/null +++ b/Include/Model/Writer/SecureContent101/NMR_ModelWriterNode_KeyStore.h @@ -0,0 +1,66 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelWriterNode_KeyStore.h defines the Model Writer KeyStore Node Class. +This is the class for exporting the 3mf keystore stream root node. + +--*/ + +#ifndef __NMR_MODELWRITERNODE_KEYSTORE +#define __NMR_MODELWRITERNODE_KEYSTORE + +#include "Model/Classes/NMR_KeyStore.h" +#include "Model/Writer/NMR_ModelWriterNode_KeyStoreBase.h" + +namespace NMR { + + class CModelWriterNode_KeyStore : public CModelWriterNode_KeyStoreBase { + private: + std::map m_consumerIndexes; + protected: + void writeWrapAlgorithmAttribute(eKeyStoreWrapAlgorithm ea); + void writeMgf(eKeyStoreMaskGenerationFunction mgf); + void writeDigest(eKeyStoreMessageDigest md); + void writeEncryptionAlgorithmAttribute(eKeyStoreEncryptAlgorithm ea); + void writeConsumers(); + void writeResourceDatagroup(); + void writeAccessRight(PKeyStoreAccessRight const & ar); + void writeResourceData(PKeyStoreResourceData const & rd); + public: + using CModelWriterNode_KeyStoreBase::CModelWriterNode_KeyStoreBase; + CModelWriterNode_KeyStore() = delete; + + CModelWriterNode_KeyStore(_In_ CXmlWriter * pXMLWriter, _In_ PProgressMonitor pProgressMonitor, _In_ PKeyStore pKeyStore): + CModelWriterNode_KeyStoreBase( pXMLWriter, pProgressMonitor, pKeyStore){}; + + virtual void writeToXML(); + }; + +} + +#endif // __NMR_MODELWRITERNODE_KEYSTORE diff --git a/Include/Model/Writer/v100/NMR_ModelWriterNode100_Mesh.h b/Include/Model/Writer/v100/NMR_ModelWriterNode100_Mesh.h new file mode 100644 index 0000000..6a6954b --- /dev/null +++ b/Include/Model/Writer/v100/NMR_ModelWriterNode100_Mesh.h @@ -0,0 +1,129 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelWriterNode_Mesh.h defines the Model Writer Mesh Node Class. +This is the class for exporting the 3mf mesh node. + +--*/ + +#ifndef __NMR_MODELWRITERNODE100_MESH +#define __NMR_MODELWRITERNODE100_MESH + +#include "Model/Writer/NMR_ModelWriterNode_ModelBase.h" +#include "Model/Classes/NMR_ModelObject.h" +#include "Model/Classes/NMR_ModelMeshObject.h" + +#include "Common/MeshInformation/NMR_MeshInformation_Properties.h" + +#include "Common/Platform/NMR_XmlWriter.h" +#include + +#define MODELWRITERMESH100_LINEBUFFERSIZE 1024 +#define MODELWRITERMESH100_VERTEXLINESTART " m_VertexLine; + std::array m_TriangleLine; + std::array m_BeamLine; + std::array m_BallLine; + std::array m_BeamRefLine; + std::array m_BallRefLine; + nfUint32 m_nVertexBufferPos; + nfUint32 m_nTriangleBufferPos; + nfUint32 m_nBeamBufferPos; + nfUint32 m_nBallBufferPos; + nfUint32 m_nBeamRefBufferPos; + nfUint32 m_nBallRefBufferPos; + private: + const int m_nPosAfterDecPoint; + const int m_nPutDoubleFactor; + __NMR_INLINE void putFloat(_In_ const nfFloat fValue, _In_ std::array & line, _In_ nfUint32 & nBufferPos); + __NMR_INLINE void putDouble(_In_ const nfDouble dValue, _In_ std::array & line, _In_ nfUint32 & nBufferPos); + + protected: + __NMR_INLINE void putVertexString(_In_ const nfChar * pszString); + __NMR_INLINE void putVertexFloat(_In_ const nfFloat fValue); + + __NMR_INLINE void putTriangleString(_In_ const nfChar * pszString); + __NMR_INLINE void putTriangleUInt32(_In_ const nfUint32 nValue); + + __NMR_INLINE void putBeamString(_In_ const nfChar * pszString); + __NMR_INLINE void putBeamUInt32(_In_ const nfUint32 nValue); + __NMR_INLINE void putBeamDouble(_In_ const nfDouble dValue); + + __NMR_INLINE void putBallString(_In_ const nfChar * pszString); + __NMR_INLINE void putBallUInt32(_In_ const nfUint32 nValue); + __NMR_INLINE void putBallDouble(_In_ const nfDouble dValue); + + __NMR_INLINE void putBeamRefString(_In_ const nfChar * pszString); + __NMR_INLINE void putBeamRefUInt32(_In_ const nfUint32 nValue); + + __NMR_INLINE void putBallRefString(_In_ const nfChar * pszString); + __NMR_INLINE void putBallRefUInt32(_In_ const nfUint32 nValue); + + __NMR_INLINE void writeVertexData(_In_ MESHNODE * pNode); + __NMR_INLINE void writeFaceData_Plain(_In_ MESHFACE * pFace, _In_opt_ const nfChar * pszAdditionalString); + __NMR_INLINE void writeFaceData_OneProperty(_In_ MESHFACE * pFace, _In_ const ModelResourceID nPropertyID, _In_ const ModelResourceIndex nPropertyIndex, _In_opt_ const nfChar * pszAdditionalString); + __NMR_INLINE void writeFaceData_ThreeProperties(_In_ MESHFACE * pFace, _In_ const ModelResourceID nPropertyID, _In_ const ModelResourceIndex nPropertyIndex1, _In_ const ModelResourceIndex nPropertyIndex2, _In_ const ModelResourceIndex nPropertyIndex3, _In_opt_ const nfChar * pszAdditionalString); + __NMR_INLINE void writeBeamData(_In_ MESHBEAM * pBeam, _In_ nfDouble dRadius, _In_ eModelBeamLatticeCapMode eDefaultCapMode); + __NMR_INLINE void writeBallData(_In_ MESHBALL * pBall, _In_ eModelBeamLatticeBallMode eBallMode, _In_ nfDouble dRadius); + __NMR_INLINE void writeRefData(_In_ INT nRefID); + __NMR_INLINE void writeBallRefData(_In_ INT nRefID); + public: + CModelWriterNode100_Mesh() = delete; + CModelWriterNode100_Mesh(_In_ CModelMeshObject * pModelMeshObject, _In_ CXmlWriter * pXMLWriter, _In_ PProgressMonitor pProgressMonitor, + _In_ PMeshInformation_PropertyIndexMapping pPropertyIndexMapping, _In_ int nPosAfterDecPoint, _In_ nfBool bWriteMaterialExtension, _In_ nfBool m_bWriteBeamLatticeExtension); + virtual void writeToXML(); + }; + +} + +#endif // __NMR_MODELWRITERNODE100_MESH diff --git a/Include/Model/Writer/v100/NMR_ModelWriterNode100_Model.h b/Include/Model/Writer/v100/NMR_ModelWriterNode100_Model.h new file mode 100644 index 0000000..6ed375b --- /dev/null +++ b/Include/Model/Writer/v100/NMR_ModelWriterNode100_Model.h @@ -0,0 +1,100 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelWriterNode_Model.h defines the Model Writer Model Node Class. +This is the class for exporting the 3mf model stream root node. + +--*/ + +#ifndef __NMR_MODELWRITERNODE100_MODEL +#define __NMR_MODELWRITERNODE100_MODEL + +#include "Model/Classes/NMR_Model.h" +#include "Model/Writer/NMR_ModelWriterNode_ModelBase.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Model/Classes/NMR_ModelMeshObject.h" +#include "Common/Platform/NMR_XmlWriter.h" + +#include "Common/MeshInformation/NMR_MeshInformation_Properties.h" + + +namespace NMR { + + class CModelWriterNode100_Model : public CModelWriterNode_ModelBase { + protected: + nfUint32 m_nDecimalPrecision; + + PMeshInformation_PropertyIndexMapping m_pPropertyIndexMapping; + + nfBool m_bWriteMaterialExtension; + nfBool m_bWriteProductionExtension; + nfBool m_bWriteBeamLatticeExtension; + nfBool m_bWriteNurbsExtension; + nfBool m_bWriteSliceExtension; + nfBool m_bWriteSecureContentExtension; + nfBool m_bWriteBaseMaterials; + nfBool m_bWriteObjects; + nfBool m_bIsRootModel; + nfBool m_bWriteCustomNamespaces; + + void writeModelMetaData(); + void writeMetaData(_In_ PModelMetaData pMetaData); + void writeMetaDataGroup(_In_ PModelMetaDataGroup pMetaDataGroup); + + void writeResources(); + void writeBaseMaterials(); + void writeTextures2D(); + void writeColors(); + void writeTex2Coords(); + void writeCompositeMaterials(); + void writeMultiProperties(); + void writeMultiPropertyAttributes(_In_ CModelMultiPropertyGroupResource* pMultiPropertyGroup); + void writeMultiPropertyMultiElements(_In_ CModelMultiPropertyGroupResource* pMultiPropertyGroup); + + void writeObjects(); + void writeBuild(); + + void writeSliceStacks(); + void writeSliceStack(_In_ CModelSliceStack *pSliceStack); + + void writeComponentsObject(_In_ CModelComponentsObject * pComponentsObject); + + void RegisterMetaDataGroupNameSpaces(PModelMetaDataGroup mdg); + void RegisterMetaDataNameSpaces(); + + public: + CModelWriterNode100_Model() = delete; + CModelWriterNode100_Model(_In_ CModel * pModel, _In_ CXmlWriter * pXMLWriter, _In_ PProgressMonitor pProgressMonitor, _In_ nfUint32 nDecimalPrecision); + CModelWriterNode100_Model(_In_ CModel * pModel, _In_ CXmlWriter * pXMLWriter, _In_ PProgressMonitor pProgressMonitor, _In_ nfUint32 nDecimalPrecision, _In_ nfBool bWritesRootModel); + + virtual void writeToXML(); + }; + +} + +#endif // __NMR_MODELWRITERNODE100_MODEL diff --git a/Include/NMR_Spec_Version.h b/Include/NMR_Spec_Version.h new file mode 100644 index 0000000..7d3f75a --- /dev/null +++ b/Include/NMR_Spec_Version.h @@ -0,0 +1,62 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_Spec_Version.h defines the current implementation version. + +--*/ + +#ifndef __NMR_SPECVERSION +#define __NMR_SPECVERSION + +// version of the core-specification implemented by this library +#define NMR_SPECVERSION_MAJOR 1 +#define NMR_SPECVERSION_MINOR 2 +#define NMR_SPECVERSION_MICRO 3 + +// Interface version for extension API +#define NMR_SPECVERSION_MATERIAL_MAJOR 1 +#define NMR_SPECVERSION_MATERIAL_MINOR 1 +#define NMR_SPECVERSION_MATERIAL_MICRO 0 + +#define NMR_SPECVERSION_PRODUCTION_MAJOR 1 +#define NMR_SPECVERSION_PRODUCTION_MINOR 1 +#define NMR_SPECVERSION_PRODUCTION_MICRO 2 + +#define NMR_SPECVERSION_BEAMLATTICE_MAJOR 1 +#define NMR_SPECVERSION_BEAMLATTICE_MINOR 1 +#define NMR_SPECVERSION_BEAMLATTICE_MICRO 0 + +#define NMR_SPECVERSION_SLICE_MAJOR 1 +#define NMR_SPECVERSION_SLICE_MINOR 0 +#define NMR_SPECVERSION_SLICE_MICRO 2 + +#define NMR_SPECVERSION_SECURECONTENT_MAJOR 1 +#define NMR_SPECVERSION_SECURECONTENT_MINOR 0 +#define NMR_SPECVERSION_SECURECONTENT_MICRO 2 + +#endif // __NMR_SPECVERSION diff --git a/Include/lib3mf_abi.hpp b/Include/lib3mf_abi.hpp new file mode 100644 index 0000000..16fece3 --- /dev/null +++ b/Include/lib3mf_abi.hpp @@ -0,0 +1,3711 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +This file has been generated by the Automatic Component Toolkit (ACT) version 1.6.0. + +Abstract: This is an autogenerated C++-Header file in order to allow an easy + use of the 3MF Library + +Interface version: 2.2.0 + +*/ + +#ifndef __LIB3MF_HEADER_CPP +#define __LIB3MF_HEADER_CPP + +#ifdef __LIB3MF_EXPORTS +#ifdef _WIN32 +#define LIB3MF_DECLSPEC __declspec (dllexport) +#else // _WIN32 +#define LIB3MF_DECLSPEC __attribute__((visibility("default"))) +#endif // _WIN32 +#else // __LIB3MF_EXPORTS +#define LIB3MF_DECLSPEC +#endif // __LIB3MF_EXPORTS + +#include "lib3mf_types.hpp" + + +extern "C" { + +/************************************************************************************************************************* + Class definition for Base +**************************************************************************************************************************/ + +/************************************************************************************************************************* + Class definition for Writer +**************************************************************************************************************************/ + +/** +* Writes out the model as file. The file type is specified by the Model Writer class. +* +* @param[in] pWriter - Writer instance. +* @param[in] pFilename - Filename to write into +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_writer_writetofile(Lib3MF_Writer pWriter, const char * pFilename); + +/** +* Retrieves the size of the full 3MF file stream. +* +* @param[in] pWriter - Writer instance. +* @param[out] pStreamSize - the stream size +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_writer_getstreamsize(Lib3MF_Writer pWriter, Lib3MF_uint64 * pStreamSize); + +/** +* Writes out the 3MF file into a memory buffer +* +* @param[in] pWriter - Writer instance. +* @param[in] nBufferBufferSize - Number of elements in buffer +* @param[out] pBufferNeededCount - will be filled with the count of the written elements, or needed buffer size. +* @param[out] pBufferBuffer - uint8 buffer of buffer to write into +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_writer_writetobuffer(Lib3MF_Writer pWriter, const Lib3MF_uint64 nBufferBufferSize, Lib3MF_uint64* pBufferNeededCount, Lib3MF_uint8 * pBufferBuffer); + +/** +* Writes out the model and passes the data to a provided callback function. The file type is specified by the Model Writer class. +* +* @param[in] pWriter - Writer instance. +* @param[in] pTheWriteCallback - Callback to call for writing a data chunk +* @param[in] pTheSeekCallback - Callback to call for seeking in the stream +* @param[in] pUserData - Userdata that is passed to the callback function +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_writer_writetocallback(Lib3MF_Writer pWriter, Lib3MF::WriteCallback pTheWriteCallback, Lib3MF::SeekCallback pTheSeekCallback, Lib3MF_pvoid pUserData); + +/** +* Set the progress callback for calls to this writer +* +* @param[in] pWriter - Writer instance. +* @param[in] pProgressCallback - pointer to the callback function. +* @param[in] pUserData - pointer to arbitrary user data that is passed without modification to the callback. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_writer_setprogresscallback(Lib3MF_Writer pWriter, Lib3MF::ProgressCallback pProgressCallback, Lib3MF_pvoid pUserData); + +/** +* Returns the number of digits after the decimal point to be written in each vertex coordinate-value. +* +* @param[in] pWriter - Writer instance. +* @param[out] pDecimalPrecision - The number of digits to be written in each vertex coordinate-value after the decimal point. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_writer_getdecimalprecision(Lib3MF_Writer pWriter, Lib3MF_uint32 * pDecimalPrecision); + +/** +* Sets the number of digits after the decimal point to be written in each vertex coordinate-value. +* +* @param[in] pWriter - Writer instance. +* @param[in] nDecimalPrecision - The number of digits to be written in each vertex coordinate-value after the decimal point. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_writer_setdecimalprecision(Lib3MF_Writer pWriter, Lib3MF_uint32 nDecimalPrecision); + +/** +* Activates (deactivates) the strict mode of the reader. +* +* @param[in] pWriter - Writer instance. +* @param[in] bStrictModeActive - flag whether strict mode is active or not. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_writer_setstrictmodeactive(Lib3MF_Writer pWriter, bool bStrictModeActive); + +/** +* Queries whether the strict mode of the reader is active or not +* +* @param[in] pWriter - Writer instance. +* @param[out] pStrictModeActive - returns flag whether strict mode is active or not. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_writer_getstrictmodeactive(Lib3MF_Writer pWriter, bool * pStrictModeActive); + +/** +* Returns Warning and Error Information of the read process +* +* @param[in] pWriter - Writer instance. +* @param[in] nIndex - Index of the Warning. Valid values are 0 to WarningCount - 1 +* @param[out] pErrorCode - filled with the error code of the warning +* @param[in] nWarningBufferSize - size of the buffer (including trailing 0) +* @param[out] pWarningNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pWarningBuffer - buffer of the message of the warning, may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_writer_getwarning(Lib3MF_Writer pWriter, Lib3MF_uint32 nIndex, Lib3MF_uint32 * pErrorCode, const Lib3MF_uint32 nWarningBufferSize, Lib3MF_uint32* pWarningNeededChars, char * pWarningBuffer); + +/** +* Returns Warning and Error Count of the read process +* +* @param[in] pWriter - Writer instance. +* @param[out] pCount - filled with the count of the occurred warnings. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_writer_getwarningcount(Lib3MF_Writer pWriter, Lib3MF_uint32 * pCount); + +/** +* Registers a callback to deal with data key encryption/decryption from keystore +* +* @param[in] pWriter - Writer instance. +* @param[in] pConsumerID - The ConsumerID to register for +* @param[in] pTheCallback - The callback to be callede for wrapping and encryption key +* @param[in] pUserData - Userdata that is passed to the callback function +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_writer_addkeywrappingcallback(Lib3MF_Writer pWriter, const char * pConsumerID, Lib3MF::KeyWrappingCallback pTheCallback, Lib3MF_pvoid pUserData); + +/** +* Registers a callback to deal with encryption of content +* +* @param[in] pWriter - Writer instance. +* @param[in] pTheCallback - The callback used to encrypt content +* @param[in] pUserData - Userdata that is passed to the callback function +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_writer_setcontentencryptioncallback(Lib3MF_Writer pWriter, Lib3MF::ContentEncryptionCallback pTheCallback, Lib3MF_pvoid pUserData); + +/************************************************************************************************************************* + Class definition for Reader +**************************************************************************************************************************/ + +/** +* Reads a model from a file. The file type is specified by the Model Reader class +* +* @param[in] pReader - Reader instance. +* @param[in] pFilename - Filename to read from +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_reader_readfromfile(Lib3MF_Reader pReader, const char * pFilename); + +/** +* Reads a model from a memory buffer. +* +* @param[in] pReader - Reader instance. +* @param[in] nBufferBufferSize - Number of elements in buffer +* @param[in] pBufferBuffer - uint8 buffer of Buffer to read from +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_reader_readfrombuffer(Lib3MF_Reader pReader, Lib3MF_uint64 nBufferBufferSize, const Lib3MF_uint8 * pBufferBuffer); + +/** +* Reads a model and from the data provided by a callback function +* +* @param[in] pReader - Reader instance. +* @param[in] pTheReadCallback - Callback to call for reading a data chunk +* @param[in] nStreamSize - number of bytes the callback returns +* @param[in] pTheSeekCallback - Callback to call for seeking in the stream. +* @param[in] pUserData - Userdata that is passed to the callback function +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_reader_readfromcallback(Lib3MF_Reader pReader, Lib3MF::ReadCallback pTheReadCallback, Lib3MF_uint64 nStreamSize, Lib3MF::SeekCallback pTheSeekCallback, Lib3MF_pvoid pUserData); + +/** +* Set the progress callback for calls to this writer +* +* @param[in] pReader - Reader instance. +* @param[in] pProgressCallback - pointer to the callback function. +* @param[in] pUserData - pointer to arbitrary user data that is passed without modification to the callback. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_reader_setprogresscallback(Lib3MF_Reader pReader, Lib3MF::ProgressCallback pProgressCallback, Lib3MF_pvoid pUserData); + +/** +* Adds a relationship type which shall be read as attachment in memory while loading +* +* @param[in] pReader - Reader instance. +* @param[in] pRelationShipType - String of the relationship type +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_reader_addrelationtoread(Lib3MF_Reader pReader, const char * pRelationShipType); + +/** +* Removes a relationship type which shall be read as attachment in memory while loading +* +* @param[in] pReader - Reader instance. +* @param[in] pRelationShipType - String of the relationship type +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_reader_removerelationtoread(Lib3MF_Reader pReader, const char * pRelationShipType); + +/** +* Activates (deactivates) the strict mode of the reader. +* +* @param[in] pReader - Reader instance. +* @param[in] bStrictModeActive - flag whether strict mode is active or not. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_reader_setstrictmodeactive(Lib3MF_Reader pReader, bool bStrictModeActive); + +/** +* Queries whether the strict mode of the reader is active or not +* +* @param[in] pReader - Reader instance. +* @param[out] pStrictModeActive - returns flag whether strict mode is active or not. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_reader_getstrictmodeactive(Lib3MF_Reader pReader, bool * pStrictModeActive); + +/** +* Returns Warning and Error Information of the read process +* +* @param[in] pReader - Reader instance. +* @param[in] nIndex - Index of the Warning. Valid values are 0 to WarningCount - 1 +* @param[out] pErrorCode - filled with the error code of the warning +* @param[in] nWarningBufferSize - size of the buffer (including trailing 0) +* @param[out] pWarningNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pWarningBuffer - buffer of the message of the warning, may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_reader_getwarning(Lib3MF_Reader pReader, Lib3MF_uint32 nIndex, Lib3MF_uint32 * pErrorCode, const Lib3MF_uint32 nWarningBufferSize, Lib3MF_uint32* pWarningNeededChars, char * pWarningBuffer); + +/** +* Returns Warning and Error Count of the read process +* +* @param[in] pReader - Reader instance. +* @param[out] pCount - filled with the count of the occurred warnings. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_reader_getwarningcount(Lib3MF_Reader pReader, Lib3MF_uint32 * pCount); + +/** +* Registers a callback to deal with key wrapping mechanism from keystore +* +* @param[in] pReader - Reader instance. +* @param[in] pConsumerID - The ConsumerID to register for +* @param[in] pTheCallback - The callback used to decrypt data key +* @param[in] pUserData - Userdata that is passed to the callback function +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_reader_addkeywrappingcallback(Lib3MF_Reader pReader, const char * pConsumerID, Lib3MF::KeyWrappingCallback pTheCallback, Lib3MF_pvoid pUserData); + +/** +* Registers a callback to deal with encryption of content +* +* @param[in] pReader - Reader instance. +* @param[in] pTheCallback - The callback used to encrypt content +* @param[in] pUserData - Userdata that is passed to the callback function +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_reader_setcontentencryptioncallback(Lib3MF_Reader pReader, Lib3MF::ContentEncryptionCallback pTheCallback, Lib3MF_pvoid pUserData); + +/************************************************************************************************************************* + Class definition for PackagePart +**************************************************************************************************************************/ + +/** +* Returns the absolute path of this PackagePart. +* +* @param[in] pPackagePart - PackagePart instance. +* @param[in] nPathBufferSize - size of the buffer (including trailing 0) +* @param[out] pPathNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pPathBuffer - buffer of Returns the absolute path of this PackagePart, may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_packagepart_getpath(Lib3MF_PackagePart pPackagePart, const Lib3MF_uint32 nPathBufferSize, Lib3MF_uint32* pPathNeededChars, char * pPathBuffer); + +/** +* Sets the absolute path of this PackagePart. +* +* @param[in] pPackagePart - PackagePart instance. +* @param[in] pPath - Sets the absolute path of this PackagePart. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_packagepart_setpath(Lib3MF_PackagePart pPackagePart, const char * pPath); + +/************************************************************************************************************************* + Class definition for Resource +**************************************************************************************************************************/ + +/** +* Retrieves the unique id of this resource within a package. This function will be removed in a later release in favor of GetUniqueResourceID +* +* @param[in] pResource - Resource instance. +* @param[out] pUniqueResourceID - Retrieves the unique id of this resource within a package. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_resource_getresourceid(Lib3MF_Resource pResource, Lib3MF_uint32 * pUniqueResourceID); + +/** +* Retrieves the unique id of this resource within a package. +* +* @param[in] pResource - Resource instance. +* @param[out] pUniqueResourceID - Retrieves the unique id of this resource within a package. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_resource_getuniqueresourceid(Lib3MF_Resource pResource, Lib3MF_uint32 * pUniqueResourceID); + +/** +* Returns the PackagePart within which this resource resides +* +* @param[in] pResource - Resource instance. +* @param[out] pPackagePart - the PackagePart within which this resource resides. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_resource_packagepart(Lib3MF_Resource pResource, Lib3MF_PackagePart * pPackagePart); + +/** +* Sets the new PackagePart within which this resource resides +* +* @param[in] pResource - Resource instance. +* @param[in] pPackagePart - the new PackagePart within which this resource resides. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_resource_setpackagepart(Lib3MF_Resource pResource, Lib3MF_PackagePart pPackagePart); + +/** +* Retrieves the id of this resource within a model. +* +* @param[in] pResource - Resource instance. +* @param[out] pModelResourceId - Retrieves the id of this resource within a model. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_resource_getmodelresourceid(Lib3MF_Resource pResource, Lib3MF_uint32 * pModelResourceId); + +/************************************************************************************************************************* + Class definition for ResourceIterator +**************************************************************************************************************************/ + +/** +* Iterates to the next resource in the list. +* +* @param[in] pResourceIterator - ResourceIterator instance. +* @param[out] pHasNext - Iterates to the next resource in the list. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_resourceiterator_movenext(Lib3MF_ResourceIterator pResourceIterator, bool * pHasNext); + +/** +* Iterates to the previous resource in the list. +* +* @param[in] pResourceIterator - ResourceIterator instance. +* @param[out] pHasPrevious - Iterates to the previous resource in the list. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_resourceiterator_moveprevious(Lib3MF_ResourceIterator pResourceIterator, bool * pHasPrevious); + +/** +* Returns the resource the iterator points at. +* +* @param[in] pResourceIterator - ResourceIterator instance. +* @param[out] pResource - returns the resource instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_resourceiterator_getcurrent(Lib3MF_ResourceIterator pResourceIterator, Lib3MF_Resource * pResource); + +/** +* Creates a new resource iterator with the same resource list. +* +* @param[in] pResourceIterator - ResourceIterator instance. +* @param[out] pOutResourceIterator - returns the cloned Iterator instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_resourceiterator_clone(Lib3MF_ResourceIterator pResourceIterator, Lib3MF_ResourceIterator * pOutResourceIterator); + +/** +* Returns the number of resoucres the iterator captures. +* +* @param[in] pResourceIterator - ResourceIterator instance. +* @param[out] pCount - returns the number of resoucres the iterator captures. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_resourceiterator_count(Lib3MF_ResourceIterator pResourceIterator, Lib3MF_uint64 * pCount); + +/************************************************************************************************************************* + Class definition for SliceStackIterator +**************************************************************************************************************************/ + +/** +* Returns the SliceStack the iterator points at. +* +* @param[in] pSliceStackIterator - SliceStackIterator instance. +* @param[out] pResource - returns the SliceStack instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_slicestackiterator_getcurrentslicestack(Lib3MF_SliceStackIterator pSliceStackIterator, Lib3MF_SliceStack * pResource); + +/************************************************************************************************************************* + Class definition for ObjectIterator +**************************************************************************************************************************/ + +/** +* Returns the Object the iterator points at. +* +* @param[in] pObjectIterator - ObjectIterator instance. +* @param[out] pResource - returns the Object instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_objectiterator_getcurrentobject(Lib3MF_ObjectIterator pObjectIterator, Lib3MF_Object * pResource); + +/************************************************************************************************************************* + Class definition for MeshObjectIterator +**************************************************************************************************************************/ + +/** +* Returns the MeshObject the iterator points at. +* +* @param[in] pMeshObjectIterator - MeshObjectIterator instance. +* @param[out] pResource - returns the MeshObject instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobjectiterator_getcurrentmeshobject(Lib3MF_MeshObjectIterator pMeshObjectIterator, Lib3MF_MeshObject * pResource); + +/************************************************************************************************************************* + Class definition for ComponentsObjectIterator +**************************************************************************************************************************/ + +/** +* Returns the ComponentsObject the iterator points at. +* +* @param[in] pComponentsObjectIterator - ComponentsObjectIterator instance. +* @param[out] pResource - returns the ComponentsObject instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_componentsobjectiterator_getcurrentcomponentsobject(Lib3MF_ComponentsObjectIterator pComponentsObjectIterator, Lib3MF_ComponentsObject * pResource); + +/************************************************************************************************************************* + Class definition for Texture2DIterator +**************************************************************************************************************************/ + +/** +* Returns the Texture2D the iterator points at. +* +* @param[in] pTexture2DIterator - Texture2DIterator instance. +* @param[out] pResource - returns the Texture2D instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2diterator_getcurrenttexture2d(Lib3MF_Texture2DIterator pTexture2DIterator, Lib3MF_Texture2D * pResource); + +/************************************************************************************************************************* + Class definition for BaseMaterialGroupIterator +**************************************************************************************************************************/ + +/** +* Returns the MaterialGroup the iterator points at. +* +* @param[in] pBaseMaterialGroupIterator - BaseMaterialGroupIterator instance. +* @param[out] pResource - returns the BaseMaterialGroup instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_basematerialgroupiterator_getcurrentbasematerialgroup(Lib3MF_BaseMaterialGroupIterator pBaseMaterialGroupIterator, Lib3MF_BaseMaterialGroup * pResource); + +/************************************************************************************************************************* + Class definition for ColorGroupIterator +**************************************************************************************************************************/ + +/** +* Returns the ColorGroup the iterator points at. +* +* @param[in] pColorGroupIterator - ColorGroupIterator instance. +* @param[out] pResource - returns the ColorGroup instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_colorgroupiterator_getcurrentcolorgroup(Lib3MF_ColorGroupIterator pColorGroupIterator, Lib3MF_ColorGroup * pResource); + +/************************************************************************************************************************* + Class definition for Texture2DGroupIterator +**************************************************************************************************************************/ + +/** +* Returns the Texture2DGroup the iterator points at. +* +* @param[in] pTexture2DGroupIterator - Texture2DGroupIterator instance. +* @param[out] pResource - returns the Texture2DGroup instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2dgroupiterator_getcurrenttexture2dgroup(Lib3MF_Texture2DGroupIterator pTexture2DGroupIterator, Lib3MF_Texture2DGroup * pResource); + +/************************************************************************************************************************* + Class definition for CompositeMaterialsIterator +**************************************************************************************************************************/ + +/** +* Returns the CompositeMaterials the iterator points at. +* +* @param[in] pCompositeMaterialsIterator - CompositeMaterialsIterator instance. +* @param[out] pResource - returns the CompositeMaterials instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_compositematerialsiterator_getcurrentcompositematerials(Lib3MF_CompositeMaterialsIterator pCompositeMaterialsIterator, Lib3MF_CompositeMaterials * pResource); + +/************************************************************************************************************************* + Class definition for MultiPropertyGroupIterator +**************************************************************************************************************************/ + +/** +* Returns the MultiPropertyGroup the iterator points at. +* +* @param[in] pMultiPropertyGroupIterator - MultiPropertyGroupIterator instance. +* @param[out] pResource - returns the MultiPropertyGroup instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_multipropertygroupiterator_getcurrentmultipropertygroup(Lib3MF_MultiPropertyGroupIterator pMultiPropertyGroupIterator, Lib3MF_MultiPropertyGroup * pResource); + +/************************************************************************************************************************* + Class definition for MetaData +**************************************************************************************************************************/ + +/** +* returns the namespace URL of the metadata +* +* @param[in] pMetaData - MetaData instance. +* @param[in] nNameSpaceBufferSize - size of the buffer (including trailing 0) +* @param[out] pNameSpaceNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pNameSpaceBuffer - buffer of the namespace URL of the metadata, may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadata_getnamespace(Lib3MF_MetaData pMetaData, const Lib3MF_uint32 nNameSpaceBufferSize, Lib3MF_uint32* pNameSpaceNeededChars, char * pNameSpaceBuffer); + +/** +* sets a new namespace URL of the metadata +* +* @param[in] pMetaData - MetaData instance. +* @param[in] pNameSpace - the new namespace URL of the metadata +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadata_setnamespace(Lib3MF_MetaData pMetaData, const char * pNameSpace); + +/** +* returns the name of a metadata +* +* @param[in] pMetaData - MetaData instance. +* @param[in] nNameBufferSize - size of the buffer (including trailing 0) +* @param[out] pNameNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pNameBuffer - buffer of the name of the metadata, may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadata_getname(Lib3MF_MetaData pMetaData, const Lib3MF_uint32 nNameBufferSize, Lib3MF_uint32* pNameNeededChars, char * pNameBuffer); + +/** +* sets a new name of a metadata +* +* @param[in] pMetaData - MetaData instance. +* @param[in] pName - the new name of the metadata +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadata_setname(Lib3MF_MetaData pMetaData, const char * pName); + +/** +* returns the (namespace+name) of a metadata +* +* @param[in] pMetaData - MetaData instance. +* @param[in] nKeyBufferSize - size of the buffer (including trailing 0) +* @param[out] pKeyNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pKeyBuffer - buffer of the key (namespace+name) of the metadata, may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadata_getkey(Lib3MF_MetaData pMetaData, const Lib3MF_uint32 nKeyBufferSize, Lib3MF_uint32* pKeyNeededChars, char * pKeyBuffer); + +/** +* returns, whether a metadata must be preserved +* +* @param[in] pMetaData - MetaData instance. +* @param[out] pMustPreserve - returns, whether a metadata must be preserved +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadata_getmustpreserve(Lib3MF_MetaData pMetaData, bool * pMustPreserve); + +/** +* sets whether a metadata must be preserved +* +* @param[in] pMetaData - MetaData instance. +* @param[in] bMustPreserve - a new value whether a metadata must be preserved +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadata_setmustpreserve(Lib3MF_MetaData pMetaData, bool bMustPreserve); + +/** +* returns the type of a metadata +* +* @param[in] pMetaData - MetaData instance. +* @param[in] nTypeBufferSize - size of the buffer (including trailing 0) +* @param[out] pTypeNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pTypeBuffer - buffer of the type of the metadata, may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadata_gettype(Lib3MF_MetaData pMetaData, const Lib3MF_uint32 nTypeBufferSize, Lib3MF_uint32* pTypeNeededChars, char * pTypeBuffer); + +/** +* sets a new type of a metadata. This must be a simple XML type +* +* @param[in] pMetaData - MetaData instance. +* @param[in] pType - a new type of the metadata +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadata_settype(Lib3MF_MetaData pMetaData, const char * pType); + +/** +* returns the value of the metadata +* +* @param[in] pMetaData - MetaData instance. +* @param[in] nValueBufferSize - size of the buffer (including trailing 0) +* @param[out] pValueNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pValueBuffer - buffer of the value of the metadata, may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadata_getvalue(Lib3MF_MetaData pMetaData, const Lib3MF_uint32 nValueBufferSize, Lib3MF_uint32* pValueNeededChars, char * pValueBuffer); + +/** +* sets a new value of the metadata +* +* @param[in] pMetaData - MetaData instance. +* @param[in] pValue - a new value of the metadata +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadata_setvalue(Lib3MF_MetaData pMetaData, const char * pValue); + +/************************************************************************************************************************* + Class definition for MetaDataGroup +**************************************************************************************************************************/ + +/** +* returns the number of metadata in this metadatagroup +* +* @param[in] pMetaDataGroup - MetaDataGroup instance. +* @param[out] pCount - returns the number metadata +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadatagroup_getmetadatacount(Lib3MF_MetaDataGroup pMetaDataGroup, Lib3MF_uint32 * pCount); + +/** +* returns a metadata value within this metadatagroup +* +* @param[in] pMetaDataGroup - MetaDataGroup instance. +* @param[in] nIndex - Index of the Metadata. +* @param[out] pMetaData - an instance of the metadata +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadatagroup_getmetadata(Lib3MF_MetaDataGroup pMetaDataGroup, Lib3MF_uint32 nIndex, Lib3MF_MetaData * pMetaData); + +/** +* returns a metadata value within this metadatagroup +* +* @param[in] pMetaDataGroup - MetaDataGroup instance. +* @param[in] pNameSpace - the namespace of the metadata +* @param[in] pName - the name of the Metadata +* @param[out] pMetaData - an instance of the metadata +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadatagroup_getmetadatabykey(Lib3MF_MetaDataGroup pMetaDataGroup, const char * pNameSpace, const char * pName, Lib3MF_MetaData * pMetaData); + +/** +* removes metadata by index from the model. +* +* @param[in] pMetaDataGroup - MetaDataGroup instance. +* @param[in] nIndex - Index of the metadata to remove +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadatagroup_removemetadatabyindex(Lib3MF_MetaDataGroup pMetaDataGroup, Lib3MF_uint32 nIndex); + +/** +* removes metadata from the model. +* +* @param[in] pMetaDataGroup - MetaDataGroup instance. +* @param[in] pTheMetaData - The metadata to remove +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadatagroup_removemetadata(Lib3MF_MetaDataGroup pMetaDataGroup, Lib3MF_MetaData pTheMetaData); + +/** +* adds a new metadata to this metadatagroup +* +* @param[in] pMetaDataGroup - MetaDataGroup instance. +* @param[in] pNameSpace - the namespace of the metadata +* @param[in] pName - the name of the metadata +* @param[in] pValue - the value of the metadata +* @param[in] pType - the type of the metadata +* @param[in] bMustPreserve - shuold the metadata be preserved +* @param[out] pMetaData - a new instance of the metadata +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadatagroup_addmetadata(Lib3MF_MetaDataGroup pMetaDataGroup, const char * pNameSpace, const char * pName, const char * pValue, const char * pType, bool bMustPreserve, Lib3MF_MetaData * pMetaData); + +/************************************************************************************************************************* + Class definition for Object +**************************************************************************************************************************/ + +/** +* Retrieves an object's type +* +* @param[in] pObject - Object instance. +* @param[out] pObjectType - returns object type enum. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_gettype(Lib3MF_Object pObject, Lib3MF::eObjectType * pObjectType); + +/** +* Sets an object's type +* +* @param[in] pObject - Object instance. +* @param[in] eObjectType - object type enum. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_settype(Lib3MF_Object pObject, Lib3MF::eObjectType eObjectType); + +/** +* Retrieves an object's name +* +* @param[in] pObject - Object instance. +* @param[in] nNameBufferSize - size of the buffer (including trailing 0) +* @param[out] pNameNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pNameBuffer - buffer of returns object name., may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_getname(Lib3MF_Object pObject, const Lib3MF_uint32 nNameBufferSize, Lib3MF_uint32* pNameNeededChars, char * pNameBuffer); + +/** +* Sets an object's name string +* +* @param[in] pObject - Object instance. +* @param[in] pName - new object name. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_setname(Lib3MF_Object pObject, const char * pName); + +/** +* Retrieves an object's part number +* +* @param[in] pObject - Object instance. +* @param[in] nPartNumberBufferSize - size of the buffer (including trailing 0) +* @param[out] pPartNumberNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pPartNumberBuffer - buffer of returns object part number., may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_getpartnumber(Lib3MF_Object pObject, const Lib3MF_uint32 nPartNumberBufferSize, Lib3MF_uint32* pPartNumberNeededChars, char * pPartNumberBuffer); + +/** +* Sets an objects partnumber string +* +* @param[in] pObject - Object instance. +* @param[in] pPartNumber - new object part number. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_setpartnumber(Lib3MF_Object pObject, const char * pPartNumber); + +/** +* Retrieves, if an object is a mesh object +* +* @param[in] pObject - Object instance. +* @param[out] pIsMeshObject - returns, whether the object is a mesh object +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_ismeshobject(Lib3MF_Object pObject, bool * pIsMeshObject); + +/** +* Retrieves, if an object is a components object +* +* @param[in] pObject - Object instance. +* @param[out] pIsComponentsObject - returns, whether the object is a components object +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_iscomponentsobject(Lib3MF_Object pObject, bool * pIsComponentsObject); + +/** +* Retrieves, if the object is valid according to the core spec. For mesh objects, we distinguish between the type attribute of the object:In case of object type other, this always means false.In case of object type model or solidsupport, this means, if the mesh suffices all requirements of the core spec chapter 4.1.In case of object type support or surface, this always means true.A component objects is valid if and only if it contains at least one component and all child components are valid objects. +* +* @param[in] pObject - Object instance. +* @param[out] pIsValid - returns whether the object is a valid object description +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_isvalid(Lib3MF_Object pObject, bool * pIsValid); + +/** +* Use an existing attachment as thumbnail for this object +* +* @param[in] pObject - Object instance. +* @param[in] pAttachment - Instance of a new or the existing thumbnailattachment object. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_setattachmentasthumbnail(Lib3MF_Object pObject, Lib3MF_Attachment pAttachment); + +/** +* Get the attachment containing the object thumbnail. +* +* @param[in] pObject - Object instance. +* @param[out] pAttachment - Instance of the thumbnailattachment object or NULL. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_getthumbnailattachment(Lib3MF_Object pObject, Lib3MF_Attachment * pAttachment); + +/** +* Clears the attachment. The attachment instance is not removed from the package. +* +* @param[in] pObject - Object instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_clearthumbnailattachment(Lib3MF_Object pObject); + +/** +* Returns the outbox of a build item +* +* @param[in] pObject - Object instance. +* @param[out] pOutbox - Outbox of this build item +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_getoutbox(Lib3MF_Object pObject, Lib3MF::sBox * pOutbox); + +/** +* Retrieves an object's uuid string (see production extension specification) +* +* @param[in] pObject - Object instance. +* @param[out] pHasUUID - flag whether the build item has a UUID +* @param[in] nUUIDBufferSize - size of the buffer (including trailing 0) +* @param[out] pUUIDNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pUUIDBuffer - buffer of returns object uuid., may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_getuuid(Lib3MF_Object pObject, bool * pHasUUID, const Lib3MF_uint32 nUUIDBufferSize, Lib3MF_uint32* pUUIDNeededChars, char * pUUIDBuffer); + +/** +* Sets a build object's uuid string (see production extension specification) +* +* @param[in] pObject - Object instance. +* @param[in] pUUID - new object uuid string. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_setuuid(Lib3MF_Object pObject, const char * pUUID); + +/** +* Returns the metadatagroup of this object +* +* @param[in] pObject - Object instance. +* @param[out] pMetaDataGroup - returns an Instance of the metadatagroup of this object +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_getmetadatagroup(Lib3MF_Object pObject, Lib3MF_MetaDataGroup * pMetaDataGroup); + +/** +* set the meshresolution of the mesh object +* +* @param[in] pObject - Object instance. +* @param[in] eMeshResolution - meshresolution of this object +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_setslicesmeshresolution(Lib3MF_Object pObject, Lib3MF::eSlicesMeshResolution eMeshResolution); + +/** +* get the meshresolution of the mesh object +* +* @param[in] pObject - Object instance. +* @param[out] pMeshResolution - meshresolution of this object +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_getslicesmeshresolution(Lib3MF_Object pObject, Lib3MF::eSlicesMeshResolution * pMeshResolution); + +/** +* returns whether the Object has a slice stack. If Recursive is true, also checks whether any references object has a slice stack +* +* @param[in] pObject - Object instance. +* @param[in] bRecursive - check also all referenced objects? +* @param[out] pHasSlices - does the object have a slice stack? +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_hasslices(Lib3MF_Object pObject, bool bRecursive, bool * pHasSlices); + +/** +* unlinks the attached slicestack from this object. If no slice stack is attached, do noting. +* +* @param[in] pObject - Object instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_clearslicestack(Lib3MF_Object pObject); + +/** +* get the Slicestack attached to the object +* +* @param[in] pObject - Object instance. +* @param[out] pSliceStackInstance - returns the slicestack instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_getslicestack(Lib3MF_Object pObject, Lib3MF_SliceStack * pSliceStackInstance); + +/** +* assigns a slicestack to the object +* +* @param[in] pObject - Object instance. +* @param[in] pSliceStackInstance - the new slice stack of this Object +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_assignslicestack(Lib3MF_Object pObject, Lib3MF_SliceStack pSliceStackInstance); + +/************************************************************************************************************************* + Class definition for MeshObject +**************************************************************************************************************************/ + +/** +* Returns the vertex count of a mesh object. +* +* @param[in] pMeshObject - MeshObject instance. +* @param[out] pVertexCount - filled with the vertex count. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_getvertexcount(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 * pVertexCount); + +/** +* Returns the triangle count of a mesh object. +* +* @param[in] pMeshObject - MeshObject instance. +* @param[out] pVertexCount - filled with the triangle count. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_gettrianglecount(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 * pVertexCount); + +/** +* Returns the vertex count of a mesh object. +* +* @param[in] pMeshObject - MeshObject instance. +* @param[in] nIndex - Index of the vertex (0 to vertexcount - 1) +* @param[out] pCoordinates - filled with the vertex coordinates. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_getvertex(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 nIndex, Lib3MF::sPosition * pCoordinates); + +/** +* Sets the coordinates of a single vertex of a mesh object +* +* @param[in] pMeshObject - MeshObject instance. +* @param[in] nIndex - Index of the vertex (0 to vertexcount - 1) +* @param[in] pCoordinates - contains the vertex coordinates. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_setvertex(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 nIndex, const Lib3MF::sPosition * pCoordinates); + +/** +* Adds a single vertex to a mesh object +* +* @param[in] pMeshObject - MeshObject instance. +* @param[in] pCoordinates - contains the vertex coordinates. +* @param[out] pNewIndex - Index of the new vertex +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_addvertex(Lib3MF_MeshObject pMeshObject, const Lib3MF::sPosition * pCoordinates, Lib3MF_uint32 * pNewIndex); + +/** +* Obtains all vertex positions of a mesh object +* +* @param[in] pMeshObject - MeshObject instance. +* @param[in] nVerticesBufferSize - Number of elements in buffer +* @param[out] pVerticesNeededCount - will be filled with the count of the written elements, or needed buffer size. +* @param[out] pVerticesBuffer - Position buffer of contains the vertex coordinates. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_getvertices(Lib3MF_MeshObject pMeshObject, const Lib3MF_uint64 nVerticesBufferSize, Lib3MF_uint64* pVerticesNeededCount, Lib3MF::sPosition * pVerticesBuffer); + +/** +* Returns indices of a single triangle of a mesh object. +* +* @param[in] pMeshObject - MeshObject instance. +* @param[in] nIndex - Index of the triangle (0 to trianglecount - 1) +* @param[out] pIndices - filled with the triangle indices. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_gettriangle(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 nIndex, Lib3MF::sTriangle * pIndices); + +/** +* Sets the indices of a single triangle of a mesh object. +* +* @param[in] pMeshObject - MeshObject instance. +* @param[in] nIndex - Index of the triangle (0 to trianglecount - 1) +* @param[in] pIndices - contains the triangle indices. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_settriangle(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 nIndex, const Lib3MF::sTriangle * pIndices); + +/** +* Adds a single triangle to a mesh object +* +* @param[in] pMeshObject - MeshObject instance. +* @param[in] pIndices - contains the triangle indices. +* @param[out] pNewIndex - Index of the new triangle +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_addtriangle(Lib3MF_MeshObject pMeshObject, const Lib3MF::sTriangle * pIndices, Lib3MF_uint32 * pNewIndex); + +/** +* Get all triangles of a mesh object +* +* @param[in] pMeshObject - MeshObject instance. +* @param[in] nIndicesBufferSize - Number of elements in buffer +* @param[out] pIndicesNeededCount - will be filled with the count of the written elements, or needed buffer size. +* @param[out] pIndicesBuffer - Triangle buffer of contains the triangle indices. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_gettriangleindices(Lib3MF_MeshObject pMeshObject, const Lib3MF_uint64 nIndicesBufferSize, Lib3MF_uint64* pIndicesNeededCount, Lib3MF::sTriangle * pIndicesBuffer); + +/** +* Sets the property at the object-level of the mesh object. +* +* @param[in] pMeshObject - MeshObject instance. +* @param[in] nUniqueResourceID - the object-level Property UniqueResourceID. +* @param[in] nPropertyID - the object-level PropertyID. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_setobjectlevelproperty(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 nUniqueResourceID, Lib3MF_uint32 nPropertyID); + +/** +* Gets the property at the object-level of the mesh object. +* +* @param[in] pMeshObject - MeshObject instance. +* @param[out] pUniqueResourceID - the object-level Property UniqueResourceID. +* @param[out] pPropertyID - the object-level PropertyID. +* @param[out] pHasObjectLevelProperty - Has an object-level property been specified? +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_getobjectlevelproperty(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 * pUniqueResourceID, Lib3MF_uint32 * pPropertyID, bool * pHasObjectLevelProperty); + +/** +* Sets the properties of a single triangle of a mesh object. +* +* @param[in] pMeshObject - MeshObject instance. +* @param[in] nIndex - Index of the triangle (0 to trianglecount - 1) +* @param[in] pProperties - contains the triangle properties. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_settriangleproperties(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 nIndex, const Lib3MF::sTriangleProperties * pProperties); + +/** +* Gets the properties of a single triangle of a mesh object. +* +* @param[in] pMeshObject - MeshObject instance. +* @param[in] nIndex - Index of the triangle (0 to trianglecount - 1) +* @param[out] pProperty - returns the triangle properties. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_gettriangleproperties(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 nIndex, Lib3MF::sTriangleProperties * pProperty); + +/** +* Sets the properties of all triangles of a mesh object. Sets the object level property to the first entry of the passed triangle properties, if not yet specified. +* +* @param[in] pMeshObject - MeshObject instance. +* @param[in] nPropertiesArrayBufferSize - Number of elements in buffer +* @param[in] pPropertiesArrayBuffer - TriangleProperties buffer of contains the triangle properties array. Must have trianglecount elements. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_setalltriangleproperties(Lib3MF_MeshObject pMeshObject, Lib3MF_uint64 nPropertiesArrayBufferSize, const Lib3MF::sTriangleProperties * pPropertiesArrayBuffer); + +/** +* Gets the properties of all triangles of a mesh object. +* +* @param[in] pMeshObject - MeshObject instance. +* @param[in] nPropertiesArrayBufferSize - Number of elements in buffer +* @param[out] pPropertiesArrayNeededCount - will be filled with the count of the written elements, or needed buffer size. +* @param[out] pPropertiesArrayBuffer - TriangleProperties buffer of returns the triangle properties array. Must have trianglecount elements. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_getalltriangleproperties(Lib3MF_MeshObject pMeshObject, const Lib3MF_uint64 nPropertiesArrayBufferSize, Lib3MF_uint64* pPropertiesArrayNeededCount, Lib3MF::sTriangleProperties * pPropertiesArrayBuffer); + +/** +* Clears all properties of this mesh object (triangle and object-level). +* +* @param[in] pMeshObject - MeshObject instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_clearallproperties(Lib3MF_MeshObject pMeshObject); + +/** +* Set all triangles of a mesh object +* +* @param[in] pMeshObject - MeshObject instance. +* @param[in] nVerticesBufferSize - Number of elements in buffer +* @param[in] pVerticesBuffer - Position buffer of contains the positions. +* @param[in] nIndicesBufferSize - Number of elements in buffer +* @param[in] pIndicesBuffer - Triangle buffer of contains the triangle indices. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_setgeometry(Lib3MF_MeshObject pMeshObject, Lib3MF_uint64 nVerticesBufferSize, const Lib3MF::sPosition * pVerticesBuffer, Lib3MF_uint64 nIndicesBufferSize, const Lib3MF::sTriangle * pIndicesBuffer); + +/** +* Retrieves, if an object describes a topologically oriented and manifold mesh, according to the core spec. +* +* @param[in] pMeshObject - MeshObject instance. +* @param[out] pIsManifoldAndOriented - returns, if the object is oriented and manifold. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_ismanifoldandoriented(Lib3MF_MeshObject pMeshObject, bool * pIsManifoldAndOriented); + +/** +* Retrieves the BeamLattice within this MeshObject. +* +* @param[in] pMeshObject - MeshObject instance. +* @param[out] pTheBeamLattice - the BeamLattice within this MeshObject +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_beamlattice(Lib3MF_MeshObject pMeshObject, Lib3MF_BeamLattice * pTheBeamLattice); + +/************************************************************************************************************************* + Class definition for BeamLattice +**************************************************************************************************************************/ + +/** +* Returns the minimal length of beams for the beamlattice. +* +* @param[in] pBeamLattice - BeamLattice instance. +* @param[out] pMinLength - minimal length of beams for the beamlattice +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_getminlength(Lib3MF_BeamLattice pBeamLattice, Lib3MF_double * pMinLength); + +/** +* Sets the minimal length of beams for the beamlattice. +* +* @param[in] pBeamLattice - BeamLattice instance. +* @param[in] dMinLength - minimal length of beams for the beamlattice +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_setminlength(Lib3MF_BeamLattice pBeamLattice, Lib3MF_double dMinLength); + +/** +* Returns the clipping mode and the clipping-mesh for the beamlattice of this mesh. +* +* @param[in] pBeamLattice - BeamLattice instance. +* @param[out] pClipMode - contains the clip mode of this mesh +* @param[out] pUniqueResourceID - filled with the UniqueResourceID of the clipping mesh-object or an undefined value if pClipMode is MODELBEAMLATTICECLIPMODE_NONE +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_getclipping(Lib3MF_BeamLattice pBeamLattice, Lib3MF::eBeamLatticeClipMode * pClipMode, Lib3MF_uint32 * pUniqueResourceID); + +/** +* Sets the clipping mode and the clipping-mesh for the beamlattice of this mesh. +* +* @param[in] pBeamLattice - BeamLattice instance. +* @param[in] eClipMode - contains the clip mode of this mesh +* @param[in] nUniqueResourceID - the UniqueResourceID of the clipping mesh-object. This mesh-object has to be defined before setting the Clipping. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_setclipping(Lib3MF_BeamLattice pBeamLattice, Lib3MF::eBeamLatticeClipMode eClipMode, Lib3MF_uint32 nUniqueResourceID); + +/** +* Returns the representation-mesh for the beamlattice of this mesh. +* +* @param[in] pBeamLattice - BeamLattice instance. +* @param[out] pHasRepresentation - flag whether the beamlattice has a representation mesh. +* @param[out] pUniqueResourceID - filled with the UniqueResourceID of the clipping mesh-object. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_getrepresentation(Lib3MF_BeamLattice pBeamLattice, bool * pHasRepresentation, Lib3MF_uint32 * pUniqueResourceID); + +/** +* Sets the representation-mesh for the beamlattice of this mesh. +* +* @param[in] pBeamLattice - BeamLattice instance. +* @param[in] nUniqueResourceID - the UniqueResourceID of the representation mesh-object. This mesh-object has to be defined before setting the representation. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_setrepresentation(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint32 nUniqueResourceID); + +/** +* Returns the ball mode and the default ball radius for the beamlattice of this mesh. +* +* @param[in] pBeamLattice - BeamLattice instance. +* @param[out] pBallMode - contains the ball mode of this mesh +* @param[out] pBallRadius - default ball radius of balls for the beamlattice +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_getballoptions(Lib3MF_BeamLattice pBeamLattice, Lib3MF::eBeamLatticeBallMode * pBallMode, Lib3MF_double * pBallRadius); + +/** +* Sets the ball mode and thedefault ball radius for the beamlattice. +* +* @param[in] pBeamLattice - BeamLattice instance. +* @param[in] eBallMode - contains the ball mode of this mesh +* @param[in] dBallRadius - default ball radius of balls for the beamlattice +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_setballoptions(Lib3MF_BeamLattice pBeamLattice, Lib3MF::eBeamLatticeBallMode eBallMode, Lib3MF_double dBallRadius); + +/** +* Returns the beam count of a mesh object. +* +* @param[in] pBeamLattice - BeamLattice instance. +* @param[out] pCount - filled with the beam count. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_getbeamcount(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint32 * pCount); + +/** +* Returns indices, radii and capmodes of a single beam of a mesh object. +* +* @param[in] pBeamLattice - BeamLattice instance. +* @param[in] nIndex - Index of the beam (0 to beamcount - 1). +* @param[out] pBeamInfo - filled with the beam indices, radii and capmodes. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_getbeam(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint32 nIndex, Lib3MF::sBeam * pBeamInfo); + +/** +* Adds a single beam to a mesh object. +* +* @param[in] pBeamLattice - BeamLattice instance. +* @param[in] pBeamInfo - contains the node indices, radii and capmodes. +* @param[out] pIndex - filled with the new Index of the beam. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_addbeam(Lib3MF_BeamLattice pBeamLattice, const Lib3MF::sBeam * pBeamInfo, Lib3MF_uint32 * pIndex); + +/** +* Sets the indices, radii and capmodes of a single beam of a mesh object. +* +* @param[in] pBeamLattice - BeamLattice instance. +* @param[in] nIndex - Index of the beam (0 to beamcount - 1). +* @param[in] pBeamInfo - filled with the beam indices, radii and capmodes. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_setbeam(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint32 nIndex, const Lib3MF::sBeam * pBeamInfo); + +/** +* Sets all beam indices, radii and capmodes of a mesh object. +* +* @param[in] pBeamLattice - BeamLattice instance. +* @param[in] nBeamInfoBufferSize - Number of elements in buffer +* @param[in] pBeamInfoBuffer - Beam buffer of contains information of a number of beams +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_setbeams(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint64 nBeamInfoBufferSize, const Lib3MF::sBeam * pBeamInfoBuffer); + +/** +* obtains all beam indices, radii and capmodes of a mesh object. +* +* @param[in] pBeamLattice - BeamLattice instance. +* @param[in] nBeamInfoBufferSize - Number of elements in buffer +* @param[out] pBeamInfoNeededCount - will be filled with the count of the written elements, or needed buffer size. +* @param[out] pBeamInfoBuffer - Beam buffer of contains information of all beams +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_getbeams(Lib3MF_BeamLattice pBeamLattice, const Lib3MF_uint64 nBeamInfoBufferSize, Lib3MF_uint64* pBeamInfoNeededCount, Lib3MF::sBeam * pBeamInfoBuffer); + +/** +* Returns the ball count of a mesh object. +* +* @param[in] pBeamLattice - BeamLattice instance. +* @param[out] pCount - filled with the ball count. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_getballcount(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint32 * pCount); + +/** +* Returns index and radius of a single ball of a mesh object. +* +* @param[in] pBeamLattice - BeamLattice instance. +* @param[in] nIndex - Index of the ball (0 to ballcount - 1). +* @param[out] pBallInfo - filled with the ball node index and radius. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_getball(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint32 nIndex, Lib3MF::sBall * pBallInfo); + +/** +* Adds a single ball to a mesh object. +* +* @param[in] pBeamLattice - BeamLattice instance. +* @param[in] pBallInfo - contains the node index and radius. +* @param[out] pIndex - filled with the new Index of the ball. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_addball(Lib3MF_BeamLattice pBeamLattice, const Lib3MF::sBall * pBallInfo, Lib3MF_uint32 * pIndex); + +/** +* Sets the index and radius of a single ball of a mesh object. +* +* @param[in] pBeamLattice - BeamLattice instance. +* @param[in] nIndex - Index of the ball (0 to ballcount - 1). +* @param[in] pBallInfo - filled with the ball node index and radius. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_setball(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint32 nIndex, const Lib3MF::sBall * pBallInfo); + +/** +* Sets all ball indices and radii of a mesh object. +* +* @param[in] pBeamLattice - BeamLattice instance. +* @param[in] nBallInfoBufferSize - Number of elements in buffer +* @param[in] pBallInfoBuffer - Ball buffer of contains information of a number of balls +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_setballs(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint64 nBallInfoBufferSize, const Lib3MF::sBall * pBallInfoBuffer); + +/** +* obtains all ball indices and radii of a mesh object. +* +* @param[in] pBeamLattice - BeamLattice instance. +* @param[in] nBallInfoBufferSize - Number of elements in buffer +* @param[out] pBallInfoNeededCount - will be filled with the count of the written elements, or needed buffer size. +* @param[out] pBallInfoBuffer - Ball buffer of contains information of all balls +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_getballs(Lib3MF_BeamLattice pBeamLattice, const Lib3MF_uint64 nBallInfoBufferSize, Lib3MF_uint64* pBallInfoNeededCount, Lib3MF::sBall * pBallInfoBuffer); + +/** +* Returns the number of beamsets of a mesh object. +* +* @param[in] pBeamLattice - BeamLattice instance. +* @param[out] pCount - filled with the beamset count. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_getbeamsetcount(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint32 * pCount); + +/** +* Adds an empty beamset to a mesh object +* +* @param[in] pBeamLattice - BeamLattice instance. +* @param[out] pBeamSet - the new beamset +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_addbeamset(Lib3MF_BeamLattice pBeamLattice, Lib3MF_BeamSet * pBeamSet); + +/** +* Returns a beamset of a mesh object +* +* @param[in] pBeamLattice - BeamLattice instance. +* @param[in] nIndex - index of the requested beamset (0 ... beamsetcount-1). +* @param[out] pBeamSet - the requested beamset +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_getbeamset(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint32 nIndex, Lib3MF_BeamSet * pBeamSet); + +/************************************************************************************************************************* + Class definition for Component +**************************************************************************************************************************/ + +/** +* Returns the Resource Instance of the component. +* +* @param[in] pComponent - Component instance. +* @param[out] pObjectResource - filled with the Resource Instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_component_getobjectresource(Lib3MF_Component pComponent, Lib3MF_Object * pObjectResource); + +/** +* Returns the UniqueResourceID of the component. +* +* @param[in] pComponent - Component instance. +* @param[out] pUniqueResourceID - returns the UniqueResourceID. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_component_getobjectresourceid(Lib3MF_Component pComponent, Lib3MF_uint32 * pUniqueResourceID); + +/** +* returns, whether a component has a UUID and, if true, the component's UUID +* +* @param[in] pComponent - Component instance. +* @param[out] pHasUUID - flag whether the component has a UUID +* @param[in] nUUIDBufferSize - size of the buffer (including trailing 0) +* @param[out] pUUIDNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pUUIDBuffer - buffer of the UUID as string of the form 'xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx', may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_component_getuuid(Lib3MF_Component pComponent, bool * pHasUUID, const Lib3MF_uint32 nUUIDBufferSize, Lib3MF_uint32* pUUIDNeededChars, char * pUUIDBuffer); + +/** +* sets the component's UUID +* +* @param[in] pComponent - Component instance. +* @param[in] pUUID - the UUID as string of the form 'xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx' +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_component_setuuid(Lib3MF_Component pComponent, const char * pUUID); + +/** +* Returns, if the component has a different transformation than the identity matrix +* +* @param[in] pComponent - Component instance. +* @param[out] pHasTransform - if true is returned, the transformation is not equal than the identity +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_component_hastransform(Lib3MF_Component pComponent, bool * pHasTransform); + +/** +* Returns the transformation matrix of the component. +* +* @param[in] pComponent - Component instance. +* @param[out] pTransform - filled with the component transformation matrix +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_component_gettransform(Lib3MF_Component pComponent, Lib3MF::sTransform * pTransform); + +/** +* Sets the transformation matrix of the component. +* +* @param[in] pComponent - Component instance. +* @param[in] pTransform - new transformation matrix +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_component_settransform(Lib3MF_Component pComponent, const Lib3MF::sTransform * pTransform); + +/************************************************************************************************************************* + Class definition for ComponentsObject +**************************************************************************************************************************/ + +/** +* Adds a new component to a components object. +* +* @param[in] pComponentsObject - ComponentsObject instance. +* @param[in] pObjectResource - object to add as component. Must not lead to circular references! +* @param[in] pTransform - optional transform matrix for the component. +* @param[out] pComponentInstance - new component instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_componentsobject_addcomponent(Lib3MF_ComponentsObject pComponentsObject, Lib3MF_Object pObjectResource, const Lib3MF::sTransform * pTransform, Lib3MF_Component * pComponentInstance); + +/** +* Retrieves a component from a component object. +* +* @param[in] pComponentsObject - ComponentsObject instance. +* @param[in] nIndex - index of the component to retrieve (0 to componentcount - 1) +* @param[out] pComponentInstance - component instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_componentsobject_getcomponent(Lib3MF_ComponentsObject pComponentsObject, Lib3MF_uint32 nIndex, Lib3MF_Component * pComponentInstance); + +/** +* Retrieves a component count of a component object. +* +* @param[in] pComponentsObject - ComponentsObject instance. +* @param[out] pCount - returns the component count +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_componentsobject_getcomponentcount(Lib3MF_ComponentsObject pComponentsObject, Lib3MF_uint32 * pCount); + +/************************************************************************************************************************* + Class definition for BeamSet +**************************************************************************************************************************/ + +/** +* Sets a beamset's name string +* +* @param[in] pBeamSet - BeamSet instance. +* @param[in] pName - new name of the beamset. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamset_setname(Lib3MF_BeamSet pBeamSet, const char * pName); + +/** +* Retrieves a beamset's name string +* +* @param[in] pBeamSet - BeamSet instance. +* @param[in] nNameBufferSize - size of the buffer (including trailing 0) +* @param[out] pNameNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pNameBuffer - buffer of returns the name of the beamset., may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamset_getname(Lib3MF_BeamSet pBeamSet, const Lib3MF_uint32 nNameBufferSize, Lib3MF_uint32* pNameNeededChars, char * pNameBuffer); + +/** +* Sets a beamset's identifier string +* +* @param[in] pBeamSet - BeamSet instance. +* @param[in] pIdentifier - new name of the beamset. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamset_setidentifier(Lib3MF_BeamSet pBeamSet, const char * pIdentifier); + +/** +* Retrieves a beamset's identifier string +* +* @param[in] pBeamSet - BeamSet instance. +* @param[in] nIdentifierBufferSize - size of the buffer (including trailing 0) +* @param[out] pIdentifierNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pIdentifierBuffer - buffer of returns the identifier of the beamset., may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamset_getidentifier(Lib3MF_BeamSet pBeamSet, const Lib3MF_uint32 nIdentifierBufferSize, Lib3MF_uint32* pIdentifierNeededChars, char * pIdentifierBuffer); + +/** +* Retrieves the reference count of a beamset +* +* @param[in] pBeamSet - BeamSet instance. +* @param[out] pCount - returns the reference count +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamset_getreferencecount(Lib3MF_BeamSet pBeamSet, Lib3MF_uint32 * pCount); + +/** +* Sets the references of a beamset +* +* @param[in] pBeamSet - BeamSet instance. +* @param[in] nReferencesBufferSize - Number of elements in buffer +* @param[in] pReferencesBuffer - uint32 buffer of the new indices of all beams in this beamset +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamset_setreferences(Lib3MF_BeamSet pBeamSet, Lib3MF_uint64 nReferencesBufferSize, const Lib3MF_uint32 * pReferencesBuffer); + +/** +* Retrieves the references of a beamset +* +* @param[in] pBeamSet - BeamSet instance. +* @param[in] nReferencesBufferSize - Number of elements in buffer +* @param[out] pReferencesNeededCount - will be filled with the count of the written elements, or needed buffer size. +* @param[out] pReferencesBuffer - uint32 buffer of retrieves the indices of all beams in this beamset +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamset_getreferences(Lib3MF_BeamSet pBeamSet, const Lib3MF_uint64 nReferencesBufferSize, Lib3MF_uint64* pReferencesNeededCount, Lib3MF_uint32 * pReferencesBuffer); + +/** +* Retrieves the ball reference count of a beamset +* +* @param[in] pBeamSet - BeamSet instance. +* @param[out] pCount - returns the ball reference count +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamset_getballreferencecount(Lib3MF_BeamSet pBeamSet, Lib3MF_uint32 * pCount); + +/** +* Sets the ball references of a beamset +* +* @param[in] pBeamSet - BeamSet instance. +* @param[in] nBallReferencesBufferSize - Number of elements in buffer +* @param[in] pBallReferencesBuffer - uint32 buffer of the new indices of all balls in this beamset +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamset_setballreferences(Lib3MF_BeamSet pBeamSet, Lib3MF_uint64 nBallReferencesBufferSize, const Lib3MF_uint32 * pBallReferencesBuffer); + +/** +* Retrieves the ball references of a beamset +* +* @param[in] pBeamSet - BeamSet instance. +* @param[in] nBallReferencesBufferSize - Number of elements in buffer +* @param[out] pBallReferencesNeededCount - will be filled with the count of the written elements, or needed buffer size. +* @param[out] pBallReferencesBuffer - uint32 buffer of retrieves the indices of all balls in this beamset +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamset_getballreferences(Lib3MF_BeamSet pBeamSet, const Lib3MF_uint64 nBallReferencesBufferSize, Lib3MF_uint64* pBallReferencesNeededCount, Lib3MF_uint32 * pBallReferencesBuffer); + +/************************************************************************************************************************* + Class definition for BaseMaterialGroup +**************************************************************************************************************************/ + +/** +* Retrieves the count of base materials in the material group. +* +* @param[in] pBaseMaterialGroup - BaseMaterialGroup instance. +* @param[out] pCount - returns the count of base materials. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_basematerialgroup_getcount(Lib3MF_BaseMaterialGroup pBaseMaterialGroup, Lib3MF_uint32 * pCount); + +/** +* returns all the PropertyIDs of all materials in this group +* +* @param[in] pBaseMaterialGroup - BaseMaterialGroup instance. +* @param[in] nPropertyIDsBufferSize - Number of elements in buffer +* @param[out] pPropertyIDsNeededCount - will be filled with the count of the written elements, or needed buffer size. +* @param[out] pPropertyIDsBuffer - uint32 buffer of PropertyID of the material in the material group. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_basematerialgroup_getallpropertyids(Lib3MF_BaseMaterialGroup pBaseMaterialGroup, const Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer); + +/** +* Adds a new material to the material group +* +* @param[in] pBaseMaterialGroup - BaseMaterialGroup instance. +* @param[in] pName - new name of the base material. +* @param[in] pDisplayColor - Display color of the material +* @param[out] pPropertyID - returns new PropertyID of the new material in the material group. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_basematerialgroup_addmaterial(Lib3MF_BaseMaterialGroup pBaseMaterialGroup, const char * pName, const Lib3MF::sColor * pDisplayColor, Lib3MF_uint32 * pPropertyID); + +/** +* Removes a material from the material group. +* +* @param[in] pBaseMaterialGroup - BaseMaterialGroup instance. +* @param[in] nPropertyID - PropertyID of the material in the material group. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_basematerialgroup_removematerial(Lib3MF_BaseMaterialGroup pBaseMaterialGroup, Lib3MF_uint32 nPropertyID); + +/** +* Returns the base material's name +* +* @param[in] pBaseMaterialGroup - BaseMaterialGroup instance. +* @param[in] nPropertyID - PropertyID of the material in the material group. +* @param[in] nNameBufferSize - size of the buffer (including trailing 0) +* @param[out] pNameNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pNameBuffer - buffer of returns the name of the base material., may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_basematerialgroup_getname(Lib3MF_BaseMaterialGroup pBaseMaterialGroup, Lib3MF_uint32 nPropertyID, const Lib3MF_uint32 nNameBufferSize, Lib3MF_uint32* pNameNeededChars, char * pNameBuffer); + +/** +* Sets a base material's name +* +* @param[in] pBaseMaterialGroup - BaseMaterialGroup instance. +* @param[in] nPropertyID - PropertyID of the material in the material group. +* @param[in] pName - new name of the base material. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_basematerialgroup_setname(Lib3MF_BaseMaterialGroup pBaseMaterialGroup, Lib3MF_uint32 nPropertyID, const char * pName); + +/** +* Sets a base material's display color. +* +* @param[in] pBaseMaterialGroup - BaseMaterialGroup instance. +* @param[in] nPropertyID - PropertyID of the material in the material group. +* @param[in] pTheColor - The base material's display color +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_basematerialgroup_setdisplaycolor(Lib3MF_BaseMaterialGroup pBaseMaterialGroup, Lib3MF_uint32 nPropertyID, const Lib3MF::sColor * pTheColor); + +/** +* Returns a base material's display color. +* +* @param[in] pBaseMaterialGroup - BaseMaterialGroup instance. +* @param[in] nPropertyID - PropertyID of the material in the material group. +* @param[out] pTheColor - The base material's display color +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_basematerialgroup_getdisplaycolor(Lib3MF_BaseMaterialGroup pBaseMaterialGroup, Lib3MF_uint32 nPropertyID, Lib3MF::sColor * pTheColor); + +/************************************************************************************************************************* + Class definition for ColorGroup +**************************************************************************************************************************/ + +/** +* Retrieves the count of base materials in this Color Group. +* +* @param[in] pColorGroup - ColorGroup instance. +* @param[out] pCount - returns the count of colors within this color group. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_colorgroup_getcount(Lib3MF_ColorGroup pColorGroup, Lib3MF_uint32 * pCount); + +/** +* returns all the PropertyIDs of all colors within this group +* +* @param[in] pColorGroup - ColorGroup instance. +* @param[in] nPropertyIDsBufferSize - Number of elements in buffer +* @param[out] pPropertyIDsNeededCount - will be filled with the count of the written elements, or needed buffer size. +* @param[out] pPropertyIDsBuffer - uint32 buffer of PropertyID of the color in the color group. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_colorgroup_getallpropertyids(Lib3MF_ColorGroup pColorGroup, const Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer); + +/** +* Adds a new value. +* +* @param[in] pColorGroup - ColorGroup instance. +* @param[in] pTheColor - The new color +* @param[out] pPropertyID - PropertyID of the new color within this color group. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_colorgroup_addcolor(Lib3MF_ColorGroup pColorGroup, const Lib3MF::sColor * pTheColor, Lib3MF_uint32 * pPropertyID); + +/** +* Removes a color from the color group. +* +* @param[in] pColorGroup - ColorGroup instance. +* @param[in] nPropertyID - PropertyID of the color to be removed from the color group. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_colorgroup_removecolor(Lib3MF_ColorGroup pColorGroup, Lib3MF_uint32 nPropertyID); + +/** +* Sets a color value. +* +* @param[in] pColorGroup - ColorGroup instance. +* @param[in] nPropertyID - PropertyID of a color within this color group. +* @param[in] pTheColor - The color +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_colorgroup_setcolor(Lib3MF_ColorGroup pColorGroup, Lib3MF_uint32 nPropertyID, const Lib3MF::sColor * pTheColor); + +/** +* Sets a color value. +* +* @param[in] pColorGroup - ColorGroup instance. +* @param[in] nPropertyID - PropertyID of a color within this color group. +* @param[out] pTheColor - The color +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_colorgroup_getcolor(Lib3MF_ColorGroup pColorGroup, Lib3MF_uint32 nPropertyID, Lib3MF::sColor * pTheColor); + +/************************************************************************************************************************* + Class definition for Texture2DGroup +**************************************************************************************************************************/ + +/** +* Retrieves the count of tex2coords in the Texture2DGroup. +* +* @param[in] pTexture2DGroup - Texture2DGroup instance. +* @param[out] pCount - returns the count of tex2coords. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2dgroup_getcount(Lib3MF_Texture2DGroup pTexture2DGroup, Lib3MF_uint32 * pCount); + +/** +* returns all the PropertyIDs of all tex2coords in this Texture2DGroup +* +* @param[in] pTexture2DGroup - Texture2DGroup instance. +* @param[in] nPropertyIDsBufferSize - Number of elements in buffer +* @param[out] pPropertyIDsNeededCount - will be filled with the count of the written elements, or needed buffer size. +* @param[out] pPropertyIDsBuffer - uint32 buffer of PropertyID of the tex2coords in the Texture2DGroup. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2dgroup_getallpropertyids(Lib3MF_Texture2DGroup pTexture2DGroup, const Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer); + +/** +* Adds a new tex2coord to the Texture2DGroup +* +* @param[in] pTexture2DGroup - Texture2DGroup instance. +* @param[in] pUVCoordinate - The u/v-coordinate within the texture, horizontally right/vertically up from the origin in the lower left of the texture. +* @param[out] pPropertyID - returns new PropertyID of the new tex2coord in the Texture2DGroup. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2dgroup_addtex2coord(Lib3MF_Texture2DGroup pTexture2DGroup, const Lib3MF::sTex2Coord * pUVCoordinate, Lib3MF_uint32 * pPropertyID); + +/** +* Obtains a tex2coord to the Texture2DGroup +* +* @param[in] pTexture2DGroup - Texture2DGroup instance. +* @param[in] nPropertyID - the PropertyID of the tex2coord in the Texture2DGroup. +* @param[out] pUVCoordinate - The u/v-coordinate within the texture, horizontally right/vertically up from the origin in the lower left of the texture. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2dgroup_gettex2coord(Lib3MF_Texture2DGroup pTexture2DGroup, Lib3MF_uint32 nPropertyID, Lib3MF::sTex2Coord * pUVCoordinate); + +/** +* Removes a tex2coords from the Texture2DGroup. +* +* @param[in] pTexture2DGroup - Texture2DGroup instance. +* @param[in] nPropertyID - PropertyID of the tex2coords in the Texture2DGroup. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2dgroup_removetex2coord(Lib3MF_Texture2DGroup pTexture2DGroup, Lib3MF_uint32 nPropertyID); + +/** +* Obtains the texture2D instance of this group. +* +* @param[in] pTexture2DGroup - Texture2DGroup instance. +* @param[out] pTexture2DInstance - the texture2D instance of this group. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2dgroup_gettexture2d(Lib3MF_Texture2DGroup pTexture2DGroup, Lib3MF_Texture2D * pTexture2DInstance); + +/************************************************************************************************************************* + Class definition for CompositeMaterials +**************************************************************************************************************************/ + +/** +* Retrieves the count of Composite-s in the CompositeMaterials. +* +* @param[in] pCompositeMaterials - CompositeMaterials instance. +* @param[out] pCount - returns the count of Composite-s +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_compositematerials_getcount(Lib3MF_CompositeMaterials pCompositeMaterials, Lib3MF_uint32 * pCount); + +/** +* returns all the PropertyIDs of all Composite-Mixing Values in this CompositeMaterials +* +* @param[in] pCompositeMaterials - CompositeMaterials instance. +* @param[in] nPropertyIDsBufferSize - Number of elements in buffer +* @param[out] pPropertyIDsNeededCount - will be filled with the count of the written elements, or needed buffer size. +* @param[out] pPropertyIDsBuffer - uint32 buffer of PropertyID of the Composite-Mixing Values in the CompositeMaterials. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_compositematerials_getallpropertyids(Lib3MF_CompositeMaterials pCompositeMaterials, const Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer); + +/** +* Obtains the BaseMaterialGroup instance of this CompositeMaterials. +* +* @param[in] pCompositeMaterials - CompositeMaterials instance. +* @param[out] pBaseMaterialGroupInstance - returns the BaseMaterialGroup instance of this CompositeMaterials +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_compositematerials_getbasematerialgroup(Lib3MF_CompositeMaterials pCompositeMaterials, Lib3MF_BaseMaterialGroup * pBaseMaterialGroupInstance); + +/** +* Adds a new Composite-Mixing Values to the CompositeMaterials. +* +* @param[in] pCompositeMaterials - CompositeMaterials instance. +* @param[in] nCompositeBufferSize - Number of elements in buffer +* @param[in] pCompositeBuffer - CompositeConstituent buffer of The Composite Constituents to be added as composite +* @param[out] pPropertyID - returns new PropertyID of the new Composite in the CompositeMaterials. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_compositematerials_addcomposite(Lib3MF_CompositeMaterials pCompositeMaterials, Lib3MF_uint64 nCompositeBufferSize, const Lib3MF::sCompositeConstituent * pCompositeBuffer, Lib3MF_uint32 * pPropertyID); + +/** +* Removes a Composite-Maxing Ratio from the CompositeMaterials. +* +* @param[in] pCompositeMaterials - CompositeMaterials instance. +* @param[in] nPropertyID - PropertyID of the Composite-Mixing Values in the CompositeMaterials to be removed. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_compositematerials_removecomposite(Lib3MF_CompositeMaterials pCompositeMaterials, Lib3MF_uint32 nPropertyID); + +/** +* Obtains a Composite-Maxing Ratio of this CompositeMaterials. +* +* @param[in] pCompositeMaterials - CompositeMaterials instance. +* @param[in] nPropertyID - the PropertyID of the Composite-Maxing Ratio in the CompositeMaterials. +* @param[in] nCompositeBufferSize - Number of elements in buffer +* @param[out] pCompositeNeededCount - will be filled with the count of the written elements, or needed buffer size. +* @param[out] pCompositeBuffer - CompositeConstituent buffer of The Composite-Mixing Values with the given PropertyID +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_compositematerials_getcomposite(Lib3MF_CompositeMaterials pCompositeMaterials, Lib3MF_uint32 nPropertyID, const Lib3MF_uint64 nCompositeBufferSize, Lib3MF_uint64* pCompositeNeededCount, Lib3MF::sCompositeConstituent * pCompositeBuffer); + +/************************************************************************************************************************* + Class definition for MultiPropertyGroup +**************************************************************************************************************************/ + +/** +* Retrieves the count of MultiProperty-s in the MultiPropertyGroup. +* +* @param[in] pMultiPropertyGroup - MultiPropertyGroup instance. +* @param[out] pCount - returns the count of MultiProperty-s +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_multipropertygroup_getcount(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, Lib3MF_uint32 * pCount); + +/** +* returns all the PropertyIDs of all MultiProperty-s in this MultiPropertyGroup +* +* @param[in] pMultiPropertyGroup - MultiPropertyGroup instance. +* @param[in] nPropertyIDsBufferSize - Number of elements in buffer +* @param[out] pPropertyIDsNeededCount - will be filled with the count of the written elements, or needed buffer size. +* @param[out] pPropertyIDsBuffer - uint32 buffer of PropertyID of the MultiProperty-s in the MultiPropertyGroup. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_multipropertygroup_getallpropertyids(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, const Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer); + +/** +* Adds a new MultiProperty to the MultiPropertyGroup. +* +* @param[in] pMultiPropertyGroup - MultiPropertyGroup instance. +* @param[in] nPropertyIDsBufferSize - Number of elements in buffer +* @param[in] pPropertyIDsBuffer - uint32 buffer of The PropertyIDs of the new MultiProperty. +* @param[out] pPropertyID - returns the PropertyID of the new MultiProperty in the MultiPropertyGroup. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_multipropertygroup_addmultiproperty(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, Lib3MF_uint64 nPropertyIDsBufferSize, const Lib3MF_uint32 * pPropertyIDsBuffer, Lib3MF_uint32 * pPropertyID); + +/** +* Sets the PropertyIDs of a MultiProperty. +* +* @param[in] pMultiPropertyGroup - MultiPropertyGroup instance. +* @param[in] nPropertyID - the PropertyID of the MultiProperty to be changed. +* @param[in] nPropertyIDsBufferSize - Number of elements in buffer +* @param[in] pPropertyIDsBuffer - uint32 buffer of The new PropertyIDs of the MultiProperty +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_multipropertygroup_setmultiproperty(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, Lib3MF_uint32 nPropertyID, Lib3MF_uint64 nPropertyIDsBufferSize, const Lib3MF_uint32 * pPropertyIDsBuffer); + +/** +* Obtains the PropertyIDs of a MultiProperty. +* +* @param[in] pMultiPropertyGroup - MultiPropertyGroup instance. +* @param[in] nPropertyID - the PropertyID of the MultiProperty to be queried. +* @param[in] nPropertyIDsBufferSize - Number of elements in buffer +* @param[out] pPropertyIDsNeededCount - will be filled with the count of the written elements, or needed buffer size. +* @param[out] pPropertyIDsBuffer - uint32 buffer of The PropertyIDs of the MultiProperty +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_multipropertygroup_getmultiproperty(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, Lib3MF_uint32 nPropertyID, const Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer); + +/** +* Removes a MultiProperty from this MultiPropertyGroup. +* +* @param[in] pMultiPropertyGroup - MultiPropertyGroup instance. +* @param[in] nPropertyID - the PropertyID of the MultiProperty to be removed. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_multipropertygroup_removemultiproperty(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, Lib3MF_uint32 nPropertyID); + +/** +* Retrieves the number of layers of this MultiPropertyGroup. +* +* @param[in] pMultiPropertyGroup - MultiPropertyGroup instance. +* @param[out] pCount - returns the number of layers +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_multipropertygroup_getlayercount(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, Lib3MF_uint32 * pCount); + +/** +* Adds a MultiPropertyLayer to this MultiPropertyGroup. +* +* @param[in] pMultiPropertyGroup - MultiPropertyGroup instance. +* @param[in] pTheLayer - The MultiPropertyLayer to add to this MultiPropertyGroup +* @param[out] pLayerIndex - returns the index of this MultiPropertyLayer +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_multipropertygroup_addlayer(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, const Lib3MF::sMultiPropertyLayer * pTheLayer, Lib3MF_uint32 * pLayerIndex); + +/** +* Obtains a MultiPropertyLayer of this MultiPropertyGroup. +* +* @param[in] pMultiPropertyGroup - MultiPropertyGroup instance. +* @param[in] nLayerIndex - The Index of the MultiPropertyLayer queried +* @param[out] pTheLayer - The MultiPropertyLayer with index LayerIndex within MultiPropertyGroup +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_multipropertygroup_getlayer(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, Lib3MF_uint32 nLayerIndex, Lib3MF::sMultiPropertyLayer * pTheLayer); + +/** +* Removes a MultiPropertyLayer from this MultiPropertyGroup. +* +* @param[in] pMultiPropertyGroup - MultiPropertyGroup instance. +* @param[in] nLayerIndex - The Index of the MultiPropertyLayer to be removed +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_multipropertygroup_removelayer(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, Lib3MF_uint32 nLayerIndex); + +/************************************************************************************************************************* + Class definition for Attachment +**************************************************************************************************************************/ + +/** +* Retrieves an attachment's package path. This function will be removed in a later release. +* +* @param[in] pAttachment - Attachment instance. +* @param[in] nPathBufferSize - size of the buffer (including trailing 0) +* @param[out] pPathNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pPathBuffer - buffer of returns the attachment's package path string, may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_attachment_getpath(Lib3MF_Attachment pAttachment, const Lib3MF_uint32 nPathBufferSize, Lib3MF_uint32* pPathNeededChars, char * pPathBuffer); + +/** +* Sets an attachment's package path. This function will be removed in a later release. +* +* @param[in] pAttachment - Attachment instance. +* @param[in] pPath - new path of the attachment. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_attachment_setpath(Lib3MF_Attachment pAttachment, const char * pPath); + +/** +* Returns the PackagePart that is this attachment. +* +* @param[in] pAttachment - Attachment instance. +* @param[out] pPackagePart - The PackagePart of this attachment. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_attachment_packagepart(Lib3MF_Attachment pAttachment, Lib3MF_PackagePart * pPackagePart); + +/** +* Retrieves an attachment's relationship type +* +* @param[in] pAttachment - Attachment instance. +* @param[in] nPathBufferSize - size of the buffer (including trailing 0) +* @param[out] pPathNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pPathBuffer - buffer of returns the attachment's package relationship type string, may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_attachment_getrelationshiptype(Lib3MF_Attachment pAttachment, const Lib3MF_uint32 nPathBufferSize, Lib3MF_uint32* pPathNeededChars, char * pPathBuffer); + +/** +* Sets an attachment's relationship type. +* +* @param[in] pAttachment - Attachment instance. +* @param[in] pPath - new relationship type string. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_attachment_setrelationshiptype(Lib3MF_Attachment pAttachment, const char * pPath); + +/** +* Writes out the attachment as file. +* +* @param[in] pAttachment - Attachment instance. +* @param[in] pFileName - file to write into. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_attachment_writetofile(Lib3MF_Attachment pAttachment, const char * pFileName); + +/** +* Reads an attachment from a file. The path of this file is only read when this attachment is being written as part of the 3MF packege, or via the WriteToFile or WriteToBuffer-methods. +* +* @param[in] pAttachment - Attachment instance. +* @param[in] pFileName - file to read from. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_attachment_readfromfile(Lib3MF_Attachment pAttachment, const char * pFileName); + +/** +* Reads a model and from the data provided by a callback function +* +* @param[in] pAttachment - Attachment instance. +* @param[in] pTheReadCallback - Callback to call for reading a data chunk +* @param[in] nStreamSize - number of bytes the callback returns +* @param[in] pTheSeekCallback - Callback to call for seeking in the stream. +* @param[in] pUserData - Userdata that is passed to the callback function +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_attachment_readfromcallback(Lib3MF_Attachment pAttachment, Lib3MF::ReadCallback pTheReadCallback, Lib3MF_uint64 nStreamSize, Lib3MF::SeekCallback pTheSeekCallback, Lib3MF_pvoid pUserData); + +/** +* Retrieves the size of the attachment stream +* +* @param[in] pAttachment - Attachment instance. +* @param[out] pStreamSize - the stream size +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_attachment_getstreamsize(Lib3MF_Attachment pAttachment, Lib3MF_uint64 * pStreamSize); + +/** +* Writes out the attachment into a buffer +* +* @param[in] pAttachment - Attachment instance. +* @param[in] nBufferBufferSize - Number of elements in buffer +* @param[out] pBufferNeededCount - will be filled with the count of the written elements, or needed buffer size. +* @param[out] pBufferBuffer - uint8 buffer of Buffer to write into +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_attachment_writetobuffer(Lib3MF_Attachment pAttachment, const Lib3MF_uint64 nBufferBufferSize, Lib3MF_uint64* pBufferNeededCount, Lib3MF_uint8 * pBufferBuffer); + +/** +* Reads an attachment from a memory buffer +* +* @param[in] pAttachment - Attachment instance. +* @param[in] nBufferBufferSize - Number of elements in buffer +* @param[in] pBufferBuffer - uint8 buffer of Buffer to read from +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_attachment_readfrombuffer(Lib3MF_Attachment pAttachment, Lib3MF_uint64 nBufferBufferSize, const Lib3MF_uint8 * pBufferBuffer); + +/************************************************************************************************************************* + Class definition for Texture2D +**************************************************************************************************************************/ + +/** +* Retrieves the attachment located at the path of the texture. +* +* @param[in] pTexture2D - Texture2D instance. +* @param[out] pAttachment - attachment that holds the texture's image information. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2d_getattachment(Lib3MF_Texture2D pTexture2D, Lib3MF_Attachment * pAttachment); + +/** +* Sets the texture's package path to the path of the attachment. +* +* @param[in] pTexture2D - Texture2D instance. +* @param[in] pAttachment - attachment that holds the texture's image information. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2d_setattachment(Lib3MF_Texture2D pTexture2D, Lib3MF_Attachment pAttachment); + +/** +* Retrieves a texture's content type. +* +* @param[in] pTexture2D - Texture2D instance. +* @param[out] pContentType - returns content type enum. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2d_getcontenttype(Lib3MF_Texture2D pTexture2D, Lib3MF::eTextureType * pContentType); + +/** +* Retrieves a texture's content type. +* +* @param[in] pTexture2D - Texture2D instance. +* @param[in] eContentType - new Content Type +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2d_setcontenttype(Lib3MF_Texture2D pTexture2D, Lib3MF::eTextureType eContentType); + +/** +* Retrieves a texture's tilestyle type. +* +* @param[in] pTexture2D - Texture2D instance. +* @param[out] pTileStyleU - returns tilestyle type enum. +* @param[out] pTileStyleV - returns tilestyle type enum. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2d_gettilestyleuv(Lib3MF_Texture2D pTexture2D, Lib3MF::eTextureTileStyle * pTileStyleU, Lib3MF::eTextureTileStyle * pTileStyleV); + +/** +* Sets a texture's tilestyle type. +* +* @param[in] pTexture2D - Texture2D instance. +* @param[in] eTileStyleU - new tilestyle type enum. +* @param[in] eTileStyleV - new tilestyle type enum. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2d_settilestyleuv(Lib3MF_Texture2D pTexture2D, Lib3MF::eTextureTileStyle eTileStyleU, Lib3MF::eTextureTileStyle eTileStyleV); + +/** +* Retrieves a texture's filter type. +* +* @param[in] pTexture2D - Texture2D instance. +* @param[out] pFilter - returns filter type enum. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2d_getfilter(Lib3MF_Texture2D pTexture2D, Lib3MF::eTextureFilter * pFilter); + +/** +* Sets a texture's filter type. +* +* @param[in] pTexture2D - Texture2D instance. +* @param[in] eFilter - sets new filter type enum. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2d_setfilter(Lib3MF_Texture2D pTexture2D, Lib3MF::eTextureFilter eFilter); + +/************************************************************************************************************************* + Class definition for BuildItem +**************************************************************************************************************************/ + +/** +* Retrieves the object resource associated to a build item +* +* @param[in] pBuildItem - BuildItem instance. +* @param[out] pObjectResource - returns the associated resource instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditem_getobjectresource(Lib3MF_BuildItem pBuildItem, Lib3MF_Object * pObjectResource); + +/** +* returns, whether a build item has a UUID and, if true, the build item's UUID +* +* @param[in] pBuildItem - BuildItem instance. +* @param[out] pHasUUID - flag whether the build item has a UUID +* @param[in] nUUIDBufferSize - size of the buffer (including trailing 0) +* @param[out] pUUIDNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pUUIDBuffer - buffer of the UUID as string of the form 'xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx', may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditem_getuuid(Lib3MF_BuildItem pBuildItem, bool * pHasUUID, const Lib3MF_uint32 nUUIDBufferSize, Lib3MF_uint32* pUUIDNeededChars, char * pUUIDBuffer); + +/** +* sets the build item's UUID +* +* @param[in] pBuildItem - BuildItem instance. +* @param[in] pUUID - the UUID as string of the form 'xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx' +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditem_setuuid(Lib3MF_BuildItem pBuildItem, const char * pUUID); + +/** +* Retrieves the object UniqueResourceID associated to a build item +* +* @param[in] pBuildItem - BuildItem instance. +* @param[out] pUniqueResourceID - returns the UniqueResourceID of the object +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditem_getobjectresourceid(Lib3MF_BuildItem pBuildItem, Lib3MF_uint32 * pUniqueResourceID); + +/** +* Checks, if a build item has a non-identity transformation matrix +* +* @param[in] pBuildItem - BuildItem instance. +* @param[out] pHasTransform - returns true, if the transformation matrix is not the identity +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditem_hasobjecttransform(Lib3MF_BuildItem pBuildItem, bool * pHasTransform); + +/** +* Retrieves a build item's transformation matrix. +* +* @param[in] pBuildItem - BuildItem instance. +* @param[out] pTransform - returns the transformation matrix +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditem_getobjecttransform(Lib3MF_BuildItem pBuildItem, Lib3MF::sTransform * pTransform); + +/** +* Sets a build item's transformation matrix. +* +* @param[in] pBuildItem - BuildItem instance. +* @param[in] pTransform - new transformation matrix +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditem_setobjecttransform(Lib3MF_BuildItem pBuildItem, const Lib3MF::sTransform * pTransform); + +/** +* Retrieves a build item's part number string +* +* @param[in] pBuildItem - BuildItem instance. +* @param[in] nPartNumberBufferSize - size of the buffer (including trailing 0) +* @param[out] pPartNumberNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pPartNumberBuffer - buffer of Returns a build item's part number string, may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditem_getpartnumber(Lib3MF_BuildItem pBuildItem, const Lib3MF_uint32 nPartNumberBufferSize, Lib3MF_uint32* pPartNumberNeededChars, char * pPartNumberBuffer); + +/** +* Sets a build item's part number string +* +* @param[in] pBuildItem - BuildItem instance. +* @param[in] pSetPartnumber - new part number string for referencing parts from the outside world +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditem_setpartnumber(Lib3MF_BuildItem pBuildItem, const char * pSetPartnumber); + +/** +* Returns the metadatagroup of this build item +* +* @param[in] pBuildItem - BuildItem instance. +* @param[out] pMetaDataGroup - returns an Instance of the metadatagroup of this build item +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditem_getmetadatagroup(Lib3MF_BuildItem pBuildItem, Lib3MF_MetaDataGroup * pMetaDataGroup); + +/** +* Returns the outbox of a build item +* +* @param[in] pBuildItem - BuildItem instance. +* @param[out] pOutbox - Outbox of this build item +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditem_getoutbox(Lib3MF_BuildItem pBuildItem, Lib3MF::sBox * pOutbox); + +/************************************************************************************************************************* + Class definition for BuildItemIterator +**************************************************************************************************************************/ + +/** +* Iterates to the next build item in the list. +* +* @param[in] pBuildItemIterator - BuildItemIterator instance. +* @param[out] pHasNext - Iterates to the next build item in the list. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditemiterator_movenext(Lib3MF_BuildItemIterator pBuildItemIterator, bool * pHasNext); + +/** +* Iterates to the previous build item in the list. +* +* @param[in] pBuildItemIterator - BuildItemIterator instance. +* @param[out] pHasPrevious - Iterates to the previous build item in the list. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditemiterator_moveprevious(Lib3MF_BuildItemIterator pBuildItemIterator, bool * pHasPrevious); + +/** +* Returns the build item the iterator points at. +* +* @param[in] pBuildItemIterator - BuildItemIterator instance. +* @param[out] pBuildItem - returns the build item instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditemiterator_getcurrent(Lib3MF_BuildItemIterator pBuildItemIterator, Lib3MF_BuildItem * pBuildItem); + +/** +* Creates a new build item iterator with the same build item list. +* +* @param[in] pBuildItemIterator - BuildItemIterator instance. +* @param[out] pOutBuildItemIterator - returns the cloned Iterator instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditemiterator_clone(Lib3MF_BuildItemIterator pBuildItemIterator, Lib3MF_BuildItemIterator * pOutBuildItemIterator); + +/** +* Returns the number of build items the iterator captures. +* +* @param[in] pBuildItemIterator - BuildItemIterator instance. +* @param[out] pCount - returns the number of build items the iterator captures. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditemiterator_count(Lib3MF_BuildItemIterator pBuildItemIterator, Lib3MF_uint64 * pCount); + +/************************************************************************************************************************* + Class definition for Slice +**************************************************************************************************************************/ + +/** +* Set all vertices of a slice. All polygons will be cleared. +* +* @param[in] pSlice - Slice instance. +* @param[in] nVerticesBufferSize - Number of elements in buffer +* @param[in] pVerticesBuffer - Position2D buffer of contains the positions. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_slice_setvertices(Lib3MF_Slice pSlice, Lib3MF_uint64 nVerticesBufferSize, const Lib3MF::sPosition2D * pVerticesBuffer); + +/** +* Get all vertices of a slice +* +* @param[in] pSlice - Slice instance. +* @param[in] nVerticesBufferSize - Number of elements in buffer +* @param[out] pVerticesNeededCount - will be filled with the count of the written elements, or needed buffer size. +* @param[out] pVerticesBuffer - Position2D buffer of contains the positions. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_slice_getvertices(Lib3MF_Slice pSlice, const Lib3MF_uint64 nVerticesBufferSize, Lib3MF_uint64* pVerticesNeededCount, Lib3MF::sPosition2D * pVerticesBuffer); + +/** +* Get the number of vertices in a slice +* +* @param[in] pSlice - Slice instance. +* @param[out] pCount - the number of vertices in the slice +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_slice_getvertexcount(Lib3MF_Slice pSlice, Lib3MF_uint64 * pCount); + +/** +* Add a new polygon to this slice +* +* @param[in] pSlice - Slice instance. +* @param[in] nIndicesBufferSize - Number of elements in buffer +* @param[in] pIndicesBuffer - uint32 buffer of the new indices of the new polygon +* @param[out] pIndex - the index of the new polygon +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_slice_addpolygon(Lib3MF_Slice pSlice, Lib3MF_uint64 nIndicesBufferSize, const Lib3MF_uint32 * pIndicesBuffer, Lib3MF_uint64 * pIndex); + +/** +* Get the number of polygons in the slice +* +* @param[in] pSlice - Slice instance. +* @param[out] pCount - the number of polygons in the slice +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_slice_getpolygoncount(Lib3MF_Slice pSlice, Lib3MF_uint64 * pCount); + +/** +* Set all indices of a polygon +* +* @param[in] pSlice - Slice instance. +* @param[in] nIndex - the index of the polygon to manipulate +* @param[in] nIndicesBufferSize - Number of elements in buffer +* @param[in] pIndicesBuffer - uint32 buffer of the new indices of the index-th polygon +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_slice_setpolygonindices(Lib3MF_Slice pSlice, Lib3MF_uint64 nIndex, Lib3MF_uint64 nIndicesBufferSize, const Lib3MF_uint32 * pIndicesBuffer); + +/** +* Get all vertices of a slice +* +* @param[in] pSlice - Slice instance. +* @param[in] nIndex - the index of the polygon to manipulate +* @param[in] nIndicesBufferSize - Number of elements in buffer +* @param[out] pIndicesNeededCount - will be filled with the count of the written elements, or needed buffer size. +* @param[out] pIndicesBuffer - uint32 buffer of the indices of the index-th polygon +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_slice_getpolygonindices(Lib3MF_Slice pSlice, Lib3MF_uint64 nIndex, const Lib3MF_uint64 nIndicesBufferSize, Lib3MF_uint64* pIndicesNeededCount, Lib3MF_uint32 * pIndicesBuffer); + +/** +* Get the number of vertices in a slice +* +* @param[in] pSlice - Slice instance. +* @param[in] nIndex - the index of the polygon to manipulate +* @param[out] pCount - the number of indices of the index-th polygon +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_slice_getpolygonindexcount(Lib3MF_Slice pSlice, Lib3MF_uint64 nIndex, Lib3MF_uint64 * pCount); + +/** +* Get the upper Z-Coordinate of this slice. +* +* @param[in] pSlice - Slice instance. +* @param[out] pZTop - the upper Z-Coordinate of this slice +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_slice_getztop(Lib3MF_Slice pSlice, Lib3MF_double * pZTop); + +/************************************************************************************************************************* + Class definition for SliceStack +**************************************************************************************************************************/ + +/** +* Get the lower Z-Coordinate of the slice stack. +* +* @param[in] pSliceStack - SliceStack instance. +* @param[out] pZBottom - the lower Z-Coordinate the slice stack +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_slicestack_getbottomz(Lib3MF_SliceStack pSliceStack, Lib3MF_double * pZBottom); + +/** +* Returns the number of slices +* +* @param[in] pSliceStack - SliceStack instance. +* @param[out] pCount - the number of slices +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_slicestack_getslicecount(Lib3MF_SliceStack pSliceStack, Lib3MF_uint64 * pCount); + +/** +* Query a slice from the slice stack +* +* @param[in] pSliceStack - SliceStack instance. +* @param[in] nSliceIndex - the index of the slice +* @param[out] pTheSlice - the Slice instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_slicestack_getslice(Lib3MF_SliceStack pSliceStack, Lib3MF_uint64 nSliceIndex, Lib3MF_Slice * pTheSlice); + +/** +* Returns the number of slices +* +* @param[in] pSliceStack - SliceStack instance. +* @param[in] dZTop - upper Z coordinate of the slice +* @param[out] pTheSlice - a new Slice instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_slicestack_addslice(Lib3MF_SliceStack pSliceStack, Lib3MF_double dZTop, Lib3MF_Slice * pTheSlice); + +/** +* Returns the number of slice refs +* +* @param[in] pSliceStack - SliceStack instance. +* @param[out] pCount - the number of slicereferences +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_slicestack_getslicerefcount(Lib3MF_SliceStack pSliceStack, Lib3MF_uint64 * pCount); + +/** +* Adds another existing slicestack as sliceref in this slicestack +* +* @param[in] pSliceStack - SliceStack instance. +* @param[in] pTheSliceStack - the slicestack to use as sliceref +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_slicestack_addslicestackreference(Lib3MF_SliceStack pSliceStack, Lib3MF_SliceStack pTheSliceStack); + +/** +* Adds another existing slicestack as sliceref in this slicestack +* +* @param[in] pSliceStack - SliceStack instance. +* @param[in] nSliceRefIndex - the index of the slice ref +* @param[out] pTheSliceStack - the slicestack that is used as sliceref +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_slicestack_getslicestackreference(Lib3MF_SliceStack pSliceStack, Lib3MF_uint64 nSliceRefIndex, Lib3MF_SliceStack * pTheSliceStack); + +/** +* Removes the indirection of slices via slice-refs, i.e. creates the slices of all slice refs of this SliceStack as actual slices of this SliceStack. All previously existing slices or slicerefs will be removed. +* +* @param[in] pSliceStack - SliceStack instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_slicestack_collapseslicereferences(Lib3MF_SliceStack pSliceStack); + +/** +* Sets the package path where this Slice should be stored. Input an empty string to reset the path +* +* @param[in] pSliceStack - SliceStack instance. +* @param[in] pPath - the package path where this Slice should be stored +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_slicestack_setownpath(Lib3MF_SliceStack pSliceStack, const char * pPath); + +/** +* Obtains the package path where this Slice should be stored. Returns an empty string if the slicestack is stored within the root model. +* +* @param[in] pSliceStack - SliceStack instance. +* @param[in] nPathBufferSize - size of the buffer (including trailing 0) +* @param[out] pPathNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pPathBuffer - buffer of the package path where this Slice will be stored, may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_slicestack_getownpath(Lib3MF_SliceStack pSliceStack, const Lib3MF_uint32 nPathBufferSize, Lib3MF_uint32* pPathNeededChars, char * pPathBuffer); + +/************************************************************************************************************************* + Class definition for Consumer +**************************************************************************************************************************/ + +/** +* Gets the consumerid +* +* @param[in] pConsumer - Consumer instance. +* @param[in] nConsumerIDBufferSize - size of the buffer (including trailing 0) +* @param[out] pConsumerIDNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pConsumerIDBuffer - buffer of A unique identifier for the consumers, may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_consumer_getconsumerid(Lib3MF_Consumer pConsumer, const Lib3MF_uint32 nConsumerIDBufferSize, Lib3MF_uint32* pConsumerIDNeededChars, char * pConsumerIDBuffer); + +/** +* Getts the keyid +* +* @param[in] pConsumer - Consumer instance. +* @param[in] nKeyIDBufferSize - size of the buffer (including trailing 0) +* @param[out] pKeyIDNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pKeyIDBuffer - buffer of The identifier for the key of this consumer, may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_consumer_getkeyid(Lib3MF_Consumer pConsumer, const Lib3MF_uint32 nKeyIDBufferSize, Lib3MF_uint32* pKeyIDNeededChars, char * pKeyIDBuffer); + +/** +* Gets the keyvalue associated with this consumer +* +* @param[in] pConsumer - Consumer instance. +* @param[in] nKeyValueBufferSize - size of the buffer (including trailing 0) +* @param[out] pKeyValueNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pKeyValueBuffer - buffer of The public key, when available, of this consumer, may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_consumer_getkeyvalue(Lib3MF_Consumer pConsumer, const Lib3MF_uint32 nKeyValueBufferSize, Lib3MF_uint32* pKeyValueNeededChars, char * pKeyValueBuffer); + +/************************************************************************************************************************* + Class definition for AccessRight +**************************************************************************************************************************/ + +/** +* Gets the consumer associated with this access right +* +* @param[in] pAccessRight - AccessRight instance. +* @param[out] pConsumer - The consumer instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_accessright_getconsumer(Lib3MF_AccessRight pAccessRight, Lib3MF_Consumer * pConsumer); + +/** +* Gets the associated encryption algorithm +* +* @param[in] pAccessRight - AccessRight instance. +* @param[out] pAlgorithm - The algorithm used for the key in this accessright +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_accessright_getwrappingalgorithm(Lib3MF_AccessRight pAccessRight, Lib3MF::eWrappingAlgorithm * pAlgorithm); + +/** +* Gets the associated mask generation function algorithm +* +* @param[in] pAccessRight - AccessRight instance. +* @param[out] pAlgorithm - The MFG1 algorithm +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_accessright_getmgfalgorithm(Lib3MF_AccessRight pAccessRight, Lib3MF::eMgfAlgorithm * pAlgorithm); + +/** +* Gets the digest method assoicated +* +* @param[in] pAccessRight - AccessRight instance. +* @param[out] pAlgorithm - The digest method for this accessright +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_accessright_getdigestmethod(Lib3MF_AccessRight pAccessRight, Lib3MF::eDigestMethod * pAlgorithm); + +/************************************************************************************************************************* + Class definition for ContentEncryptionParams +**************************************************************************************************************************/ + +/** +* Returns the encryption method to be used in this encryption process +* +* @param[in] pContentEncryptionParams - ContentEncryptionParams instance. +* @param[out] pAlgorithm - +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_contentencryptionparams_getencryptionalgorithm(Lib3MF_ContentEncryptionParams pContentEncryptionParams, Lib3MF::eEncryptionAlgorithm * pAlgorithm); + +/** +* Gets the key for the resource associated +* +* @param[in] pContentEncryptionParams - ContentEncryptionParams instance. +* @param[in] nByteDataBufferSize - Number of elements in buffer +* @param[out] pByteDataNeededCount - will be filled with the count of the written elements, or needed buffer size. +* @param[out] pByteDataBuffer - uint8 buffer of Pointer to a buffer where to place the key. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_contentencryptionparams_getkey(Lib3MF_ContentEncryptionParams pContentEncryptionParams, const Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64* pByteDataNeededCount, Lib3MF_uint8 * pByteDataBuffer); + +/** +* Gets the IV data +* +* @param[in] pContentEncryptionParams - ContentEncryptionParams instance. +* @param[in] nByteDataBufferSize - Number of elements in buffer +* @param[out] pByteDataNeededCount - will be filled with the count of the written elements, or needed buffer size. +* @param[out] pByteDataBuffer - uint8 buffer of Pointer to a buffer where to place the data. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_contentencryptionparams_getinitializationvector(Lib3MF_ContentEncryptionParams pContentEncryptionParams, const Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64* pByteDataNeededCount, Lib3MF_uint8 * pByteDataBuffer); + +/** +* A handler descriptor that uniquely identifies the context of the resource. Each resource will be assigned a different value +* +* @param[in] pContentEncryptionParams - ContentEncryptionParams instance. +* @param[in] nByteDataBufferSize - Number of elements in buffer +* @param[out] pByteDataNeededCount - will be filled with the count of the written elements, or needed buffer size. +* @param[out] pByteDataBuffer - uint8 buffer of Pointer to a buffer where to place the data. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_contentencryptionparams_getauthenticationtag(Lib3MF_ContentEncryptionParams pContentEncryptionParams, const Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64* pByteDataNeededCount, Lib3MF_uint8 * pByteDataBuffer); + +/** +* Sets the authentication tag +* +* @param[in] pContentEncryptionParams - ContentEncryptionParams instance. +* @param[in] nByteDataBufferSize - Number of elements in buffer +* @param[in] pByteDataBuffer - uint8 buffer of The authentication tag size +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_contentencryptionparams_setauthenticationtag(Lib3MF_ContentEncryptionParams pContentEncryptionParams, Lib3MF_uint64 nByteDataBufferSize, const Lib3MF_uint8 * pByteDataBuffer); + +/** +* A handler descriptor that uniquely identifies the context of the resource. Each resource will be assigned a different value +* +* @param[in] pContentEncryptionParams - ContentEncryptionParams instance. +* @param[in] nByteDataBufferSize - Number of elements in buffer +* @param[out] pByteDataNeededCount - will be filled with the count of the written elements, or needed buffer size. +* @param[out] pByteDataBuffer - uint8 buffer of Buffer where the data will be placed +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_contentencryptionparams_getadditionalauthenticationdata(Lib3MF_ContentEncryptionParams pContentEncryptionParams, const Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64* pByteDataNeededCount, Lib3MF_uint8 * pByteDataBuffer); + +/** +* A handler descriptor that uniquely identifies the context of the resource. Each resource will be assigned a different value +* +* @param[in] pContentEncryptionParams - ContentEncryptionParams instance. +* @param[out] pDescriptor - +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_contentencryptionparams_getdescriptor(Lib3MF_ContentEncryptionParams pContentEncryptionParams, Lib3MF_uint64 * pDescriptor); + +/** +* Gets the resourcedatagroup keyuuid +* +* @param[in] pContentEncryptionParams - ContentEncryptionParams instance. +* @param[in] nUUIDBufferSize - size of the buffer (including trailing 0) +* @param[out] pUUIDNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pUUIDBuffer - buffer of The resourcedatagroup keyuuid that may be use to reference an external key, may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_contentencryptionparams_getkeyuuid(Lib3MF_ContentEncryptionParams pContentEncryptionParams, const Lib3MF_uint32 nUUIDBufferSize, Lib3MF_uint32* pUUIDNeededChars, char * pUUIDBuffer); + +/************************************************************************************************************************* + Class definition for ResourceData +**************************************************************************************************************************/ + +/** +* Gets the encrypted part path +* +* @param[in] pResourceData - ResourceData instance. +* @param[out] pPath - The part path +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_resourcedata_getpath(Lib3MF_ResourceData pResourceData, Lib3MF_PackagePart * pPath); + +/** +* Gets the encryption algorithm used to encrypt this ResourceData +* +* @param[in] pResourceData - ResourceData instance. +* @param[out] pEncryptionAlgorithm - The encryption algorithm +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_resourcedata_getencryptionalgorithm(Lib3MF_ResourceData pResourceData, Lib3MF::eEncryptionAlgorithm * pEncryptionAlgorithm); + +/** +* Tells whether this ResourceData is compressed or not +* +* @param[in] pResourceData - ResourceData instance. +* @param[out] pCompression - The compression method +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_resourcedata_getcompression(Lib3MF_ResourceData pResourceData, Lib3MF::eCompression * pCompression); + +/** +* Tells whether this ResourceData is compressed or not +* +* @param[in] pResourceData - ResourceData instance. +* @param[in] nByteDataBufferSize - Number of elements in buffer +* @param[out] pByteDataNeededCount - will be filled with the count of the written elements, or needed buffer size. +* @param[out] pByteDataBuffer - uint8 buffer of The compression method +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_resourcedata_getadditionalauthenticationdata(Lib3MF_ResourceData pResourceData, const Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64* pByteDataNeededCount, Lib3MF_uint8 * pByteDataBuffer); + +/************************************************************************************************************************* + Class definition for ResourceDataGroup +**************************************************************************************************************************/ + +/** +* Sets the resourcedatagroup keyuuid +* +* @param[in] pResourceDataGroup - ResourceDataGroup instance. +* @param[in] nUUIDBufferSize - size of the buffer (including trailing 0) +* @param[out] pUUIDNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pUUIDBuffer - buffer of The new resourcedatagroup keyuuid., may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_resourcedatagroup_getkeyuuid(Lib3MF_ResourceDataGroup pResourceDataGroup, const Lib3MF_uint32 nUUIDBufferSize, Lib3MF_uint32* pUUIDNeededChars, char * pUUIDBuffer); + +/** +* Add accessright to resourcedatagroup element +* +* @param[in] pResourceDataGroup - ResourceDataGroup instance. +* @param[in] pConsumer - The Consumer reference +* @param[in] eWrappingAlgorithm - The key wrapping algorithm to be used +* @param[in] eMgfAlgorithm - The mask generation function to be used +* @param[in] eDigestMethod - The digest mechanism to be used +* @param[out] pTheAccessRight - The acess right instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_resourcedatagroup_addaccessright(Lib3MF_ResourceDataGroup pResourceDataGroup, Lib3MF_Consumer pConsumer, Lib3MF::eWrappingAlgorithm eWrappingAlgorithm, Lib3MF::eMgfAlgorithm eMgfAlgorithm, Lib3MF::eDigestMethod eDigestMethod, Lib3MF_AccessRight * pTheAccessRight); + +/** +* Finds the AccessRight associated with a Consumer +* +* @param[in] pResourceDataGroup - ResourceDataGroup instance. +* @param[in] pConsumer - The Consumer instance +* @param[out] pTheAccessRight - The AcessRight instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_resourcedatagroup_findaccessrightbyconsumer(Lib3MF_ResourceDataGroup pResourceDataGroup, Lib3MF_Consumer pConsumer, Lib3MF_AccessRight * pTheAccessRight); + +/** +* Removes access from a Consumer on this resource data group +* +* @param[in] pResourceDataGroup - ResourceDataGroup instance. +* @param[in] pConsumer - The Consumer instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_resourcedatagroup_removeaccessright(Lib3MF_ResourceDataGroup pResourceDataGroup, Lib3MF_Consumer pConsumer); + +/************************************************************************************************************************* + Class definition for KeyStore +**************************************************************************************************************************/ + +/** +* Adds a consumer to the keystore +* +* @param[in] pKeyStore - KeyStore instance. +* @param[in] pConsumerID - A unique identifier for the consumer +* @param[in] pKeyID - The id of the key of the consumer +* @param[in] pKeyValue - The public key for this consumer in PEM format +* @param[out] pConsumer - The consumer instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_addconsumer(Lib3MF_KeyStore pKeyStore, const char * pConsumerID, const char * pKeyID, const char * pKeyValue, Lib3MF_Consumer * pConsumer); + +/** +* Gets the number of consumers in the keystore +* +* @param[in] pKeyStore - KeyStore instance. +* @param[out] pCount - The consumer count +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_getconsumercount(Lib3MF_KeyStore pKeyStore, Lib3MF_uint64 * pCount); + +/** +* Get a consumer from the keystore +* +* @param[in] pKeyStore - KeyStore instance. +* @param[in] nConsumerIndex - The index of the consumer +* @param[out] pConsumer - The consumer instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_getconsumer(Lib3MF_KeyStore pKeyStore, Lib3MF_uint64 nConsumerIndex, Lib3MF_Consumer * pConsumer); + +/** +* Removes a consumer from the keystore +* +* @param[in] pKeyStore - KeyStore instance. +* @param[in] pConsumer - The consumer instance to remove +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_removeconsumer(Lib3MF_KeyStore pKeyStore, Lib3MF_Consumer pConsumer); + +/** +* Finds a consumer by ID +* +* @param[in] pKeyStore - KeyStore instance. +* @param[in] pConsumerID - The ID of the consumer +* @param[out] pConsumer - The consumer instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_findconsumer(Lib3MF_KeyStore pKeyStore, const char * pConsumerID, Lib3MF_Consumer * pConsumer); + +/** +* Gets the number of resource data group in the keysore +* +* @param[in] pKeyStore - KeyStore instance. +* @param[out] pCount - The number of resource data available +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_getresourcedatagroupcount(Lib3MF_KeyStore pKeyStore, Lib3MF_uint64 * pCount); + +/** +* Adds a resource data group into the keystore. +* +* @param[in] pKeyStore - KeyStore instance. +* @param[out] pResourceDataGroup - The resource data group instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_addresourcedatagroup(Lib3MF_KeyStore pKeyStore, Lib3MF_ResourceDataGroup * pResourceDataGroup); + +/** +* Gets a resource data group +* +* @param[in] pKeyStore - KeyStore instance. +* @param[in] nResourceDataIndex - The index of the resource data +* @param[out] pResourceDataGroup - The resource data group instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_getresourcedatagroup(Lib3MF_KeyStore pKeyStore, Lib3MF_uint64 nResourceDataIndex, Lib3MF_ResourceDataGroup * pResourceDataGroup); + +/** +* Removes a resource data group +* +* @param[in] pKeyStore - KeyStore instance. +* @param[in] pResourceDataGroup - The resource data group instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_removeresourcedatagroup(Lib3MF_KeyStore pKeyStore, Lib3MF_ResourceDataGroup pResourceDataGroup); + +/** +* Finds a resource data group that contains a particular resourcedata +* +* @param[in] pKeyStore - KeyStore instance. +* @param[in] pPartPath - The target path for the resourcedata hold by the resource data group +* @param[out] pResourceDataGroup - The data resource instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_findresourcedatagroup(Lib3MF_KeyStore pKeyStore, Lib3MF_PackagePart pPartPath, Lib3MF_ResourceDataGroup * pResourceDataGroup); + +/** +* Add resourcedata to resourcedatagroup element +* +* @param[in] pKeyStore - KeyStore instance. +* @param[in] pResourceDataGroup - The resource data group where to add this resource data +* @param[in] pPartPath - The path of the part to be encrypted +* @param[in] eAlgorithm - The encryption algorithm to be used to encrypt this resource +* @param[in] eCompression - Whether compression should be used prior to encryption +* @param[in] nAdditionalAuthenticationDataBufferSize - Number of elements in buffer +* @param[in] pAdditionalAuthenticationDataBuffer - uint8 buffer of Additional data to be encrypted along the contents for better security +* @param[out] pResourceData - The data resource instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_addresourcedata(Lib3MF_KeyStore pKeyStore, Lib3MF_ResourceDataGroup pResourceDataGroup, Lib3MF_PackagePart pPartPath, Lib3MF::eEncryptionAlgorithm eAlgorithm, Lib3MF::eCompression eCompression, Lib3MF_uint64 nAdditionalAuthenticationDataBufferSize, const Lib3MF_uint8 * pAdditionalAuthenticationDataBuffer, Lib3MF_ResourceData * pResourceData); + +/** +* Removes a resource data +* +* @param[in] pKeyStore - KeyStore instance. +* @param[in] pResourceData - The resource data to be removed +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_removeresourcedata(Lib3MF_KeyStore pKeyStore, Lib3MF_ResourceData pResourceData); + +/** +* Finds a resource data on this resource group +* +* @param[in] pKeyStore - KeyStore instance. +* @param[in] pResourcePath - The target path for the resourcedata +* @param[out] pResourceData - The resource data instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_findresourcedata(Lib3MF_KeyStore pKeyStore, Lib3MF_PackagePart pResourcePath, Lib3MF_ResourceData * pResourceData); + +/** +* Gets the number of resource data in the keysore +* +* @param[in] pKeyStore - KeyStore instance. +* @param[out] pCount - The number of resource data available +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_getresourcedatacount(Lib3MF_KeyStore pKeyStore, Lib3MF_uint64 * pCount); + +/** +* Gets a resource data +* +* @param[in] pKeyStore - KeyStore instance. +* @param[in] nResourceDataIndex - The index of the resource data +* @param[out] pResourceData - The data resource instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_getresourcedata(Lib3MF_KeyStore pKeyStore, Lib3MF_uint64 nResourceDataIndex, Lib3MF_ResourceData * pResourceData); + +/** +* Gets the keystore UUID +* +* @param[in] pKeyStore - KeyStore instance. +* @param[out] pHasUUID - flag whether the keystore has a UUID +* @param[in] nUUIDBufferSize - size of the buffer (including trailing 0) +* @param[out] pUUIDNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pUUIDBuffer - buffer of returns the keystore uuid., may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_getuuid(Lib3MF_KeyStore pKeyStore, bool * pHasUUID, const Lib3MF_uint32 nUUIDBufferSize, Lib3MF_uint32* pUUIDNeededChars, char * pUUIDBuffer); + +/** +* Sets the keystore UUID +* +* @param[in] pKeyStore - KeyStore instance. +* @param[in] pUUID - The new keystore uuid. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_setuuid(Lib3MF_KeyStore pKeyStore, const char * pUUID); + +/************************************************************************************************************************* + Class definition for Model +**************************************************************************************************************************/ + +/** +* Returns the PackagePart within the OPC package that holds the root model. +* +* @param[in] pModel - Model instance. +* @param[out] pRootModelPart - the PackagePart within the OPC package that holds the model-file +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_rootmodelpart(Lib3MF_Model pModel, Lib3MF_PackagePart * pRootModelPart); + +/** +* Returns a new PackagePart for use within the OPC package. +* +* @param[in] pModel - Model instance. +* @param[in] pAbsolutePath - the absolute Path (physical location) within the OPC package +* @param[out] pModelPart - the new PackagePart within the OPC package +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_findorcreatepackagepart(Lib3MF_Model pModel, const char * pAbsolutePath, Lib3MF_PackagePart * pModelPart); + +/** +* sets the units of a model. +* +* @param[in] pModel - Model instance. +* @param[in] eUnit - Unit enum value for the model unit +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_setunit(Lib3MF_Model pModel, Lib3MF::eModelUnit eUnit); + +/** +* returns the units of a model. +* +* @param[in] pModel - Model instance. +* @param[out] pUnit - Unit enum value for the model unit +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getunit(Lib3MF_Model pModel, Lib3MF::eModelUnit * pUnit); + +/** +* retrieves the language of a model +* +* @param[in] pModel - Model instance. +* @param[in] nLanguageBufferSize - size of the buffer (including trailing 0) +* @param[out] pLanguageNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pLanguageBuffer - buffer of language identifier, may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getlanguage(Lib3MF_Model pModel, const Lib3MF_uint32 nLanguageBufferSize, Lib3MF_uint32* pLanguageNeededChars, char * pLanguageBuffer); + +/** +* sets the language of a model +* +* @param[in] pModel - Model instance. +* @param[in] pLanguage - language identifier +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_setlanguage(Lib3MF_Model pModel, const char * pLanguage); + +/** +* creates a model writer instance for a specific file type +* +* @param[in] pModel - Model instance. +* @param[in] pWriterClass - string identifier for the file type +* @param[out] pWriterInstance - string identifier for the file type +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_querywriter(Lib3MF_Model pModel, const char * pWriterClass, Lib3MF_Writer * pWriterInstance); + +/** +* creates a model reader instance for a specific file type +* +* @param[in] pModel - Model instance. +* @param[in] pReaderClass - string identifier for the file type +* @param[out] pReaderInstance - string identifier for the file type +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_queryreader(Lib3MF_Model pModel, const char * pReaderClass, Lib3MF_Reader * pReaderInstance); + +/** +* finds a model texture by its UniqueResourceID +* +* @param[in] pModel - Model instance. +* @param[in] nUniqueResourceID - UniqueResourceID +* @param[out] pTextureInstance - returns the texture2d instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_gettexture2dbyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, Lib3MF_Texture2D * pTextureInstance); + +/** +* returns a Property's type +* +* @param[in] pModel - Model instance. +* @param[in] nUniqueResourceID - Resource ID of the Property to Query +* @param[out] pThePropertyType - returns a Property's type +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getpropertytypebyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, Lib3MF::ePropertyType * pThePropertyType); + +/** +* finds a model base material group by its UniqueResourceID +* +* @param[in] pModel - Model instance. +* @param[in] nUniqueResourceID - UniqueResourceID +* @param[out] pBaseMaterialGroupInstance - returns the BaseMaterialGroup instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getbasematerialgroupbyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, Lib3MF_BaseMaterialGroup * pBaseMaterialGroupInstance); + +/** +* finds a model texture2d group by its UniqueResourceID +* +* @param[in] pModel - Model instance. +* @param[in] nUniqueResourceID - UniqueResourceID +* @param[out] pTexture2DGroupInstance - returns the Texture2DGroup instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_gettexture2dgroupbyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, Lib3MF_Texture2DGroup * pTexture2DGroupInstance); + +/** +* finds a model CompositeMaterials by its UniqueResourceID +* +* @param[in] pModel - Model instance. +* @param[in] nUniqueResourceID - UniqueResourceID +* @param[out] pCompositeMaterialsInstance - returns the CompositeMaterials instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getcompositematerialsbyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, Lib3MF_CompositeMaterials * pCompositeMaterialsInstance); + +/** +* finds a model MultiPropertyGroup by its UniqueResourceID +* +* @param[in] pModel - Model instance. +* @param[in] nUniqueResourceID - UniqueResourceID +* @param[out] pMultiPropertyGroupInstance - returns the MultiPropertyGroup instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getmultipropertygroupbyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, Lib3MF_MultiPropertyGroup * pMultiPropertyGroupInstance); + +/** +* finds a mesh object by its UniqueResourceID +* +* @param[in] pModel - Model instance. +* @param[in] nUniqueResourceID - UniqueResourceID +* @param[out] pMeshObjectInstance - returns the mesh object instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getmeshobjectbyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, Lib3MF_MeshObject * pMeshObjectInstance); + +/** +* finds a components object by its UniqueResourceID +* +* @param[in] pModel - Model instance. +* @param[in] nUniqueResourceID - UniqueResourceID +* @param[out] pComponentsObjectInstance - returns the components object instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getcomponentsobjectbyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, Lib3MF_ComponentsObject * pComponentsObjectInstance); + +/** +* finds a model color group by its UniqueResourceID +* +* @param[in] pModel - Model instance. +* @param[in] nUniqueResourceID - UniqueResourceID +* @param[out] pColorGroupInstance - returns the ColorGroup instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getcolorgroupbyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, Lib3MF_ColorGroup * pColorGroupInstance); + +/** +* finds a model slicestack by its UniqueResourceID +* +* @param[in] pModel - Model instance. +* @param[in] nUniqueResourceID - UniqueResourceID +* @param[out] pSliceStacInstance - returns the slicestack instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getslicestackbyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, Lib3MF_SliceStack * pSliceStacInstance); + +/** +* returns, whether a build has a UUID and, if true, the build's UUID +* +* @param[in] pModel - Model instance. +* @param[out] pHasUUID - flag whether the build has a UUID +* @param[in] nUUIDBufferSize - size of the buffer (including trailing 0) +* @param[out] pUUIDNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pUUIDBuffer - buffer of the UUID as string of the form 'xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx', may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getbuilduuid(Lib3MF_Model pModel, bool * pHasUUID, const Lib3MF_uint32 nUUIDBufferSize, Lib3MF_uint32* pUUIDNeededChars, char * pUUIDBuffer); + +/** +* sets the build's UUID +* +* @param[in] pModel - Model instance. +* @param[in] pUUID - the UUID as string of the form 'xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx' +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_setbuilduuid(Lib3MF_Model pModel, const char * pUUID); + +/** +* creates a build item iterator instance with all build items. +* +* @param[in] pModel - Model instance. +* @param[out] pBuildItemIterator - returns the iterator instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getbuilditems(Lib3MF_Model pModel, Lib3MF_BuildItemIterator * pBuildItemIterator); + +/** +* Returns the outbox of a Model +* +* @param[in] pModel - Model instance. +* @param[out] pOutbox - Outbox of this Model +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getoutbox(Lib3MF_Model pModel, Lib3MF::sBox * pOutbox); + +/** +* creates a resource iterator instance with all resources. +* +* @param[in] pModel - Model instance. +* @param[out] pResourceIterator - returns the iterator instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getresources(Lib3MF_Model pModel, Lib3MF_ResourceIterator * pResourceIterator); + +/** +* creates a resource iterator instance with all object resources. +* +* @param[in] pModel - Model instance. +* @param[out] pResourceIterator - returns the iterator instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getobjects(Lib3MF_Model pModel, Lib3MF_ObjectIterator * pResourceIterator); + +/** +* creates a resource iterator instance with all mesh object resources. +* +* @param[in] pModel - Model instance. +* @param[out] pResourceIterator - returns the iterator instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getmeshobjects(Lib3MF_Model pModel, Lib3MF_MeshObjectIterator * pResourceIterator); + +/** +* creates a resource iterator instance with all components object resources. +* +* @param[in] pModel - Model instance. +* @param[out] pResourceIterator - returns the iterator instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getcomponentsobjects(Lib3MF_Model pModel, Lib3MF_ComponentsObjectIterator * pResourceIterator); + +/** +* creates a Texture2DIterator instance with all texture2d resources. +* +* @param[in] pModel - Model instance. +* @param[out] pResourceIterator - returns the iterator instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_gettexture2ds(Lib3MF_Model pModel, Lib3MF_Texture2DIterator * pResourceIterator); + +/** +* creates a BaseMaterialGroupIterator instance with all base material resources. +* +* @param[in] pModel - Model instance. +* @param[out] pResourceIterator - returns the iterator instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getbasematerialgroups(Lib3MF_Model pModel, Lib3MF_BaseMaterialGroupIterator * pResourceIterator); + +/** +* creates a ColorGroupIterator instance with all ColorGroup resources. +* +* @param[in] pModel - Model instance. +* @param[out] pResourceIterator - returns the iterator instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getcolorgroups(Lib3MF_Model pModel, Lib3MF_ColorGroupIterator * pResourceIterator); + +/** +* creates a Texture2DGroupIterator instance with all base material resources. +* +* @param[in] pModel - Model instance. +* @param[out] pResourceIterator - returns the iterator instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_gettexture2dgroups(Lib3MF_Model pModel, Lib3MF_Texture2DGroupIterator * pResourceIterator); + +/** +* creates a CompositeMaterialsIterator instance with all CompositeMaterials resources. +* +* @param[in] pModel - Model instance. +* @param[out] pResourceIterator - returns the iterator instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getcompositematerials(Lib3MF_Model pModel, Lib3MF_CompositeMaterialsIterator * pResourceIterator); + +/** +* creates a MultiPropertyGroupsIterator instance with all MultiPropertyGroup resources. +* +* @param[in] pModel - Model instance. +* @param[out] pResourceIterator - returns the iterator instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getmultipropertygroups(Lib3MF_Model pModel, Lib3MF_MultiPropertyGroupIterator * pResourceIterator); + +/** +* creates a resource iterator instance with all slice stack resources. +* +* @param[in] pModel - Model instance. +* @param[out] pResourceIterator - returns the iterator instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getslicestacks(Lib3MF_Model pModel, Lib3MF_SliceStackIterator * pResourceIterator); + +/** +* Merges all components and objects which are referenced by a build item into a mesh. The memory is duplicated and a new model is created. +* +* @param[in] pModel - Model instance. +* @param[out] pMergedModelInstance - returns the merged model instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_mergetomodel(Lib3MF_Model pModel, Lib3MF_Model * pMergedModelInstance); + +/** +* adds an empty mesh object to the model. +* +* @param[in] pModel - Model instance. +* @param[out] pMeshObjectInstance - returns the mesh object instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_addmeshobject(Lib3MF_Model pModel, Lib3MF_MeshObject * pMeshObjectInstance); + +/** +* adds an empty component object to the model. +* +* @param[in] pModel - Model instance. +* @param[out] pComponentsObjectInstance - returns the components object instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_addcomponentsobject(Lib3MF_Model pModel, Lib3MF_ComponentsObject * pComponentsObjectInstance); + +/** +* creates a new model slicestack by its id +* +* @param[in] pModel - Model instance. +* @param[in] dZBottom - Bottom Z value of the slicestack +* @param[out] pSliceStackInstance - returns the new slicestack instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_addslicestack(Lib3MF_Model pModel, Lib3MF_double dZBottom, Lib3MF_SliceStack * pSliceStackInstance); + +/** +* adds a texture2d resource to the model. Its path is given by that of an existing attachment. +* +* @param[in] pModel - Model instance. +* @param[in] pTextureAttachment - attachment containing the image data. +* @param[out] pTexture2DInstance - returns the new texture instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_addtexture2dfromattachment(Lib3MF_Model pModel, Lib3MF_Attachment pTextureAttachment, Lib3MF_Texture2D * pTexture2DInstance); + +/** +* adds an empty BaseMaterialGroup resource to the model. +* +* @param[in] pModel - Model instance. +* @param[out] pBaseMaterialGroupInstance - returns the new base material instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_addbasematerialgroup(Lib3MF_Model pModel, Lib3MF_BaseMaterialGroup * pBaseMaterialGroupInstance); + +/** +* adds an empty ColorGroup resource to the model. +* +* @param[in] pModel - Model instance. +* @param[out] pColorGroupInstance - returns the new ColorGroup instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_addcolorgroup(Lib3MF_Model pModel, Lib3MF_ColorGroup * pColorGroupInstance); + +/** +* adds an empty Texture2DGroup resource to the model. +* +* @param[in] pModel - Model instance. +* @param[in] pTexture2DInstance - The texture2D instance of the created Texture2DGroup. +* @param[out] pTexture2DGroupInstance - returns the new Texture2DGroup instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_addtexture2dgroup(Lib3MF_Model pModel, Lib3MF_Texture2D pTexture2DInstance, Lib3MF_Texture2DGroup * pTexture2DGroupInstance); + +/** +* adds an empty CompositeMaterials resource to the model. +* +* @param[in] pModel - Model instance. +* @param[in] pBaseMaterialGroupInstance - The BaseMaterialGroup instance of the created CompositeMaterials. +* @param[out] pCompositeMaterialsInstance - returns the new CompositeMaterials instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_addcompositematerials(Lib3MF_Model pModel, Lib3MF_BaseMaterialGroup pBaseMaterialGroupInstance, Lib3MF_CompositeMaterials * pCompositeMaterialsInstance); + +/** +* adds an empty MultiPropertyGroup resource to the model. +* +* @param[in] pModel - Model instance. +* @param[out] pMultiPropertyGroupInstance - returns the new MultiPropertyGroup instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_addmultipropertygroup(Lib3MF_Model pModel, Lib3MF_MultiPropertyGroup * pMultiPropertyGroupInstance); + +/** +* adds a build item to the model. +* +* @param[in] pModel - Model instance. +* @param[in] pObject - Object instance. +* @param[in] pTransform - Transformation matrix. +* @param[out] pBuildItemInstance - returns the build item instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_addbuilditem(Lib3MF_Model pModel, Lib3MF_Object pObject, const Lib3MF::sTransform * pTransform, Lib3MF_BuildItem * pBuildItemInstance); + +/** +* removes a build item from the model +* +* @param[in] pModel - Model instance. +* @param[in] pBuildItemInstance - Build item to remove. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_removebuilditem(Lib3MF_Model pModel, Lib3MF_BuildItem pBuildItemInstance); + +/** +* Returns the metadata of the model as MetaDataGroup +* +* @param[in] pModel - Model instance. +* @param[out] pTheMetaDataGroup - returns an Instance of the metadatagroup of the model +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getmetadatagroup(Lib3MF_Model pModel, Lib3MF_MetaDataGroup * pTheMetaDataGroup); + +/** +* adds an attachment stream to the model. The OPC part will be related to the model stream with a certain relationship type. +* +* @param[in] pModel - Model instance. +* @param[in] pURI - Path of the attachment +* @param[in] pRelationShipType - Relationship type of the attachment +* @param[out] pAttachmentInstance - Instance of the attachment object +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_addattachment(Lib3MF_Model pModel, const char * pURI, const char * pRelationShipType, Lib3MF_Attachment * pAttachmentInstance); + +/** +* Removes attachment from the model. +* +* @param[in] pModel - Model instance. +* @param[in] pAttachmentInstance - Attachment instance to remove +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_removeattachment(Lib3MF_Model pModel, Lib3MF_Attachment pAttachmentInstance); + +/** +* retrieves an attachment stream object from the model.. +* +* @param[in] pModel - Model instance. +* @param[in] nIndex - Index of the attachment stream +* @param[out] pAttachmentInstance - Instance of the attachment object +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getattachment(Lib3MF_Model pModel, Lib3MF_uint32 nIndex, Lib3MF_Attachment * pAttachmentInstance); + +/** +* retrieves an attachment stream object from the model. +* +* @param[in] pModel - Model instance. +* @param[in] pURI - Path URI in the package +* @param[out] pAttachmentInstance - Instance of the attachment object +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_findattachment(Lib3MF_Model pModel, const char * pURI, Lib3MF_Attachment * pAttachmentInstance); + +/** +* retrieves the number of attachments of the model. +* +* @param[in] pModel - Model instance. +* @param[out] pAttachmentCount - Returns the number of attachments. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getattachmentcount(Lib3MF_Model pModel, Lib3MF_uint32 * pAttachmentCount); + +/** +* Retrieve whether the OPC package contains a package thumbnail. +* +* @param[in] pModel - Model instance. +* @param[out] pHasThumbnail - returns whether the OPC package contains a package thumbnail +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_haspackagethumbnailattachment(Lib3MF_Model pModel, bool * pHasThumbnail); + +/** +* Create a new or the existing package thumbnail for the OPC package. +* +* @param[in] pModel - Model instance. +* @param[out] pAttachment - Instance of a new or the existing thumbnailattachment object. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_createpackagethumbnailattachment(Lib3MF_Model pModel, Lib3MF_Attachment * pAttachment); + +/** +* Get the attachment to the OPC package containing the package thumbnail. +* +* @param[in] pModel - Model instance. +* @param[out] pAttachment - Instance of the thumbnailattachment object or NULL. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getpackagethumbnailattachment(Lib3MF_Model pModel, Lib3MF_Attachment * pAttachment); + +/** +* Remove the attachment to the OPC package containing the package thumbnail. +* +* @param[in] pModel - Model instance. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_removepackagethumbnailattachment(Lib3MF_Model pModel); + +/** +* Adds a new Content Type to the model. +* +* @param[in] pModel - Model instance. +* @param[in] pExtension - File Extension +* @param[in] pContentType - Content Type Identifier +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_addcustomcontenttype(Lib3MF_Model pModel, const char * pExtension, const char * pContentType); + +/** +* Removes a custom Content Type from the model (UTF8 version). +* +* @param[in] pModel - Model instance. +* @param[in] pExtension - File Extension +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_removecustomcontenttype(Lib3MF_Model pModel, const char * pExtension); + +/** +* Sets the random number generator callback for use in the library +* +* @param[in] pModel - Model instance. +* @param[in] pTheCallback - The callback used to generate random numbers +* @param[in] pUserData - Userdata to be passed to the callback function +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_setrandomnumbercallback(Lib3MF_Model pModel, Lib3MF::RandomNumberCallback pTheCallback, Lib3MF_pvoid pUserData); + +/** +* Gets the keystore associated with this model +* +* @param[in] pModel - Model instance. +* @param[out] pKeyStore - The package keystore +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getkeystore(Lib3MF_Model pModel, Lib3MF_KeyStore * pKeyStore); + +/************************************************************************************************************************* + Global functions +**************************************************************************************************************************/ + +/** +* retrieves the binary version of this library. +* +* @param[out] pMajor - returns the major version of this library +* @param[out] pMinor - returns the minor version of this library +* @param[out] pMicro - returns the micro version of this library +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_getlibraryversion(Lib3MF_uint32 * pMajor, Lib3MF_uint32 * pMinor, Lib3MF_uint32 * pMicro); + +/** +* retrieves prerelease information of this library. +* +* @param[out] pHasPrereleaseInfo - Does the library provide prerelease version? +* @param[in] nPrereleaseInfoBufferSize - size of the buffer (including trailing 0) +* @param[out] pPrereleaseInfoNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pPrereleaseInfoBuffer - buffer of retrieves prerelease information of this library., may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_getprereleaseinformation(bool * pHasPrereleaseInfo, const Lib3MF_uint32 nPrereleaseInfoBufferSize, Lib3MF_uint32* pPrereleaseInfoNeededChars, char * pPrereleaseInfoBuffer); + +/** +* retrieves build information of this library. +* +* @param[out] pHasBuildInfo - Does the library provide build version? +* @param[in] nBuildInformationBufferSize - size of the buffer (including trailing 0) +* @param[out] pBuildInformationNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pBuildInformationBuffer - buffer of retrieves build information of this library., may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_getbuildinformation(bool * pHasBuildInfo, const Lib3MF_uint32 nBuildInformationBufferSize, Lib3MF_uint32* pBuildInformationNeededChars, char * pBuildInformationBuffer); + +/** +* retrieves whether a specification is supported, and if so, which version. +* +* @param[in] pSpecificationURL - URL of extension to check +* @param[out] pIsSupported - returns whether this specification is supported +* @param[out] pMajor - returns the major version of the extension (if IsSupported) +* @param[out] pMinor - returns the minor version of the extension (if IsSupported) +* @param[out] pMicro - returns the micro version of the extension (if IsSupported) +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_getspecificationversion(const char * pSpecificationURL, bool * pIsSupported, Lib3MF_uint32 * pMajor, Lib3MF_uint32 * pMinor, Lib3MF_uint32 * pMicro); + +/** +* creates an empty model instance. +* +* @param[out] pModel - returns an empty model instance +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_createmodel(Lib3MF_Model * pModel); + +/** +* releases shared ownership of an object instance +* +* @param[in] pInstance - the object instance to release +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_release(Lib3MF_Base pInstance); + +/** +* acquires shared ownership of an object instance +* +* @param[in] pInstance - the object instance to acquire +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_acquire(Lib3MF_Base pInstance); + +/** +* Sets the journal file path +* +* @param[in] pJournalPath - File name of the journal file +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_setjournal(const char * pJournalPath); + +/** +* Retrieves the last error string of an instance +* +* @param[in] pInstance - Object where the error occured. +* @param[in] nLastErrorStringBufferSize - size of the buffer (including trailing 0) +* @param[out] pLastErrorStringNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pLastErrorStringBuffer - buffer of Last Error String, may be NULL +* @param[out] pHasLastError - Returns if the instance has a last error. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_getlasterror(Lib3MF_Base pInstance, const Lib3MF_uint32 nLastErrorStringBufferSize, Lib3MF_uint32* pLastErrorStringNeededChars, char * pLastErrorStringBuffer, bool * pHasLastError); + +/** +* Returns the address of the SymbolLookupMethod +* +* @param[out] pSymbolLookupMethod - Address of the SymbolAddressMethod +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_getsymbollookupmethod(Lib3MF_pvoid * pSymbolLookupMethod); + +/** +* Return an English text for a progress identifier.|Note: this is the only function you can call from your callback function. +* +* @param[in] eTheProgressIdentifier - the progress identifier that is passed to the callback function +* @param[in] nProgressMessageBufferSize - size of the buffer (including trailing 0) +* @param[out] pProgressMessageNeededChars - will be filled with the count of the written bytes, or needed buffer size. +* @param[out] pProgressMessageBuffer - buffer of English text for the progress identifier, may be NULL +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_retrieveprogressmessage(Lib3MF::eProgressIdentifier eTheProgressIdentifier, const Lib3MF_uint32 nProgressMessageBufferSize, Lib3MF_uint32* pProgressMessageNeededChars, char * pProgressMessageBuffer); + +/** +* Creates a Color from uint8 RGBA values +* +* @param[in] nRed - Red value of color (0-255) +* @param[in] nGreen - Green value of color (0-255) +* @param[in] nBlue - Blue value of color (0-255) +* @param[in] nAlpha - Alpha value of color (0-255) +* @param[out] pTheColor - Assembled color +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_rgbatocolor(Lib3MF_uint8 nRed, Lib3MF_uint8 nGreen, Lib3MF_uint8 nBlue, Lib3MF_uint8 nAlpha, Lib3MF::sColor * pTheColor); + +/** +* Creates a Color from uint8 RGBA values +* +* @param[in] fRed - Red value of color (0-1) +* @param[in] fGreen - Green value of color (0-1) +* @param[in] fBlue - Blue value of color (0-1) +* @param[in] fAlpha - Alpha value of color (0-1) +* @param[out] pTheColor - Assembled color +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_floatrgbatocolor(Lib3MF_single fRed, Lib3MF_single fGreen, Lib3MF_single fBlue, Lib3MF_single fAlpha, Lib3MF::sColor * pTheColor); + +/** +* Calculates uint8-RGBA-values from a Color +* +* @param[in] pTheColor - Color to handle +* @param[out] pRed - Red value of color (0-255) +* @param[out] pGreen - Green value of color (0-255) +* @param[out] pBlue - Blue value of color (0-255) +* @param[out] pAlpha - Alpha value of color (0-255) +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_colortorgba(const Lib3MF::sColor * pTheColor, Lib3MF_uint8 * pRed, Lib3MF_uint8 * pGreen, Lib3MF_uint8 * pBlue, Lib3MF_uint8 * pAlpha); + +/** +* Calculates float-RGBA-values from a Color +* +* @param[in] pTheColor - Color to handle +* @param[out] pRed - Red value of color (0-1) +* @param[out] pGreen - Green value of color (0-1) +* @param[out] pBlue - Blue value of color (0-1) +* @param[out] pAlpha - Alpha value of color (0-1) +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_colortofloatrgba(const Lib3MF::sColor * pTheColor, Lib3MF_single * pRed, Lib3MF_single * pGreen, Lib3MF_single * pBlue, Lib3MF_single * pAlpha); + +/** +* Creates an identity transform +* +* @param[out] pTransform - Transformation matrix. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_getidentitytransform(Lib3MF::sTransform * pTransform); + +/** +* Creates a uniform scale transform +* +* @param[in] fFactor - Factor in X, Y and Z +* @param[out] pTransform - Transformation matrix. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_getuniformscaletransform(Lib3MF_single fFactor, Lib3MF::sTransform * pTransform); + +/** +* Creates a scale transform +* +* @param[in] fFactorX - Factor in X +* @param[in] fFactorY - Factor in Y +* @param[in] fFactorZ - Factor in Z +* @param[out] pTransform - Transformation matrix. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_getscaletransform(Lib3MF_single fFactorX, Lib3MF_single fFactorY, Lib3MF_single fFactorZ, Lib3MF::sTransform * pTransform); + +/** +* Creates an translation transform +* +* @param[in] fVectorX - Translation in X +* @param[in] fVectorY - Translation in Y +* @param[in] fVectorZ - Translation in Z +* @param[out] pTransform - Transformation matrix. +* @return error code or 0 (success) +*/ +LIB3MF_DECLSPEC Lib3MFResult lib3mf_gettranslationtransform(Lib3MF_single fVectorX, Lib3MF_single fVectorY, Lib3MF_single fVectorZ, Lib3MF::sTransform * pTransform); + +} + +#endif // __LIB3MF_HEADER_CPP + diff --git a/Include/lib3mf_interfaceexception.hpp b/Include/lib3mf_interfaceexception.hpp new file mode 100644 index 0000000..ef6211c --- /dev/null +++ b/Include/lib3mf_interfaceexception.hpp @@ -0,0 +1,80 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +This file has been generated by the Automatic Component Toolkit (ACT) version 1.6.0. + +Abstract: This is an autogenerated C++ Header file with the basic internal + exception type in order to allow an easy use of the 3MF Library + +Interface version: 2.2.0 + +*/ + +#ifndef __LIB3MF_INTERFACEEXCEPTION_HEADER +#define __LIB3MF_INTERFACEEXCEPTION_HEADER + +#include +#include +#include "lib3mf_types.hpp" + +/************************************************************************************************************************* + Class ELib3MFInterfaceException +**************************************************************************************************************************/ + + +class ELib3MFInterfaceException : public std::exception { +protected: + /** + * Error code for the Exception. + */ + Lib3MFResult m_errorCode; + /** + * Error message for the Exception. + */ + std::string m_errorMessage; + +public: + /** + * Exception Constructor. + */ + ELib3MFInterfaceException(Lib3MFResult errorCode); + + /** + * Custom Exception Constructor. + */ + ELib3MFInterfaceException(Lib3MFResult errorCode, std::string errorMessage); + + /** + * Returns error code + */ + Lib3MFResult getErrorCode(); + /** + * Returns error message + */ + const char* what() const override; +}; + +#endif // __LIB3MF_INTERFACEEXCEPTION_HEADER diff --git a/Include/lib3mf_interfacejournal.hpp b/Include/lib3mf_interfacejournal.hpp new file mode 100644 index 0000000..6c9bffb --- /dev/null +++ b/Include/lib3mf_interfacejournal.hpp @@ -0,0 +1,142 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +This file has been generated by the Automatic Component Toolkit (ACT) version 1.6.0. + +Abstract: This is an autogenerated C++ header file in order to allow easy +development of the 3MF Library. It provides an automatic Journaling mechanism for the library implementation. + +Interface version: 2.2.0 + +*/ + +#ifndef __LIB3MF_INTERFACEJOURNAL_HEADER +#define __LIB3MF_INTERFACEJOURNAL_HEADER + +#include +#include +#include +#include +#include +#include +#include +#include "lib3mf_types.hpp" + +/************************************************************************************************************************* + Class CLib3MFInterfaceJournal +**************************************************************************************************************************/ + +class CLib3MFInterfaceJournal; + +class CLib3MFInterfaceJournalEntry { + + protected: + + CLib3MFInterfaceJournal * m_pJournal; + Lib3MFResult m_ErrorCode; + std::string m_sClassName; + std::string m_sMethodName; + std::string m_sInstanceHandle; + Lib3MF_uint64 m_nInitTimeStamp; + Lib3MF_uint64 m_nFinishTimeStamp; + std::list, std::string>> m_sParameters; + std::list, std::string>> m_sResultValues; + + std::string getXMLString(); + void addParameter (const std::string & sName, const std::string & sParameterType, const std::string & sParameterValue); + void addResult (const std::string & sName, const std::string & sResultType, const std::string & sResultValue); + + public: + CLib3MFInterfaceJournalEntry(CLib3MFInterfaceJournal * pJournal, std::string sClassName, std::string sMethodName, Lib3MFHandle pInstanceHandle); + ~CLib3MFInterfaceJournalEntry(); + + void writeSuccess (); + void writeError (Lib3MFResult nErrorCode); + + void addBooleanParameter(const std::string & sName, const bool bValue); + void addUInt8Parameter(const std::string & sName, const Lib3MF_uint8 nValue); + void addUInt16Parameter(const std::string & sName, const Lib3MF_uint16 nValue); + void addUInt32Parameter(const std::string & sName, const Lib3MF_uint32 nValue); + void addUInt64Parameter(const std::string & sName, const Lib3MF_uint64 nValue); + void addInt8Parameter(const std::string & sName, const Lib3MF_int8 nValue); + void addInt16Parameter(const std::string & sName, const Lib3MF_int16 nValue); + void addInt32Parameter(const std::string & sName, const Lib3MF_int32 nValue); + void addInt64Parameter(const std::string & sName, const Lib3MF_int64 nValue); + void addSingleParameter(const std::string & sName, const Lib3MF_single fValue); + void addDoubleParameter(const std::string & sName, const Lib3MF_double dValue); + void addPointerParameter(const std::string & sName, const Lib3MF_pvoid pValue); + void addStringParameter(const std::string & sName, const char * pValue); + void addHandleParameter(const std::string & sName, const Lib3MFHandle pHandle); + void addEnumParameter(const std::string & sName, const std::string & sEnumType, const Lib3MF_int32 nValue); + + void addBooleanResult(const std::string & sName, const bool bValue); + void addUInt8Result(const std::string & sName, const Lib3MF_uint8 nValue); + void addUInt16Result(const std::string & sName, const Lib3MF_uint16 nValue); + void addUInt32Result(const std::string & sName, const Lib3MF_uint32 nValue); + void addUInt64Result(const std::string & sName, const Lib3MF_uint64 nValue); + void addInt8Result(const std::string & sName, const Lib3MF_int8 nValue); + void addInt16Result(const std::string & sName, const Lib3MF_int16 nValue); + void addInt32Result(const std::string & sName, const Lib3MF_int32 nValue); + void addInt64Result(const std::string & sName, const Lib3MF_int64 nValue); + void addSingleResult(const std::string & sName, const Lib3MF_single fValue); + void addDoubleResult(const std::string & sName, const Lib3MF_double dValue); + void addPointerResult(const std::string & sName, const Lib3MF_pvoid pValue); + void addStringResult(const std::string & sName, const char * pValue); + void addHandleResult(const std::string & sName, const Lib3MFHandle pHandle); + void addEnumResult(const std::string & sName, const std::string & sEnumType, const Lib3MF_int32 nValue); + +friend class CLib3MFInterfaceJournal; + +}; + +typedef std::shared_ptr PLib3MFInterfaceJournalEntry; + + + +class CLib3MFInterfaceJournal { + + protected: + + std::string m_sFileName; + std::mutex m_Mutex; + std::ofstream m_Stream; + std::chrono::time_point m_StartTime; + void writeEntry (CLib3MFInterfaceJournalEntry * pEntry); + Lib3MF_uint64 getTimeStamp (); + + public: + + CLib3MFInterfaceJournal (const std::string & sFileName); + ~CLib3MFInterfaceJournal (); + PLib3MFInterfaceJournalEntry beginClassMethod (const Lib3MFHandle pHandle, const std::string & sClassName, const std::string & sMethodName); + PLib3MFInterfaceJournalEntry beginStaticFunction (const std::string & sMethodName); + friend class CLib3MFInterfaceJournalEntry; +}; + +typedef std::shared_ptr PLib3MFInterfaceJournal; + +#endif // __LIB3MF_INTERFACEJOURNAL_HEADER + diff --git a/Include/lib3mf_interfaces.hpp b/Include/lib3mf_interfaces.hpp new file mode 100644 index 0000000..3e71cc1 --- /dev/null +++ b/Include/lib3mf_interfaces.hpp @@ -0,0 +1,3011 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +This file has been generated by the Automatic Component Toolkit (ACT) version 1.6.0. + +Abstract: This is an autogenerated C++ header file in order to allow easy +development of the 3MF Library. The implementer of the 3MF Library needs to +derive concrete classes from the abstract classes in this header. + +Interface version: 2.2.0 + +*/ + + +#ifndef __LIB3MF_CPPINTERFACES +#define __LIB3MF_CPPINTERFACES + +#include +#include + +#include "lib3mf_types.hpp" + + + +namespace Lib3MF { +namespace Impl { + +/** + Forward declarations of class interfaces +*/ +class IBase; +class IWriter; +class IReader; +class IPackagePart; +class IResource; +class IResourceIterator; +class ISliceStackIterator; +class IObjectIterator; +class IMeshObjectIterator; +class IComponentsObjectIterator; +class ITexture2DIterator; +class IBaseMaterialGroupIterator; +class IColorGroupIterator; +class ITexture2DGroupIterator; +class ICompositeMaterialsIterator; +class IMultiPropertyGroupIterator; +class IMetaData; +class IMetaDataGroup; +class IObject; +class IMeshObject; +class IBeamLattice; +class IComponent; +class IComponentsObject; +class IBeamSet; +class IBaseMaterialGroup; +class IColorGroup; +class ITexture2DGroup; +class ICompositeMaterials; +class IMultiPropertyGroup; +class IAttachment; +class ITexture2D; +class IBuildItem; +class IBuildItemIterator; +class ISlice; +class ISliceStack; +class IConsumer; +class IAccessRight; +class IContentEncryptionParams; +class IResourceData; +class IResourceDataGroup; +class IKeyStore; +class IModel; + + + +/************************************************************************************************************************* + Class interface for Base +**************************************************************************************************************************/ + +class IBase { +public: + /** + * IBase::~IBase - virtual destructor of IBase + */ + virtual ~IBase() {}; + + /** + * IBase::ReleaseBaseClassInterface - Releases ownership of a base class interface. Deletes the reference, if necessary. + * @param[in] pIBase - The base class instance to release + */ + static void ReleaseBaseClassInterface(IBase* pIBase) + { + if (pIBase) { + pIBase->DecRefCount(); + } + }; + + /** + * IBase::AcquireBaseClassInterface - Acquires shared ownership of a base class interface. + * @param[in] pIBase - The base class instance to acquire + */ + static void AcquireBaseClassInterface(IBase* pIBase) + { + if (pIBase) { + pIBase->IncRefCount(); + } + }; + + + /** + * IBase::GetLastErrorMessage - Returns the last error registered of this class instance + * @param[out] sErrorMessage - Message of the last error registered + * @return Has an error been registered already + */ + virtual bool GetLastErrorMessage(std::string & sErrorMessage) = 0; + + /** + * IBase::ClearErrorMessages - Clears all registered messages of this class instance + */ + virtual void ClearErrorMessages() = 0; + + /** + * IBase::RegisterErrorMessage - Registers an error message with this class instance + * @param[in] sErrorMessage - Error message to register + */ + virtual void RegisterErrorMessage(const std::string & sErrorMessage) = 0; + + /** + * IBase::IncRefCount - Increases the reference count of a class instance + */ + virtual void IncRefCount() = 0; + + /** + * IBase::DecRefCount - Decreases the reference count of a class instance and free releases it, if the last reference has been removed + * @return Has the object been released + */ + virtual bool DecRefCount() = 0; +}; + + +/** + Definition of a shared pointer class for IBase +*/ +template +class IBaseSharedPtr : public std::shared_ptr +{ +public: + explicit IBaseSharedPtr(T* t = nullptr) + : std::shared_ptr(t, IBase::ReleaseBaseClassInterface) + { + t->IncRefCount(); + } + + // Reset function, as it also needs to properly set the deleter. + void reset(T* t = nullptr) + { + std::shared_ptr::reset(t, IBase::ReleaseBaseClassInterface); + } + + // Get-function that increases the Base class's reference count + T* getCoOwningPtr() + { + T* t = this->get(); + t->IncRefCount(); + return t; + } +}; + + +typedef IBaseSharedPtr PIBase; + + +/************************************************************************************************************************* + Class interface for Writer +**************************************************************************************************************************/ + +class IWriter : public virtual IBase { +public: + /** + * IWriter::WriteToFile - Writes out the model as file. The file type is specified by the Model Writer class. + * @param[in] sFilename - Filename to write into + */ + virtual void WriteToFile(const std::string & sFilename) = 0; + + /** + * IWriter::GetStreamSize - Retrieves the size of the full 3MF file stream. + * @return the stream size + */ + virtual Lib3MF_uint64 GetStreamSize() = 0; + + /** + * IWriter::WriteToBuffer - Writes out the 3MF file into a memory buffer + * @param[in] nBufferBufferSize - Number of elements in buffer + * @param[out] pBufferNeededCount - will be filled with the count of the written structs, or needed buffer size. + * @param[out] pBufferBuffer - uint8 buffer of buffer to write into + */ + virtual void WriteToBuffer(Lib3MF_uint64 nBufferBufferSize, Lib3MF_uint64* pBufferNeededCount, Lib3MF_uint8 * pBufferBuffer) = 0; + + /** + * IWriter::WriteToCallback - Writes out the model and passes the data to a provided callback function. The file type is specified by the Model Writer class. + * @param[in] pTheWriteCallback - callback function + * @param[in] pTheSeekCallback - callback function + * @param[in] nUserData - Userdata that is passed to the callback function + */ + virtual void WriteToCallback(const Lib3MF::WriteCallback pTheWriteCallback, const Lib3MF::SeekCallback pTheSeekCallback, const Lib3MF_pvoid pUserData) = 0; + + /** + * IWriter::SetProgressCallback - Set the progress callback for calls to this writer + * @param[in] pProgressCallback - callback function + * @param[in] nUserData - pointer to arbitrary user data that is passed without modification to the callback. + */ + virtual void SetProgressCallback(const Lib3MF::ProgressCallback pProgressCallback, const Lib3MF_pvoid pUserData) = 0; + + /** + * IWriter::GetDecimalPrecision - Returns the number of digits after the decimal point to be written in each vertex coordinate-value. + * @return The number of digits to be written in each vertex coordinate-value after the decimal point. + */ + virtual Lib3MF_uint32 GetDecimalPrecision() = 0; + + /** + * IWriter::SetDecimalPrecision - Sets the number of digits after the decimal point to be written in each vertex coordinate-value. + * @param[in] nDecimalPrecision - The number of digits to be written in each vertex coordinate-value after the decimal point. + */ + virtual void SetDecimalPrecision(const Lib3MF_uint32 nDecimalPrecision) = 0; + + /** + * IWriter::SetStrictModeActive - Activates (deactivates) the strict mode of the reader. + * @param[in] bStrictModeActive - flag whether strict mode is active or not. + */ + virtual void SetStrictModeActive(const bool bStrictModeActive) = 0; + + /** + * IWriter::GetStrictModeActive - Queries whether the strict mode of the reader is active or not + * @return returns flag whether strict mode is active or not. + */ + virtual bool GetStrictModeActive() = 0; + + /** + * IWriter::GetWarning - Returns Warning and Error Information of the read process + * @param[in] nIndex - Index of the Warning. Valid values are 0 to WarningCount - 1 + * @param[out] nErrorCode - filled with the error code of the warning + * @return the message of the warning + */ + virtual std::string GetWarning(const Lib3MF_uint32 nIndex, Lib3MF_uint32 & nErrorCode) = 0; + + /** + * IWriter::GetWarningCount - Returns Warning and Error Count of the read process + * @return filled with the count of the occurred warnings. + */ + virtual Lib3MF_uint32 GetWarningCount() = 0; + + /** + * IWriter::AddKeyWrappingCallback - Registers a callback to deal with data key encryption/decryption from keystore + * @param[in] sConsumerID - The ConsumerID to register for + * @param[in] pTheCallback - callback function + * @param[in] nUserData - Userdata that is passed to the callback function + */ + virtual void AddKeyWrappingCallback(const std::string & sConsumerID, const Lib3MF::KeyWrappingCallback pTheCallback, const Lib3MF_pvoid pUserData) = 0; + + /** + * IWriter::SetContentEncryptionCallback - Registers a callback to deal with encryption of content + * @param[in] pTheCallback - callback function + * @param[in] nUserData - Userdata that is passed to the callback function + */ + virtual void SetContentEncryptionCallback(const Lib3MF::ContentEncryptionCallback pTheCallback, const Lib3MF_pvoid pUserData) = 0; + +}; + +typedef IBaseSharedPtr PIWriter; + + +/************************************************************************************************************************* + Class interface for Reader +**************************************************************************************************************************/ + +class IReader : public virtual IBase { +public: + /** + * IReader::ReadFromFile - Reads a model from a file. The file type is specified by the Model Reader class + * @param[in] sFilename - Filename to read from + */ + virtual void ReadFromFile(const std::string & sFilename) = 0; + + /** + * IReader::ReadFromBuffer - Reads a model from a memory buffer. + * @param[in] nBufferBufferSize - Number of elements in buffer + * @param[in] pBufferBuffer - Buffer to read from + */ + virtual void ReadFromBuffer(const Lib3MF_uint64 nBufferBufferSize, const Lib3MF_uint8 * pBufferBuffer) = 0; + + /** + * IReader::ReadFromCallback - Reads a model and from the data provided by a callback function + * @param[in] pTheReadCallback - callback function + * @param[in] nStreamSize - number of bytes the callback returns + * @param[in] pTheSeekCallback - callback function + * @param[in] nUserData - Userdata that is passed to the callback function + */ + virtual void ReadFromCallback(const Lib3MF::ReadCallback pTheReadCallback, const Lib3MF_uint64 nStreamSize, const Lib3MF::SeekCallback pTheSeekCallback, const Lib3MF_pvoid pUserData) = 0; + + /** + * IReader::SetProgressCallback - Set the progress callback for calls to this writer + * @param[in] pProgressCallback - callback function + * @param[in] nUserData - pointer to arbitrary user data that is passed without modification to the callback. + */ + virtual void SetProgressCallback(const Lib3MF::ProgressCallback pProgressCallback, const Lib3MF_pvoid pUserData) = 0; + + /** + * IReader::AddRelationToRead - Adds a relationship type which shall be read as attachment in memory while loading + * @param[in] sRelationShipType - String of the relationship type + */ + virtual void AddRelationToRead(const std::string & sRelationShipType) = 0; + + /** + * IReader::RemoveRelationToRead - Removes a relationship type which shall be read as attachment in memory while loading + * @param[in] sRelationShipType - String of the relationship type + */ + virtual void RemoveRelationToRead(const std::string & sRelationShipType) = 0; + + /** + * IReader::SetStrictModeActive - Activates (deactivates) the strict mode of the reader. + * @param[in] bStrictModeActive - flag whether strict mode is active or not. + */ + virtual void SetStrictModeActive(const bool bStrictModeActive) = 0; + + /** + * IReader::GetStrictModeActive - Queries whether the strict mode of the reader is active or not + * @return returns flag whether strict mode is active or not. + */ + virtual bool GetStrictModeActive() = 0; + + /** + * IReader::GetWarning - Returns Warning and Error Information of the read process + * @param[in] nIndex - Index of the Warning. Valid values are 0 to WarningCount - 1 + * @param[out] nErrorCode - filled with the error code of the warning + * @return the message of the warning + */ + virtual std::string GetWarning(const Lib3MF_uint32 nIndex, Lib3MF_uint32 & nErrorCode) = 0; + + /** + * IReader::GetWarningCount - Returns Warning and Error Count of the read process + * @return filled with the count of the occurred warnings. + */ + virtual Lib3MF_uint32 GetWarningCount() = 0; + + /** + * IReader::AddKeyWrappingCallback - Registers a callback to deal with key wrapping mechanism from keystore + * @param[in] sConsumerID - The ConsumerID to register for + * @param[in] pTheCallback - callback function + * @param[in] nUserData - Userdata that is passed to the callback function + */ + virtual void AddKeyWrappingCallback(const std::string & sConsumerID, const Lib3MF::KeyWrappingCallback pTheCallback, const Lib3MF_pvoid pUserData) = 0; + + /** + * IReader::SetContentEncryptionCallback - Registers a callback to deal with encryption of content + * @param[in] pTheCallback - callback function + * @param[in] nUserData - Userdata that is passed to the callback function + */ + virtual void SetContentEncryptionCallback(const Lib3MF::ContentEncryptionCallback pTheCallback, const Lib3MF_pvoid pUserData) = 0; + +}; + +typedef IBaseSharedPtr PIReader; + + +/************************************************************************************************************************* + Class interface for PackagePart +**************************************************************************************************************************/ + +class IPackagePart : public virtual IBase { +public: + /** + * IPackagePart::GetPath - Returns the absolute path of this PackagePart. + * @return Returns the absolute path of this PackagePart + */ + virtual std::string GetPath() = 0; + + /** + * IPackagePart::SetPath - Sets the absolute path of this PackagePart. + * @param[in] sPath - Sets the absolute path of this PackagePart. + */ + virtual void SetPath(const std::string & sPath) = 0; + +}; + +typedef IBaseSharedPtr PIPackagePart; + + +/************************************************************************************************************************* + Class interface for Resource +**************************************************************************************************************************/ + +class IResource : public virtual IBase { +public: + /** + * IResource::GetResourceID - Retrieves the unique id of this resource within a package. This function will be removed in a later release in favor of GetUniqueResourceID + * @return Retrieves the unique id of this resource within a package. + */ + virtual Lib3MF_uint32 GetResourceID() = 0; + + /** + * IResource::GetUniqueResourceID - Retrieves the unique id of this resource within a package. + * @return Retrieves the unique id of this resource within a package. + */ + virtual Lib3MF_uint32 GetUniqueResourceID() = 0; + + /** + * IResource::PackagePart - Returns the PackagePart within which this resource resides + * @return the PackagePart within which this resource resides. + */ + virtual IPackagePart * PackagePart() = 0; + + /** + * IResource::SetPackagePart - Sets the new PackagePart within which this resource resides + * @param[in] pPackagePart - the new PackagePart within which this resource resides. + */ + virtual void SetPackagePart(IPackagePart* pPackagePart) = 0; + + /** + * IResource::GetModelResourceID - Retrieves the id of this resource within a model. + * @return Retrieves the id of this resource within a model. + */ + virtual Lib3MF_uint32 GetModelResourceID() = 0; + +}; + +typedef IBaseSharedPtr PIResource; + + +/************************************************************************************************************************* + Class interface for ResourceIterator +**************************************************************************************************************************/ + +class IResourceIterator : public virtual IBase { +public: + /** + * IResourceIterator::MoveNext - Iterates to the next resource in the list. + * @return Iterates to the next resource in the list. + */ + virtual bool MoveNext() = 0; + + /** + * IResourceIterator::MovePrevious - Iterates to the previous resource in the list. + * @return Iterates to the previous resource in the list. + */ + virtual bool MovePrevious() = 0; + + /** + * IResourceIterator::GetCurrent - Returns the resource the iterator points at. + * @return returns the resource instance. + */ + virtual IResource * GetCurrent() = 0; + + /** + * IResourceIterator::Clone - Creates a new resource iterator with the same resource list. + * @return returns the cloned Iterator instance + */ + virtual IResourceIterator * Clone() = 0; + + /** + * IResourceIterator::Count - Returns the number of resoucres the iterator captures. + * @return returns the number of resoucres the iterator captures. + */ + virtual Lib3MF_uint64 Count() = 0; + +}; + +typedef IBaseSharedPtr PIResourceIterator; + + +/************************************************************************************************************************* + Class interface for SliceStackIterator +**************************************************************************************************************************/ + +class ISliceStackIterator : public virtual IResourceIterator { +public: + /** + * ISliceStackIterator::GetCurrentSliceStack - Returns the SliceStack the iterator points at. + * @return returns the SliceStack instance. + */ + virtual ISliceStack * GetCurrentSliceStack() = 0; + +}; + +typedef IBaseSharedPtr PISliceStackIterator; + + +/************************************************************************************************************************* + Class interface for ObjectIterator +**************************************************************************************************************************/ + +class IObjectIterator : public virtual IResourceIterator { +public: + /** + * IObjectIterator::GetCurrentObject - Returns the Object the iterator points at. + * @return returns the Object instance. + */ + virtual IObject * GetCurrentObject() = 0; + +}; + +typedef IBaseSharedPtr PIObjectIterator; + + +/************************************************************************************************************************* + Class interface for MeshObjectIterator +**************************************************************************************************************************/ + +class IMeshObjectIterator : public virtual IResourceIterator { +public: + /** + * IMeshObjectIterator::GetCurrentMeshObject - Returns the MeshObject the iterator points at. + * @return returns the MeshObject instance. + */ + virtual IMeshObject * GetCurrentMeshObject() = 0; + +}; + +typedef IBaseSharedPtr PIMeshObjectIterator; + + +/************************************************************************************************************************* + Class interface for ComponentsObjectIterator +**************************************************************************************************************************/ + +class IComponentsObjectIterator : public virtual IResourceIterator { +public: + /** + * IComponentsObjectIterator::GetCurrentComponentsObject - Returns the ComponentsObject the iterator points at. + * @return returns the ComponentsObject instance. + */ + virtual IComponentsObject * GetCurrentComponentsObject() = 0; + +}; + +typedef IBaseSharedPtr PIComponentsObjectIterator; + + +/************************************************************************************************************************* + Class interface for Texture2DIterator +**************************************************************************************************************************/ + +class ITexture2DIterator : public virtual IResourceIterator { +public: + /** + * ITexture2DIterator::GetCurrentTexture2D - Returns the Texture2D the iterator points at. + * @return returns the Texture2D instance. + */ + virtual ITexture2D * GetCurrentTexture2D() = 0; + +}; + +typedef IBaseSharedPtr PITexture2DIterator; + + +/************************************************************************************************************************* + Class interface for BaseMaterialGroupIterator +**************************************************************************************************************************/ + +class IBaseMaterialGroupIterator : public virtual IResourceIterator { +public: + /** + * IBaseMaterialGroupIterator::GetCurrentBaseMaterialGroup - Returns the MaterialGroup the iterator points at. + * @return returns the BaseMaterialGroup instance. + */ + virtual IBaseMaterialGroup * GetCurrentBaseMaterialGroup() = 0; + +}; + +typedef IBaseSharedPtr PIBaseMaterialGroupIterator; + + +/************************************************************************************************************************* + Class interface for ColorGroupIterator +**************************************************************************************************************************/ + +class IColorGroupIterator : public virtual IResourceIterator { +public: + /** + * IColorGroupIterator::GetCurrentColorGroup - Returns the ColorGroup the iterator points at. + * @return returns the ColorGroup instance. + */ + virtual IColorGroup * GetCurrentColorGroup() = 0; + +}; + +typedef IBaseSharedPtr PIColorGroupIterator; + + +/************************************************************************************************************************* + Class interface for Texture2DGroupIterator +**************************************************************************************************************************/ + +class ITexture2DGroupIterator : public virtual IResourceIterator { +public: + /** + * ITexture2DGroupIterator::GetCurrentTexture2DGroup - Returns the Texture2DGroup the iterator points at. + * @return returns the Texture2DGroup instance. + */ + virtual ITexture2DGroup * GetCurrentTexture2DGroup() = 0; + +}; + +typedef IBaseSharedPtr PITexture2DGroupIterator; + + +/************************************************************************************************************************* + Class interface for CompositeMaterialsIterator +**************************************************************************************************************************/ + +class ICompositeMaterialsIterator : public virtual IResourceIterator { +public: + /** + * ICompositeMaterialsIterator::GetCurrentCompositeMaterials - Returns the CompositeMaterials the iterator points at. + * @return returns the CompositeMaterials instance. + */ + virtual ICompositeMaterials * GetCurrentCompositeMaterials() = 0; + +}; + +typedef IBaseSharedPtr PICompositeMaterialsIterator; + + +/************************************************************************************************************************* + Class interface for MultiPropertyGroupIterator +**************************************************************************************************************************/ + +class IMultiPropertyGroupIterator : public virtual IResourceIterator { +public: + /** + * IMultiPropertyGroupIterator::GetCurrentMultiPropertyGroup - Returns the MultiPropertyGroup the iterator points at. + * @return returns the MultiPropertyGroup instance. + */ + virtual IMultiPropertyGroup * GetCurrentMultiPropertyGroup() = 0; + +}; + +typedef IBaseSharedPtr PIMultiPropertyGroupIterator; + + +/************************************************************************************************************************* + Class interface for MetaData +**************************************************************************************************************************/ + +class IMetaData : public virtual IBase { +public: + /** + * IMetaData::GetNameSpace - returns the namespace URL of the metadata + * @return the namespace URL of the metadata + */ + virtual std::string GetNameSpace() = 0; + + /** + * IMetaData::SetNameSpace - sets a new namespace URL of the metadata + * @param[in] sNameSpace - the new namespace URL of the metadata + */ + virtual void SetNameSpace(const std::string & sNameSpace) = 0; + + /** + * IMetaData::GetName - returns the name of a metadata + * @return the name of the metadata + */ + virtual std::string GetName() = 0; + + /** + * IMetaData::SetName - sets a new name of a metadata + * @param[in] sName - the new name of the metadata + */ + virtual void SetName(const std::string & sName) = 0; + + /** + * IMetaData::GetKey - returns the (namespace+name) of a metadata + * @return the key (namespace+name) of the metadata + */ + virtual std::string GetKey() = 0; + + /** + * IMetaData::GetMustPreserve - returns, whether a metadata must be preserved + * @return returns, whether a metadata must be preserved + */ + virtual bool GetMustPreserve() = 0; + + /** + * IMetaData::SetMustPreserve - sets whether a metadata must be preserved + * @param[in] bMustPreserve - a new value whether a metadata must be preserved + */ + virtual void SetMustPreserve(const bool bMustPreserve) = 0; + + /** + * IMetaData::GetType - returns the type of a metadata + * @return the type of the metadata + */ + virtual std::string GetType() = 0; + + /** + * IMetaData::SetType - sets a new type of a metadata. This must be a simple XML type + * @param[in] sType - a new type of the metadata + */ + virtual void SetType(const std::string & sType) = 0; + + /** + * IMetaData::GetValue - returns the value of the metadata + * @return the value of the metadata + */ + virtual std::string GetValue() = 0; + + /** + * IMetaData::SetValue - sets a new value of the metadata + * @param[in] sValue - a new value of the metadata + */ + virtual void SetValue(const std::string & sValue) = 0; + +}; + +typedef IBaseSharedPtr PIMetaData; + + +/************************************************************************************************************************* + Class interface for MetaDataGroup +**************************************************************************************************************************/ + +class IMetaDataGroup : public virtual IBase { +public: + /** + * IMetaDataGroup::GetMetaDataCount - returns the number of metadata in this metadatagroup + * @return returns the number metadata + */ + virtual Lib3MF_uint32 GetMetaDataCount() = 0; + + /** + * IMetaDataGroup::GetMetaData - returns a metadata value within this metadatagroup + * @param[in] nIndex - Index of the Metadata. + * @return an instance of the metadata + */ + virtual IMetaData * GetMetaData(const Lib3MF_uint32 nIndex) = 0; + + /** + * IMetaDataGroup::GetMetaDataByKey - returns a metadata value within this metadatagroup + * @param[in] sNameSpace - the namespace of the metadata + * @param[in] sName - the name of the Metadata + * @return an instance of the metadata + */ + virtual IMetaData * GetMetaDataByKey(const std::string & sNameSpace, const std::string & sName) = 0; + + /** + * IMetaDataGroup::RemoveMetaDataByIndex - removes metadata by index from the model. + * @param[in] nIndex - Index of the metadata to remove + */ + virtual void RemoveMetaDataByIndex(const Lib3MF_uint32 nIndex) = 0; + + /** + * IMetaDataGroup::RemoveMetaData - removes metadata from the model. + * @param[in] pTheMetaData - The metadata to remove + */ + virtual void RemoveMetaData(IMetaData* pTheMetaData) = 0; + + /** + * IMetaDataGroup::AddMetaData - adds a new metadata to this metadatagroup + * @param[in] sNameSpace - the namespace of the metadata + * @param[in] sName - the name of the metadata + * @param[in] sValue - the value of the metadata + * @param[in] sType - the type of the metadata + * @param[in] bMustPreserve - shuold the metadata be preserved + * @return a new instance of the metadata + */ + virtual IMetaData * AddMetaData(const std::string & sNameSpace, const std::string & sName, const std::string & sValue, const std::string & sType, const bool bMustPreserve) = 0; + +}; + +typedef IBaseSharedPtr PIMetaDataGroup; + + +/************************************************************************************************************************* + Class interface for Object +**************************************************************************************************************************/ + +class IObject : public virtual IResource { +public: + /** + * IObject::GetType - Retrieves an object's type + * @return returns object type enum. + */ + virtual Lib3MF::eObjectType GetType() = 0; + + /** + * IObject::SetType - Sets an object's type + * @param[in] eObjectType - object type enum. + */ + virtual void SetType(const Lib3MF::eObjectType eObjectType) = 0; + + /** + * IObject::GetName - Retrieves an object's name + * @return returns object name. + */ + virtual std::string GetName() = 0; + + /** + * IObject::SetName - Sets an object's name string + * @param[in] sName - new object name. + */ + virtual void SetName(const std::string & sName) = 0; + + /** + * IObject::GetPartNumber - Retrieves an object's part number + * @return returns object part number. + */ + virtual std::string GetPartNumber() = 0; + + /** + * IObject::SetPartNumber - Sets an objects partnumber string + * @param[in] sPartNumber - new object part number. + */ + virtual void SetPartNumber(const std::string & sPartNumber) = 0; + + /** + * IObject::IsMeshObject - Retrieves, if an object is a mesh object + * @return returns, whether the object is a mesh object + */ + virtual bool IsMeshObject() = 0; + + /** + * IObject::IsComponentsObject - Retrieves, if an object is a components object + * @return returns, whether the object is a components object + */ + virtual bool IsComponentsObject() = 0; + + /** + * IObject::IsValid - Retrieves, if the object is valid according to the core spec. For mesh objects, we distinguish between the type attribute of the object:In case of object type other, this always means false.In case of object type model or solidsupport, this means, if the mesh suffices all requirements of the core spec chapter 4.1.In case of object type support or surface, this always means true.A component objects is valid if and only if it contains at least one component and all child components are valid objects. + * @return returns whether the object is a valid object description + */ + virtual bool IsValid() = 0; + + /** + * IObject::SetAttachmentAsThumbnail - Use an existing attachment as thumbnail for this object + * @param[in] pAttachment - Instance of a new or the existing thumbnailattachment object. + */ + virtual void SetAttachmentAsThumbnail(IAttachment* pAttachment) = 0; + + /** + * IObject::GetThumbnailAttachment - Get the attachment containing the object thumbnail. + * @return Instance of the thumbnailattachment object or NULL. + */ + virtual IAttachment * GetThumbnailAttachment() = 0; + + /** + * IObject::ClearThumbnailAttachment - Clears the attachment. The attachment instance is not removed from the package. + */ + virtual void ClearThumbnailAttachment() = 0; + + /** + * IObject::GetOutbox - Returns the outbox of a build item + * @return Outbox of this build item + */ + virtual Lib3MF::sBox GetOutbox() = 0; + + /** + * IObject::GetUUID - Retrieves an object's uuid string (see production extension specification) + * @param[out] bHasUUID - flag whether the build item has a UUID + * @return returns object uuid. + */ + virtual std::string GetUUID(bool & bHasUUID) = 0; + + /** + * IObject::SetUUID - Sets a build object's uuid string (see production extension specification) + * @param[in] sUUID - new object uuid string. + */ + virtual void SetUUID(const std::string & sUUID) = 0; + + /** + * IObject::GetMetaDataGroup - Returns the metadatagroup of this object + * @return returns an Instance of the metadatagroup of this object + */ + virtual IMetaDataGroup * GetMetaDataGroup() = 0; + + /** + * IObject::SetSlicesMeshResolution - set the meshresolution of the mesh object + * @param[in] eMeshResolution - meshresolution of this object + */ + virtual void SetSlicesMeshResolution(const Lib3MF::eSlicesMeshResolution eMeshResolution) = 0; + + /** + * IObject::GetSlicesMeshResolution - get the meshresolution of the mesh object + * @return meshresolution of this object + */ + virtual Lib3MF::eSlicesMeshResolution GetSlicesMeshResolution() = 0; + + /** + * IObject::HasSlices - returns whether the Object has a slice stack. If Recursive is true, also checks whether any references object has a slice stack + * @param[in] bRecursive - check also all referenced objects? + * @return does the object have a slice stack? + */ + virtual bool HasSlices(const bool bRecursive) = 0; + + /** + * IObject::ClearSliceStack - unlinks the attached slicestack from this object. If no slice stack is attached, do noting. + */ + virtual void ClearSliceStack() = 0; + + /** + * IObject::GetSliceStack - get the Slicestack attached to the object + * @return returns the slicestack instance + */ + virtual ISliceStack * GetSliceStack() = 0; + + /** + * IObject::AssignSliceStack - assigns a slicestack to the object + * @param[in] pSliceStackInstance - the new slice stack of this Object + */ + virtual void AssignSliceStack(ISliceStack* pSliceStackInstance) = 0; + +}; + +typedef IBaseSharedPtr PIObject; + + +/************************************************************************************************************************* + Class interface for MeshObject +**************************************************************************************************************************/ + +class IMeshObject : public virtual IObject { +public: + /** + * IMeshObject::GetVertexCount - Returns the vertex count of a mesh object. + * @return filled with the vertex count. + */ + virtual Lib3MF_uint32 GetVertexCount() = 0; + + /** + * IMeshObject::GetTriangleCount - Returns the triangle count of a mesh object. + * @return filled with the triangle count. + */ + virtual Lib3MF_uint32 GetTriangleCount() = 0; + + /** + * IMeshObject::GetVertex - Returns the vertex count of a mesh object. + * @param[in] nIndex - Index of the vertex (0 to vertexcount - 1) + * @return filled with the vertex coordinates. + */ + virtual Lib3MF::sPosition GetVertex(const Lib3MF_uint32 nIndex) = 0; + + /** + * IMeshObject::SetVertex - Sets the coordinates of a single vertex of a mesh object + * @param[in] nIndex - Index of the vertex (0 to vertexcount - 1) + * @param[in] Coordinates - contains the vertex coordinates. + */ + virtual void SetVertex(const Lib3MF_uint32 nIndex, const Lib3MF::sPosition Coordinates) = 0; + + /** + * IMeshObject::AddVertex - Adds a single vertex to a mesh object + * @param[in] Coordinates - contains the vertex coordinates. + * @return Index of the new vertex + */ + virtual Lib3MF_uint32 AddVertex(const Lib3MF::sPosition Coordinates) = 0; + + /** + * IMeshObject::GetVertices - Obtains all vertex positions of a mesh object + * @param[in] nVerticesBufferSize - Number of elements in buffer + * @param[out] pVerticesNeededCount - will be filled with the count of the written structs, or needed buffer size. + * @param[out] pVerticesBuffer - Position buffer of contains the vertex coordinates. + */ + virtual void GetVertices(Lib3MF_uint64 nVerticesBufferSize, Lib3MF_uint64* pVerticesNeededCount, Lib3MF::sPosition * pVerticesBuffer) = 0; + + /** + * IMeshObject::GetTriangle - Returns indices of a single triangle of a mesh object. + * @param[in] nIndex - Index of the triangle (0 to trianglecount - 1) + * @return filled with the triangle indices. + */ + virtual Lib3MF::sTriangle GetTriangle(const Lib3MF_uint32 nIndex) = 0; + + /** + * IMeshObject::SetTriangle - Sets the indices of a single triangle of a mesh object. + * @param[in] nIndex - Index of the triangle (0 to trianglecount - 1) + * @param[in] Indices - contains the triangle indices. + */ + virtual void SetTriangle(const Lib3MF_uint32 nIndex, const Lib3MF::sTriangle Indices) = 0; + + /** + * IMeshObject::AddTriangle - Adds a single triangle to a mesh object + * @param[in] Indices - contains the triangle indices. + * @return Index of the new triangle + */ + virtual Lib3MF_uint32 AddTriangle(const Lib3MF::sTriangle Indices) = 0; + + /** + * IMeshObject::GetTriangleIndices - Get all triangles of a mesh object + * @param[in] nIndicesBufferSize - Number of elements in buffer + * @param[out] pIndicesNeededCount - will be filled with the count of the written structs, or needed buffer size. + * @param[out] pIndicesBuffer - Triangle buffer of contains the triangle indices. + */ + virtual void GetTriangleIndices(Lib3MF_uint64 nIndicesBufferSize, Lib3MF_uint64* pIndicesNeededCount, Lib3MF::sTriangle * pIndicesBuffer) = 0; + + /** + * IMeshObject::SetObjectLevelProperty - Sets the property at the object-level of the mesh object. + * @param[in] nUniqueResourceID - the object-level Property UniqueResourceID. + * @param[in] nPropertyID - the object-level PropertyID. + */ + virtual void SetObjectLevelProperty(const Lib3MF_uint32 nUniqueResourceID, const Lib3MF_uint32 nPropertyID) = 0; + + /** + * IMeshObject::GetObjectLevelProperty - Gets the property at the object-level of the mesh object. + * @param[out] nUniqueResourceID - the object-level Property UniqueResourceID. + * @param[out] nPropertyID - the object-level PropertyID. + * @return Has an object-level property been specified? + */ + virtual bool GetObjectLevelProperty(Lib3MF_uint32 & nUniqueResourceID, Lib3MF_uint32 & nPropertyID) = 0; + + /** + * IMeshObject::SetTriangleProperties - Sets the properties of a single triangle of a mesh object. + * @param[in] nIndex - Index of the triangle (0 to trianglecount - 1) + * @param[in] Properties - contains the triangle properties. + */ + virtual void SetTriangleProperties(const Lib3MF_uint32 nIndex, const Lib3MF::sTriangleProperties Properties) = 0; + + /** + * IMeshObject::GetTriangleProperties - Gets the properties of a single triangle of a mesh object. + * @param[in] nIndex - Index of the triangle (0 to trianglecount - 1) + * @param[out] sProperty - returns the triangle properties. + */ + virtual void GetTriangleProperties(const Lib3MF_uint32 nIndex, Lib3MF::sTriangleProperties & sProperty) = 0; + + /** + * IMeshObject::SetAllTriangleProperties - Sets the properties of all triangles of a mesh object. Sets the object level property to the first entry of the passed triangle properties, if not yet specified. + * @param[in] nPropertiesArrayBufferSize - Number of elements in buffer + * @param[in] pPropertiesArrayBuffer - contains the triangle properties array. Must have trianglecount elements. + */ + virtual void SetAllTriangleProperties(const Lib3MF_uint64 nPropertiesArrayBufferSize, const Lib3MF::sTriangleProperties * pPropertiesArrayBuffer) = 0; + + /** + * IMeshObject::GetAllTriangleProperties - Gets the properties of all triangles of a mesh object. + * @param[in] nPropertiesArrayBufferSize - Number of elements in buffer + * @param[out] pPropertiesArrayNeededCount - will be filled with the count of the written structs, or needed buffer size. + * @param[out] pPropertiesArrayBuffer - TriangleProperties buffer of returns the triangle properties array. Must have trianglecount elements. + */ + virtual void GetAllTriangleProperties(Lib3MF_uint64 nPropertiesArrayBufferSize, Lib3MF_uint64* pPropertiesArrayNeededCount, Lib3MF::sTriangleProperties * pPropertiesArrayBuffer) = 0; + + /** + * IMeshObject::ClearAllProperties - Clears all properties of this mesh object (triangle and object-level). + */ + virtual void ClearAllProperties() = 0; + + /** + * IMeshObject::SetGeometry - Set all triangles of a mesh object + * @param[in] nVerticesBufferSize - Number of elements in buffer + * @param[in] pVerticesBuffer - contains the positions. + * @param[in] nIndicesBufferSize - Number of elements in buffer + * @param[in] pIndicesBuffer - contains the triangle indices. + */ + virtual void SetGeometry(const Lib3MF_uint64 nVerticesBufferSize, const Lib3MF::sPosition * pVerticesBuffer, const Lib3MF_uint64 nIndicesBufferSize, const Lib3MF::sTriangle * pIndicesBuffer) = 0; + + /** + * IMeshObject::IsManifoldAndOriented - Retrieves, if an object describes a topologically oriented and manifold mesh, according to the core spec. + * @return returns, if the object is oriented and manifold. + */ + virtual bool IsManifoldAndOriented() = 0; + + /** + * IMeshObject::BeamLattice - Retrieves the BeamLattice within this MeshObject. + * @return the BeamLattice within this MeshObject + */ + virtual IBeamLattice * BeamLattice() = 0; + +}; + +typedef IBaseSharedPtr PIMeshObject; + + +/************************************************************************************************************************* + Class interface for BeamLattice +**************************************************************************************************************************/ + +class IBeamLattice : public virtual IBase { +public: + /** + * IBeamLattice::GetMinLength - Returns the minimal length of beams for the beamlattice. + * @return minimal length of beams for the beamlattice + */ + virtual Lib3MF_double GetMinLength() = 0; + + /** + * IBeamLattice::SetMinLength - Sets the minimal length of beams for the beamlattice. + * @param[in] dMinLength - minimal length of beams for the beamlattice + */ + virtual void SetMinLength(const Lib3MF_double dMinLength) = 0; + + /** + * IBeamLattice::GetClipping - Returns the clipping mode and the clipping-mesh for the beamlattice of this mesh. + * @param[out] eClipMode - contains the clip mode of this mesh + * @param[out] nUniqueResourceID - filled with the UniqueResourceID of the clipping mesh-object or an undefined value if pClipMode is MODELBEAMLATTICECLIPMODE_NONE + */ + virtual void GetClipping(Lib3MF::eBeamLatticeClipMode & eClipMode, Lib3MF_uint32 & nUniqueResourceID) = 0; + + /** + * IBeamLattice::SetClipping - Sets the clipping mode and the clipping-mesh for the beamlattice of this mesh. + * @param[in] eClipMode - contains the clip mode of this mesh + * @param[in] nUniqueResourceID - the UniqueResourceID of the clipping mesh-object. This mesh-object has to be defined before setting the Clipping. + */ + virtual void SetClipping(const Lib3MF::eBeamLatticeClipMode eClipMode, const Lib3MF_uint32 nUniqueResourceID) = 0; + + /** + * IBeamLattice::GetRepresentation - Returns the representation-mesh for the beamlattice of this mesh. + * @return flag whether the beamlattice has a representation mesh. + * @param[out] nUniqueResourceID - filled with the UniqueResourceID of the clipping mesh-object. + */ + virtual bool GetRepresentation(Lib3MF_uint32 & nUniqueResourceID) = 0; + + /** + * IBeamLattice::SetRepresentation - Sets the representation-mesh for the beamlattice of this mesh. + * @param[in] nUniqueResourceID - the UniqueResourceID of the representation mesh-object. This mesh-object has to be defined before setting the representation. + */ + virtual void SetRepresentation(const Lib3MF_uint32 nUniqueResourceID) = 0; + + /** + * IBeamLattice::GetBallOptions - Returns the ball mode and the default ball radius for the beamlattice of this mesh. + * @param[out] eBallMode - contains the ball mode of this mesh + * @param[out] dBallRadius - default ball radius of balls for the beamlattice + */ + virtual void GetBallOptions(Lib3MF::eBeamLatticeBallMode & eBallMode, Lib3MF_double & dBallRadius) = 0; + + /** + * IBeamLattice::SetBallOptions - Sets the ball mode and thedefault ball radius for the beamlattice. + * @param[in] eBallMode - contains the ball mode of this mesh + * @param[in] dBallRadius - default ball radius of balls for the beamlattice + */ + virtual void SetBallOptions(const Lib3MF::eBeamLatticeBallMode eBallMode, const Lib3MF_double dBallRadius) = 0; + + /** + * IBeamLattice::GetBeamCount - Returns the beam count of a mesh object. + * @return filled with the beam count. + */ + virtual Lib3MF_uint32 GetBeamCount() = 0; + + /** + * IBeamLattice::GetBeam - Returns indices, radii and capmodes of a single beam of a mesh object. + * @param[in] nIndex - Index of the beam (0 to beamcount - 1). + * @return filled with the beam indices, radii and capmodes. + */ + virtual Lib3MF::sBeam GetBeam(const Lib3MF_uint32 nIndex) = 0; + + /** + * IBeamLattice::AddBeam - Adds a single beam to a mesh object. + * @param[in] BeamInfo - contains the node indices, radii and capmodes. + * @return filled with the new Index of the beam. + */ + virtual Lib3MF_uint32 AddBeam(const Lib3MF::sBeam BeamInfo) = 0; + + /** + * IBeamLattice::SetBeam - Sets the indices, radii and capmodes of a single beam of a mesh object. + * @param[in] nIndex - Index of the beam (0 to beamcount - 1). + * @param[in] BeamInfo - filled with the beam indices, radii and capmodes. + */ + virtual void SetBeam(const Lib3MF_uint32 nIndex, const Lib3MF::sBeam BeamInfo) = 0; + + /** + * IBeamLattice::SetBeams - Sets all beam indices, radii and capmodes of a mesh object. + * @param[in] nBeamInfoBufferSize - Number of elements in buffer + * @param[in] pBeamInfoBuffer - contains information of a number of beams + */ + virtual void SetBeams(const Lib3MF_uint64 nBeamInfoBufferSize, const Lib3MF::sBeam * pBeamInfoBuffer) = 0; + + /** + * IBeamLattice::GetBeams - obtains all beam indices, radii and capmodes of a mesh object. + * @param[in] nBeamInfoBufferSize - Number of elements in buffer + * @param[out] pBeamInfoNeededCount - will be filled with the count of the written structs, or needed buffer size. + * @param[out] pBeamInfoBuffer - Beam buffer of contains information of all beams + */ + virtual void GetBeams(Lib3MF_uint64 nBeamInfoBufferSize, Lib3MF_uint64* pBeamInfoNeededCount, Lib3MF::sBeam * pBeamInfoBuffer) = 0; + + /** + * IBeamLattice::GetBallCount - Returns the ball count of a mesh object. + * @return filled with the ball count. + */ + virtual Lib3MF_uint32 GetBallCount() = 0; + + /** + * IBeamLattice::GetBall - Returns index and radius of a single ball of a mesh object. + * @param[in] nIndex - Index of the ball (0 to ballcount - 1). + * @return filled with the ball node index and radius. + */ + virtual Lib3MF::sBall GetBall(const Lib3MF_uint32 nIndex) = 0; + + /** + * IBeamLattice::AddBall - Adds a single ball to a mesh object. + * @param[in] BallInfo - contains the node index and radius. + * @return filled with the new Index of the ball. + */ + virtual Lib3MF_uint32 AddBall(const Lib3MF::sBall BallInfo) = 0; + + /** + * IBeamLattice::SetBall - Sets the index and radius of a single ball of a mesh object. + * @param[in] nIndex - Index of the ball (0 to ballcount - 1). + * @param[in] BallInfo - filled with the ball node index and radius. + */ + virtual void SetBall(const Lib3MF_uint32 nIndex, const Lib3MF::sBall BallInfo) = 0; + + /** + * IBeamLattice::SetBalls - Sets all ball indices and radii of a mesh object. + * @param[in] nBallInfoBufferSize - Number of elements in buffer + * @param[in] pBallInfoBuffer - contains information of a number of balls + */ + virtual void SetBalls(const Lib3MF_uint64 nBallInfoBufferSize, const Lib3MF::sBall * pBallInfoBuffer) = 0; + + /** + * IBeamLattice::GetBalls - obtains all ball indices and radii of a mesh object. + * @param[in] nBallInfoBufferSize - Number of elements in buffer + * @param[out] pBallInfoNeededCount - will be filled with the count of the written structs, or needed buffer size. + * @param[out] pBallInfoBuffer - Ball buffer of contains information of all balls + */ + virtual void GetBalls(Lib3MF_uint64 nBallInfoBufferSize, Lib3MF_uint64* pBallInfoNeededCount, Lib3MF::sBall * pBallInfoBuffer) = 0; + + /** + * IBeamLattice::GetBeamSetCount - Returns the number of beamsets of a mesh object. + * @return filled with the beamset count. + */ + virtual Lib3MF_uint32 GetBeamSetCount() = 0; + + /** + * IBeamLattice::AddBeamSet - Adds an empty beamset to a mesh object + * @return the new beamset + */ + virtual IBeamSet * AddBeamSet() = 0; + + /** + * IBeamLattice::GetBeamSet - Returns a beamset of a mesh object + * @param[in] nIndex - index of the requested beamset (0 ... beamsetcount-1). + * @return the requested beamset + */ + virtual IBeamSet * GetBeamSet(const Lib3MF_uint32 nIndex) = 0; + +}; + +typedef IBaseSharedPtr PIBeamLattice; + + +/************************************************************************************************************************* + Class interface for Component +**************************************************************************************************************************/ + +class IComponent : public virtual IBase { +public: + /** + * IComponent::GetObjectResource - Returns the Resource Instance of the component. + * @return filled with the Resource Instance. + */ + virtual IObject * GetObjectResource() = 0; + + /** + * IComponent::GetObjectResourceID - Returns the UniqueResourceID of the component. + * @return returns the UniqueResourceID. + */ + virtual Lib3MF_uint32 GetObjectResourceID() = 0; + + /** + * IComponent::GetUUID - returns, whether a component has a UUID and, if true, the component's UUID + * @param[out] bHasUUID - flag whether the component has a UUID + * @return the UUID as string of the form 'xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx' + */ + virtual std::string GetUUID(bool & bHasUUID) = 0; + + /** + * IComponent::SetUUID - sets the component's UUID + * @param[in] sUUID - the UUID as string of the form 'xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx' + */ + virtual void SetUUID(const std::string & sUUID) = 0; + + /** + * IComponent::HasTransform - Returns, if the component has a different transformation than the identity matrix + * @return if true is returned, the transformation is not equal than the identity + */ + virtual bool HasTransform() = 0; + + /** + * IComponent::GetTransform - Returns the transformation matrix of the component. + * @return filled with the component transformation matrix + */ + virtual Lib3MF::sTransform GetTransform() = 0; + + /** + * IComponent::SetTransform - Sets the transformation matrix of the component. + * @param[in] Transform - new transformation matrix + */ + virtual void SetTransform(const Lib3MF::sTransform Transform) = 0; + +}; + +typedef IBaseSharedPtr PIComponent; + + +/************************************************************************************************************************* + Class interface for ComponentsObject +**************************************************************************************************************************/ + +class IComponentsObject : public virtual IObject { +public: + /** + * IComponentsObject::AddComponent - Adds a new component to a components object. + * @param[in] pObjectResource - object to add as component. Must not lead to circular references! + * @param[in] Transform - optional transform matrix for the component. + * @return new component instance + */ + virtual IComponent * AddComponent(IObject* pObjectResource, const Lib3MF::sTransform Transform) = 0; + + /** + * IComponentsObject::GetComponent - Retrieves a component from a component object. + * @param[in] nIndex - index of the component to retrieve (0 to componentcount - 1) + * @return component instance + */ + virtual IComponent * GetComponent(const Lib3MF_uint32 nIndex) = 0; + + /** + * IComponentsObject::GetComponentCount - Retrieves a component count of a component object. + * @return returns the component count + */ + virtual Lib3MF_uint32 GetComponentCount() = 0; + +}; + +typedef IBaseSharedPtr PIComponentsObject; + + +/************************************************************************************************************************* + Class interface for BeamSet +**************************************************************************************************************************/ + +class IBeamSet : public virtual IBase { +public: + /** + * IBeamSet::SetName - Sets a beamset's name string + * @param[in] sName - new name of the beamset. + */ + virtual void SetName(const std::string & sName) = 0; + + /** + * IBeamSet::GetName - Retrieves a beamset's name string + * @return returns the name of the beamset. + */ + virtual std::string GetName() = 0; + + /** + * IBeamSet::SetIdentifier - Sets a beamset's identifier string + * @param[in] sIdentifier - new name of the beamset. + */ + virtual void SetIdentifier(const std::string & sIdentifier) = 0; + + /** + * IBeamSet::GetIdentifier - Retrieves a beamset's identifier string + * @return returns the identifier of the beamset. + */ + virtual std::string GetIdentifier() = 0; + + /** + * IBeamSet::GetReferenceCount - Retrieves the reference count of a beamset + * @return returns the reference count + */ + virtual Lib3MF_uint32 GetReferenceCount() = 0; + + /** + * IBeamSet::SetReferences - Sets the references of a beamset + * @param[in] nReferencesBufferSize - Number of elements in buffer + * @param[in] pReferencesBuffer - the new indices of all beams in this beamset + */ + virtual void SetReferences(const Lib3MF_uint64 nReferencesBufferSize, const Lib3MF_uint32 * pReferencesBuffer) = 0; + + /** + * IBeamSet::GetReferences - Retrieves the references of a beamset + * @param[in] nReferencesBufferSize - Number of elements in buffer + * @param[out] pReferencesNeededCount - will be filled with the count of the written structs, or needed buffer size. + * @param[out] pReferencesBuffer - uint32 buffer of retrieves the indices of all beams in this beamset + */ + virtual void GetReferences(Lib3MF_uint64 nReferencesBufferSize, Lib3MF_uint64* pReferencesNeededCount, Lib3MF_uint32 * pReferencesBuffer) = 0; + + /** + * IBeamSet::GetBallReferenceCount - Retrieves the ball reference count of a beamset + * @return returns the ball reference count + */ + virtual Lib3MF_uint32 GetBallReferenceCount() = 0; + + /** + * IBeamSet::SetBallReferences - Sets the ball references of a beamset + * @param[in] nBallReferencesBufferSize - Number of elements in buffer + * @param[in] pBallReferencesBuffer - the new indices of all balls in this beamset + */ + virtual void SetBallReferences(const Lib3MF_uint64 nBallReferencesBufferSize, const Lib3MF_uint32 * pBallReferencesBuffer) = 0; + + /** + * IBeamSet::GetBallReferences - Retrieves the ball references of a beamset + * @param[in] nBallReferencesBufferSize - Number of elements in buffer + * @param[out] pBallReferencesNeededCount - will be filled with the count of the written structs, or needed buffer size. + * @param[out] pBallReferencesBuffer - uint32 buffer of retrieves the indices of all balls in this beamset + */ + virtual void GetBallReferences(Lib3MF_uint64 nBallReferencesBufferSize, Lib3MF_uint64* pBallReferencesNeededCount, Lib3MF_uint32 * pBallReferencesBuffer) = 0; + +}; + +typedef IBaseSharedPtr PIBeamSet; + + +/************************************************************************************************************************* + Class interface for BaseMaterialGroup +**************************************************************************************************************************/ + +class IBaseMaterialGroup : public virtual IResource { +public: + /** + * IBaseMaterialGroup::GetCount - Retrieves the count of base materials in the material group. + * @return returns the count of base materials. + */ + virtual Lib3MF_uint32 GetCount() = 0; + + /** + * IBaseMaterialGroup::GetAllPropertyIDs - returns all the PropertyIDs of all materials in this group + * @param[in] nPropertyIDsBufferSize - Number of elements in buffer + * @param[out] pPropertyIDsNeededCount - will be filled with the count of the written structs, or needed buffer size. + * @param[out] pPropertyIDsBuffer - uint32 buffer of PropertyID of the material in the material group. + */ + virtual void GetAllPropertyIDs(Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer) = 0; + + /** + * IBaseMaterialGroup::AddMaterial - Adds a new material to the material group + * @param[in] sName - new name of the base material. + * @param[in] DisplayColor - Display color of the material + * @return returns new PropertyID of the new material in the material group. + */ + virtual Lib3MF_uint32 AddMaterial(const std::string & sName, const Lib3MF::sColor DisplayColor) = 0; + + /** + * IBaseMaterialGroup::RemoveMaterial - Removes a material from the material group. + * @param[in] nPropertyID - PropertyID of the material in the material group. + */ + virtual void RemoveMaterial(const Lib3MF_uint32 nPropertyID) = 0; + + /** + * IBaseMaterialGroup::GetName - Returns the base material's name + * @param[in] nPropertyID - PropertyID of the material in the material group. + * @return returns the name of the base material. + */ + virtual std::string GetName(const Lib3MF_uint32 nPropertyID) = 0; + + /** + * IBaseMaterialGroup::SetName - Sets a base material's name + * @param[in] nPropertyID - PropertyID of the material in the material group. + * @param[in] sName - new name of the base material. + */ + virtual void SetName(const Lib3MF_uint32 nPropertyID, const std::string & sName) = 0; + + /** + * IBaseMaterialGroup::SetDisplayColor - Sets a base material's display color. + * @param[in] nPropertyID - PropertyID of the material in the material group. + * @param[in] TheColor - The base material's display color + */ + virtual void SetDisplayColor(const Lib3MF_uint32 nPropertyID, const Lib3MF::sColor TheColor) = 0; + + /** + * IBaseMaterialGroup::GetDisplayColor - Returns a base material's display color. + * @param[in] nPropertyID - PropertyID of the material in the material group. + * @return The base material's display color + */ + virtual Lib3MF::sColor GetDisplayColor(const Lib3MF_uint32 nPropertyID) = 0; + +}; + +typedef IBaseSharedPtr PIBaseMaterialGroup; + + +/************************************************************************************************************************* + Class interface for ColorGroup +**************************************************************************************************************************/ + +class IColorGroup : public virtual IResource { +public: + /** + * IColorGroup::GetCount - Retrieves the count of base materials in this Color Group. + * @return returns the count of colors within this color group. + */ + virtual Lib3MF_uint32 GetCount() = 0; + + /** + * IColorGroup::GetAllPropertyIDs - returns all the PropertyIDs of all colors within this group + * @param[in] nPropertyIDsBufferSize - Number of elements in buffer + * @param[out] pPropertyIDsNeededCount - will be filled with the count of the written structs, or needed buffer size. + * @param[out] pPropertyIDsBuffer - uint32 buffer of PropertyID of the color in the color group. + */ + virtual void GetAllPropertyIDs(Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer) = 0; + + /** + * IColorGroup::AddColor - Adds a new value. + * @param[in] TheColor - The new color + * @return PropertyID of the new color within this color group. + */ + virtual Lib3MF_uint32 AddColor(const Lib3MF::sColor TheColor) = 0; + + /** + * IColorGroup::RemoveColor - Removes a color from the color group. + * @param[in] nPropertyID - PropertyID of the color to be removed from the color group. + */ + virtual void RemoveColor(const Lib3MF_uint32 nPropertyID) = 0; + + /** + * IColorGroup::SetColor - Sets a color value. + * @param[in] nPropertyID - PropertyID of a color within this color group. + * @param[in] TheColor - The color + */ + virtual void SetColor(const Lib3MF_uint32 nPropertyID, const Lib3MF::sColor TheColor) = 0; + + /** + * IColorGroup::GetColor - Sets a color value. + * @param[in] nPropertyID - PropertyID of a color within this color group. + * @return The color + */ + virtual Lib3MF::sColor GetColor(const Lib3MF_uint32 nPropertyID) = 0; + +}; + +typedef IBaseSharedPtr PIColorGroup; + + +/************************************************************************************************************************* + Class interface for Texture2DGroup +**************************************************************************************************************************/ + +class ITexture2DGroup : public virtual IResource { +public: + /** + * ITexture2DGroup::GetCount - Retrieves the count of tex2coords in the Texture2DGroup. + * @return returns the count of tex2coords. + */ + virtual Lib3MF_uint32 GetCount() = 0; + + /** + * ITexture2DGroup::GetAllPropertyIDs - returns all the PropertyIDs of all tex2coords in this Texture2DGroup + * @param[in] nPropertyIDsBufferSize - Number of elements in buffer + * @param[out] pPropertyIDsNeededCount - will be filled with the count of the written structs, or needed buffer size. + * @param[out] pPropertyIDsBuffer - uint32 buffer of PropertyID of the tex2coords in the Texture2DGroup. + */ + virtual void GetAllPropertyIDs(Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer) = 0; + + /** + * ITexture2DGroup::AddTex2Coord - Adds a new tex2coord to the Texture2DGroup + * @param[in] UVCoordinate - The u/v-coordinate within the texture, horizontally right/vertically up from the origin in the lower left of the texture. + * @return returns new PropertyID of the new tex2coord in the Texture2DGroup. + */ + virtual Lib3MF_uint32 AddTex2Coord(const Lib3MF::sTex2Coord UVCoordinate) = 0; + + /** + * ITexture2DGroup::GetTex2Coord - Obtains a tex2coord to the Texture2DGroup + * @param[in] nPropertyID - the PropertyID of the tex2coord in the Texture2DGroup. + * @return The u/v-coordinate within the texture, horizontally right/vertically up from the origin in the lower left of the texture. + */ + virtual Lib3MF::sTex2Coord GetTex2Coord(const Lib3MF_uint32 nPropertyID) = 0; + + /** + * ITexture2DGroup::RemoveTex2Coord - Removes a tex2coords from the Texture2DGroup. + * @param[in] nPropertyID - PropertyID of the tex2coords in the Texture2DGroup. + */ + virtual void RemoveTex2Coord(const Lib3MF_uint32 nPropertyID) = 0; + + /** + * ITexture2DGroup::GetTexture2D - Obtains the texture2D instance of this group. + * @return the texture2D instance of this group. + */ + virtual ITexture2D * GetTexture2D() = 0; + +}; + +typedef IBaseSharedPtr PITexture2DGroup; + + +/************************************************************************************************************************* + Class interface for CompositeMaterials +**************************************************************************************************************************/ + +class ICompositeMaterials : public virtual IResource { +public: + /** + * ICompositeMaterials::GetCount - Retrieves the count of Composite-s in the CompositeMaterials. + * @return returns the count of Composite-s + */ + virtual Lib3MF_uint32 GetCount() = 0; + + /** + * ICompositeMaterials::GetAllPropertyIDs - returns all the PropertyIDs of all Composite-Mixing Values in this CompositeMaterials + * @param[in] nPropertyIDsBufferSize - Number of elements in buffer + * @param[out] pPropertyIDsNeededCount - will be filled with the count of the written structs, or needed buffer size. + * @param[out] pPropertyIDsBuffer - uint32 buffer of PropertyID of the Composite-Mixing Values in the CompositeMaterials. + */ + virtual void GetAllPropertyIDs(Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer) = 0; + + /** + * ICompositeMaterials::GetBaseMaterialGroup - Obtains the BaseMaterialGroup instance of this CompositeMaterials. + * @return returns the BaseMaterialGroup instance of this CompositeMaterials + */ + virtual IBaseMaterialGroup * GetBaseMaterialGroup() = 0; + + /** + * ICompositeMaterials::AddComposite - Adds a new Composite-Mixing Values to the CompositeMaterials. + * @param[in] nCompositeBufferSize - Number of elements in buffer + * @param[in] pCompositeBuffer - The Composite Constituents to be added as composite + * @return returns new PropertyID of the new Composite in the CompositeMaterials. + */ + virtual Lib3MF_uint32 AddComposite(const Lib3MF_uint64 nCompositeBufferSize, const Lib3MF::sCompositeConstituent * pCompositeBuffer) = 0; + + /** + * ICompositeMaterials::RemoveComposite - Removes a Composite-Maxing Ratio from the CompositeMaterials. + * @param[in] nPropertyID - PropertyID of the Composite-Mixing Values in the CompositeMaterials to be removed. + */ + virtual void RemoveComposite(const Lib3MF_uint32 nPropertyID) = 0; + + /** + * ICompositeMaterials::GetComposite - Obtains a Composite-Maxing Ratio of this CompositeMaterials. + * @param[in] nPropertyID - the PropertyID of the Composite-Maxing Ratio in the CompositeMaterials. + * @param[in] nCompositeBufferSize - Number of elements in buffer + * @param[out] pCompositeNeededCount - will be filled with the count of the written structs, or needed buffer size. + * @param[out] pCompositeBuffer - CompositeConstituent buffer of The Composite-Mixing Values with the given PropertyID + */ + virtual void GetComposite(const Lib3MF_uint32 nPropertyID, Lib3MF_uint64 nCompositeBufferSize, Lib3MF_uint64* pCompositeNeededCount, Lib3MF::sCompositeConstituent * pCompositeBuffer) = 0; + +}; + +typedef IBaseSharedPtr PICompositeMaterials; + + +/************************************************************************************************************************* + Class interface for MultiPropertyGroup +**************************************************************************************************************************/ + +class IMultiPropertyGroup : public virtual IResource { +public: + /** + * IMultiPropertyGroup::GetCount - Retrieves the count of MultiProperty-s in the MultiPropertyGroup. + * @return returns the count of MultiProperty-s + */ + virtual Lib3MF_uint32 GetCount() = 0; + + /** + * IMultiPropertyGroup::GetAllPropertyIDs - returns all the PropertyIDs of all MultiProperty-s in this MultiPropertyGroup + * @param[in] nPropertyIDsBufferSize - Number of elements in buffer + * @param[out] pPropertyIDsNeededCount - will be filled with the count of the written structs, or needed buffer size. + * @param[out] pPropertyIDsBuffer - uint32 buffer of PropertyID of the MultiProperty-s in the MultiPropertyGroup. + */ + virtual void GetAllPropertyIDs(Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer) = 0; + + /** + * IMultiPropertyGroup::AddMultiProperty - Adds a new MultiProperty to the MultiPropertyGroup. + * @param[in] nPropertyIDsBufferSize - Number of elements in buffer + * @param[in] pPropertyIDsBuffer - The PropertyIDs of the new MultiProperty. + * @return returns the PropertyID of the new MultiProperty in the MultiPropertyGroup. + */ + virtual Lib3MF_uint32 AddMultiProperty(const Lib3MF_uint64 nPropertyIDsBufferSize, const Lib3MF_uint32 * pPropertyIDsBuffer) = 0; + + /** + * IMultiPropertyGroup::SetMultiProperty - Sets the PropertyIDs of a MultiProperty. + * @param[in] nPropertyID - the PropertyID of the MultiProperty to be changed. + * @param[in] nPropertyIDsBufferSize - Number of elements in buffer + * @param[in] pPropertyIDsBuffer - The new PropertyIDs of the MultiProperty + */ + virtual void SetMultiProperty(const Lib3MF_uint32 nPropertyID, const Lib3MF_uint64 nPropertyIDsBufferSize, const Lib3MF_uint32 * pPropertyIDsBuffer) = 0; + + /** + * IMultiPropertyGroup::GetMultiProperty - Obtains the PropertyIDs of a MultiProperty. + * @param[in] nPropertyID - the PropertyID of the MultiProperty to be queried. + * @param[in] nPropertyIDsBufferSize - Number of elements in buffer + * @param[out] pPropertyIDsNeededCount - will be filled with the count of the written structs, or needed buffer size. + * @param[out] pPropertyIDsBuffer - uint32 buffer of The PropertyIDs of the MultiProperty + */ + virtual void GetMultiProperty(const Lib3MF_uint32 nPropertyID, Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer) = 0; + + /** + * IMultiPropertyGroup::RemoveMultiProperty - Removes a MultiProperty from this MultiPropertyGroup. + * @param[in] nPropertyID - the PropertyID of the MultiProperty to be removed. + */ + virtual void RemoveMultiProperty(const Lib3MF_uint32 nPropertyID) = 0; + + /** + * IMultiPropertyGroup::GetLayerCount - Retrieves the number of layers of this MultiPropertyGroup. + * @return returns the number of layers + */ + virtual Lib3MF_uint32 GetLayerCount() = 0; + + /** + * IMultiPropertyGroup::AddLayer - Adds a MultiPropertyLayer to this MultiPropertyGroup. + * @param[in] TheLayer - The MultiPropertyLayer to add to this MultiPropertyGroup + * @return returns the index of this MultiPropertyLayer + */ + virtual Lib3MF_uint32 AddLayer(const Lib3MF::sMultiPropertyLayer TheLayer) = 0; + + /** + * IMultiPropertyGroup::GetLayer - Obtains a MultiPropertyLayer of this MultiPropertyGroup. + * @param[in] nLayerIndex - The Index of the MultiPropertyLayer queried + * @return The MultiPropertyLayer with index LayerIndex within MultiPropertyGroup + */ + virtual Lib3MF::sMultiPropertyLayer GetLayer(const Lib3MF_uint32 nLayerIndex) = 0; + + /** + * IMultiPropertyGroup::RemoveLayer - Removes a MultiPropertyLayer from this MultiPropertyGroup. + * @param[in] nLayerIndex - The Index of the MultiPropertyLayer to be removed + */ + virtual void RemoveLayer(const Lib3MF_uint32 nLayerIndex) = 0; + +}; + +typedef IBaseSharedPtr PIMultiPropertyGroup; + + +/************************************************************************************************************************* + Class interface for Attachment +**************************************************************************************************************************/ + +class IAttachment : public virtual IBase { +public: + /** + * IAttachment::GetPath - Retrieves an attachment's package path. This function will be removed in a later release. + * @return returns the attachment's package path string + */ + virtual std::string GetPath() = 0; + + /** + * IAttachment::SetPath - Sets an attachment's package path. This function will be removed in a later release. + * @param[in] sPath - new path of the attachment. + */ + virtual void SetPath(const std::string & sPath) = 0; + + /** + * IAttachment::PackagePart - Returns the PackagePart that is this attachment. + * @return The PackagePart of this attachment. + */ + virtual IPackagePart * PackagePart() = 0; + + /** + * IAttachment::GetRelationShipType - Retrieves an attachment's relationship type + * @return returns the attachment's package relationship type string + */ + virtual std::string GetRelationShipType() = 0; + + /** + * IAttachment::SetRelationShipType - Sets an attachment's relationship type. + * @param[in] sPath - new relationship type string. + */ + virtual void SetRelationShipType(const std::string & sPath) = 0; + + /** + * IAttachment::WriteToFile - Writes out the attachment as file. + * @param[in] sFileName - file to write into. + */ + virtual void WriteToFile(const std::string & sFileName) = 0; + + /** + * IAttachment::ReadFromFile - Reads an attachment from a file. The path of this file is only read when this attachment is being written as part of the 3MF packege, or via the WriteToFile or WriteToBuffer-methods. + * @param[in] sFileName - file to read from. + */ + virtual void ReadFromFile(const std::string & sFileName) = 0; + + /** + * IAttachment::ReadFromCallback - Reads a model and from the data provided by a callback function + * @param[in] pTheReadCallback - callback function + * @param[in] nStreamSize - number of bytes the callback returns + * @param[in] pTheSeekCallback - callback function + * @param[in] nUserData - Userdata that is passed to the callback function + */ + virtual void ReadFromCallback(const Lib3MF::ReadCallback pTheReadCallback, const Lib3MF_uint64 nStreamSize, const Lib3MF::SeekCallback pTheSeekCallback, const Lib3MF_pvoid pUserData) = 0; + + /** + * IAttachment::GetStreamSize - Retrieves the size of the attachment stream + * @return the stream size + */ + virtual Lib3MF_uint64 GetStreamSize() = 0; + + /** + * IAttachment::WriteToBuffer - Writes out the attachment into a buffer + * @param[in] nBufferBufferSize - Number of elements in buffer + * @param[out] pBufferNeededCount - will be filled with the count of the written structs, or needed buffer size. + * @param[out] pBufferBuffer - uint8 buffer of Buffer to write into + */ + virtual void WriteToBuffer(Lib3MF_uint64 nBufferBufferSize, Lib3MF_uint64* pBufferNeededCount, Lib3MF_uint8 * pBufferBuffer) = 0; + + /** + * IAttachment::ReadFromBuffer - Reads an attachment from a memory buffer + * @param[in] nBufferBufferSize - Number of elements in buffer + * @param[in] pBufferBuffer - Buffer to read from + */ + virtual void ReadFromBuffer(const Lib3MF_uint64 nBufferBufferSize, const Lib3MF_uint8 * pBufferBuffer) = 0; + +}; + +typedef IBaseSharedPtr PIAttachment; + + +/************************************************************************************************************************* + Class interface for Texture2D +**************************************************************************************************************************/ + +class ITexture2D : public virtual IResource { +public: + /** + * ITexture2D::GetAttachment - Retrieves the attachment located at the path of the texture. + * @return attachment that holds the texture's image information. + */ + virtual IAttachment * GetAttachment() = 0; + + /** + * ITexture2D::SetAttachment - Sets the texture's package path to the path of the attachment. + * @param[in] pAttachment - attachment that holds the texture's image information. + */ + virtual void SetAttachment(IAttachment* pAttachment) = 0; + + /** + * ITexture2D::GetContentType - Retrieves a texture's content type. + * @return returns content type enum. + */ + virtual Lib3MF::eTextureType GetContentType() = 0; + + /** + * ITexture2D::SetContentType - Retrieves a texture's content type. + * @param[in] eContentType - new Content Type + */ + virtual void SetContentType(const Lib3MF::eTextureType eContentType) = 0; + + /** + * ITexture2D::GetTileStyleUV - Retrieves a texture's tilestyle type. + * @param[out] eTileStyleU - returns tilestyle type enum. + * @param[out] eTileStyleV - returns tilestyle type enum. + */ + virtual void GetTileStyleUV(Lib3MF::eTextureTileStyle & eTileStyleU, Lib3MF::eTextureTileStyle & eTileStyleV) = 0; + + /** + * ITexture2D::SetTileStyleUV - Sets a texture's tilestyle type. + * @param[in] eTileStyleU - new tilestyle type enum. + * @param[in] eTileStyleV - new tilestyle type enum. + */ + virtual void SetTileStyleUV(const Lib3MF::eTextureTileStyle eTileStyleU, const Lib3MF::eTextureTileStyle eTileStyleV) = 0; + + /** + * ITexture2D::GetFilter - Retrieves a texture's filter type. + * @return returns filter type enum. + */ + virtual Lib3MF::eTextureFilter GetFilter() = 0; + + /** + * ITexture2D::SetFilter - Sets a texture's filter type. + * @param[in] eFilter - sets new filter type enum. + */ + virtual void SetFilter(const Lib3MF::eTextureFilter eFilter) = 0; + +}; + +typedef IBaseSharedPtr PITexture2D; + + +/************************************************************************************************************************* + Class interface for BuildItem +**************************************************************************************************************************/ + +class IBuildItem : public virtual IBase { +public: + /** + * IBuildItem::GetObjectResource - Retrieves the object resource associated to a build item + * @return returns the associated resource instance + */ + virtual IObject * GetObjectResource() = 0; + + /** + * IBuildItem::GetUUID - returns, whether a build item has a UUID and, if true, the build item's UUID + * @param[out] bHasUUID - flag whether the build item has a UUID + * @return the UUID as string of the form 'xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx' + */ + virtual std::string GetUUID(bool & bHasUUID) = 0; + + /** + * IBuildItem::SetUUID - sets the build item's UUID + * @param[in] sUUID - the UUID as string of the form 'xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx' + */ + virtual void SetUUID(const std::string & sUUID) = 0; + + /** + * IBuildItem::GetObjectResourceID - Retrieves the object UniqueResourceID associated to a build item + * @return returns the UniqueResourceID of the object + */ + virtual Lib3MF_uint32 GetObjectResourceID() = 0; + + /** + * IBuildItem::HasObjectTransform - Checks, if a build item has a non-identity transformation matrix + * @return returns true, if the transformation matrix is not the identity + */ + virtual bool HasObjectTransform() = 0; + + /** + * IBuildItem::GetObjectTransform - Retrieves a build item's transformation matrix. + * @return returns the transformation matrix + */ + virtual Lib3MF::sTransform GetObjectTransform() = 0; + + /** + * IBuildItem::SetObjectTransform - Sets a build item's transformation matrix. + * @param[in] Transform - new transformation matrix + */ + virtual void SetObjectTransform(const Lib3MF::sTransform Transform) = 0; + + /** + * IBuildItem::GetPartNumber - Retrieves a build item's part number string + * @return Returns a build item's part number string + */ + virtual std::string GetPartNumber() = 0; + + /** + * IBuildItem::SetPartNumber - Sets a build item's part number string + * @param[in] sSetPartnumber - new part number string for referencing parts from the outside world + */ + virtual void SetPartNumber(const std::string & sSetPartnumber) = 0; + + /** + * IBuildItem::GetMetaDataGroup - Returns the metadatagroup of this build item + * @return returns an Instance of the metadatagroup of this build item + */ + virtual IMetaDataGroup * GetMetaDataGroup() = 0; + + /** + * IBuildItem::GetOutbox - Returns the outbox of a build item + * @return Outbox of this build item + */ + virtual Lib3MF::sBox GetOutbox() = 0; + +}; + +typedef IBaseSharedPtr PIBuildItem; + + +/************************************************************************************************************************* + Class interface for BuildItemIterator +**************************************************************************************************************************/ + +class IBuildItemIterator : public virtual IBase { +public: + /** + * IBuildItemIterator::MoveNext - Iterates to the next build item in the list. + * @return Iterates to the next build item in the list. + */ + virtual bool MoveNext() = 0; + + /** + * IBuildItemIterator::MovePrevious - Iterates to the previous build item in the list. + * @return Iterates to the previous build item in the list. + */ + virtual bool MovePrevious() = 0; + + /** + * IBuildItemIterator::GetCurrent - Returns the build item the iterator points at. + * @return returns the build item instance. + */ + virtual IBuildItem * GetCurrent() = 0; + + /** + * IBuildItemIterator::Clone - Creates a new build item iterator with the same build item list. + * @return returns the cloned Iterator instance + */ + virtual IBuildItemIterator * Clone() = 0; + + /** + * IBuildItemIterator::Count - Returns the number of build items the iterator captures. + * @return returns the number of build items the iterator captures. + */ + virtual Lib3MF_uint64 Count() = 0; + +}; + +typedef IBaseSharedPtr PIBuildItemIterator; + + +/************************************************************************************************************************* + Class interface for Slice +**************************************************************************************************************************/ + +class ISlice : public virtual IBase { +public: + /** + * ISlice::SetVertices - Set all vertices of a slice. All polygons will be cleared. + * @param[in] nVerticesBufferSize - Number of elements in buffer + * @param[in] pVerticesBuffer - contains the positions. + */ + virtual void SetVertices(const Lib3MF_uint64 nVerticesBufferSize, const Lib3MF::sPosition2D * pVerticesBuffer) = 0; + + /** + * ISlice::GetVertices - Get all vertices of a slice + * @param[in] nVerticesBufferSize - Number of elements in buffer + * @param[out] pVerticesNeededCount - will be filled with the count of the written structs, or needed buffer size. + * @param[out] pVerticesBuffer - Position2D buffer of contains the positions. + */ + virtual void GetVertices(Lib3MF_uint64 nVerticesBufferSize, Lib3MF_uint64* pVerticesNeededCount, Lib3MF::sPosition2D * pVerticesBuffer) = 0; + + /** + * ISlice::GetVertexCount - Get the number of vertices in a slice + * @return the number of vertices in the slice + */ + virtual Lib3MF_uint64 GetVertexCount() = 0; + + /** + * ISlice::AddPolygon - Add a new polygon to this slice + * @param[in] nIndicesBufferSize - Number of elements in buffer + * @param[in] pIndicesBuffer - the new indices of the new polygon + * @return the index of the new polygon + */ + virtual Lib3MF_uint64 AddPolygon(const Lib3MF_uint64 nIndicesBufferSize, const Lib3MF_uint32 * pIndicesBuffer) = 0; + + /** + * ISlice::GetPolygonCount - Get the number of polygons in the slice + * @return the number of polygons in the slice + */ + virtual Lib3MF_uint64 GetPolygonCount() = 0; + + /** + * ISlice::SetPolygonIndices - Set all indices of a polygon + * @param[in] nIndex - the index of the polygon to manipulate + * @param[in] nIndicesBufferSize - Number of elements in buffer + * @param[in] pIndicesBuffer - the new indices of the index-th polygon + */ + virtual void SetPolygonIndices(const Lib3MF_uint64 nIndex, const Lib3MF_uint64 nIndicesBufferSize, const Lib3MF_uint32 * pIndicesBuffer) = 0; + + /** + * ISlice::GetPolygonIndices - Get all vertices of a slice + * @param[in] nIndex - the index of the polygon to manipulate + * @param[in] nIndicesBufferSize - Number of elements in buffer + * @param[out] pIndicesNeededCount - will be filled with the count of the written structs, or needed buffer size. + * @param[out] pIndicesBuffer - uint32 buffer of the indices of the index-th polygon + */ + virtual void GetPolygonIndices(const Lib3MF_uint64 nIndex, Lib3MF_uint64 nIndicesBufferSize, Lib3MF_uint64* pIndicesNeededCount, Lib3MF_uint32 * pIndicesBuffer) = 0; + + /** + * ISlice::GetPolygonIndexCount - Get the number of vertices in a slice + * @param[in] nIndex - the index of the polygon to manipulate + * @return the number of indices of the index-th polygon + */ + virtual Lib3MF_uint64 GetPolygonIndexCount(const Lib3MF_uint64 nIndex) = 0; + + /** + * ISlice::GetZTop - Get the upper Z-Coordinate of this slice. + * @return the upper Z-Coordinate of this slice + */ + virtual Lib3MF_double GetZTop() = 0; + +}; + +typedef IBaseSharedPtr PISlice; + + +/************************************************************************************************************************* + Class interface for SliceStack +**************************************************************************************************************************/ + +class ISliceStack : public virtual IResource { +public: + /** + * ISliceStack::GetBottomZ - Get the lower Z-Coordinate of the slice stack. + * @return the lower Z-Coordinate the slice stack + */ + virtual Lib3MF_double GetBottomZ() = 0; + + /** + * ISliceStack::GetSliceCount - Returns the number of slices + * @return the number of slices + */ + virtual Lib3MF_uint64 GetSliceCount() = 0; + + /** + * ISliceStack::GetSlice - Query a slice from the slice stack + * @param[in] nSliceIndex - the index of the slice + * @return the Slice instance + */ + virtual ISlice * GetSlice(const Lib3MF_uint64 nSliceIndex) = 0; + + /** + * ISliceStack::AddSlice - Returns the number of slices + * @param[in] dZTop - upper Z coordinate of the slice + * @return a new Slice instance + */ + virtual ISlice * AddSlice(const Lib3MF_double dZTop) = 0; + + /** + * ISliceStack::GetSliceRefCount - Returns the number of slice refs + * @return the number of slicereferences + */ + virtual Lib3MF_uint64 GetSliceRefCount() = 0; + + /** + * ISliceStack::AddSliceStackReference - Adds another existing slicestack as sliceref in this slicestack + * @param[in] pTheSliceStack - the slicestack to use as sliceref + */ + virtual void AddSliceStackReference(ISliceStack* pTheSliceStack) = 0; + + /** + * ISliceStack::GetSliceStackReference - Adds another existing slicestack as sliceref in this slicestack + * @param[in] nSliceRefIndex - the index of the slice ref + * @return the slicestack that is used as sliceref + */ + virtual ISliceStack * GetSliceStackReference(const Lib3MF_uint64 nSliceRefIndex) = 0; + + /** + * ISliceStack::CollapseSliceReferences - Removes the indirection of slices via slice-refs, i.e. creates the slices of all slice refs of this SliceStack as actual slices of this SliceStack. All previously existing slices or slicerefs will be removed. + */ + virtual void CollapseSliceReferences() = 0; + + /** + * ISliceStack::SetOwnPath - Sets the package path where this Slice should be stored. Input an empty string to reset the path + * @param[in] sPath - the package path where this Slice should be stored + */ + virtual void SetOwnPath(const std::string & sPath) = 0; + + /** + * ISliceStack::GetOwnPath - Obtains the package path where this Slice should be stored. Returns an empty string if the slicestack is stored within the root model. + * @return the package path where this Slice will be stored + */ + virtual std::string GetOwnPath() = 0; + +}; + +typedef IBaseSharedPtr PISliceStack; + + +/************************************************************************************************************************* + Class interface for Consumer +**************************************************************************************************************************/ + +class IConsumer : public virtual IBase { +public: + /** + * IConsumer::GetConsumerID - Gets the consumerid + * @return A unique identifier for the consumers + */ + virtual std::string GetConsumerID() = 0; + + /** + * IConsumer::GetKeyID - Getts the keyid + * @return The identifier for the key of this consumer + */ + virtual std::string GetKeyID() = 0; + + /** + * IConsumer::GetKeyValue - Gets the keyvalue associated with this consumer + * @return The public key, when available, of this consumer + */ + virtual std::string GetKeyValue() = 0; + +}; + +typedef IBaseSharedPtr PIConsumer; + + +/************************************************************************************************************************* + Class interface for AccessRight +**************************************************************************************************************************/ + +class IAccessRight : public virtual IBase { +public: + /** + * IAccessRight::GetConsumer - Gets the consumer associated with this access right + * @return The consumer instance + */ + virtual IConsumer * GetConsumer() = 0; + + /** + * IAccessRight::GetWrappingAlgorithm - Gets the associated encryption algorithm + * @return The algorithm used for the key in this accessright + */ + virtual Lib3MF::eWrappingAlgorithm GetWrappingAlgorithm() = 0; + + /** + * IAccessRight::GetMgfAlgorithm - Gets the associated mask generation function algorithm + * @return The MFG1 algorithm + */ + virtual Lib3MF::eMgfAlgorithm GetMgfAlgorithm() = 0; + + /** + * IAccessRight::GetDigestMethod - Gets the digest method assoicated + * @return The digest method for this accessright + */ + virtual Lib3MF::eDigestMethod GetDigestMethod() = 0; + +}; + +typedef IBaseSharedPtr PIAccessRight; + + +/************************************************************************************************************************* + Class interface for ContentEncryptionParams +**************************************************************************************************************************/ + +class IContentEncryptionParams : public virtual IBase { +public: + /** + * IContentEncryptionParams::GetEncryptionAlgorithm - Returns the encryption method to be used in this encryption process + * @return + */ + virtual Lib3MF::eEncryptionAlgorithm GetEncryptionAlgorithm() = 0; + + /** + * IContentEncryptionParams::GetKey - Gets the key for the resource associated + * @param[in] nByteDataBufferSize - Number of elements in buffer + * @param[out] pByteDataNeededCount - will be filled with the count of the written structs, or needed buffer size. + * @param[out] pByteDataBuffer - uint8 buffer of Pointer to a buffer where to place the key. + */ + virtual void GetKey(Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64* pByteDataNeededCount, Lib3MF_uint8 * pByteDataBuffer) = 0; + + /** + * IContentEncryptionParams::GetInitializationVector - Gets the IV data + * @param[in] nByteDataBufferSize - Number of elements in buffer + * @param[out] pByteDataNeededCount - will be filled with the count of the written structs, or needed buffer size. + * @param[out] pByteDataBuffer - uint8 buffer of Pointer to a buffer where to place the data. + */ + virtual void GetInitializationVector(Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64* pByteDataNeededCount, Lib3MF_uint8 * pByteDataBuffer) = 0; + + /** + * IContentEncryptionParams::GetAuthenticationTag - A handler descriptor that uniquely identifies the context of the resource. Each resource will be assigned a different value + * @param[in] nByteDataBufferSize - Number of elements in buffer + * @param[out] pByteDataNeededCount - will be filled with the count of the written structs, or needed buffer size. + * @param[out] pByteDataBuffer - uint8 buffer of Pointer to a buffer where to place the data. + */ + virtual void GetAuthenticationTag(Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64* pByteDataNeededCount, Lib3MF_uint8 * pByteDataBuffer) = 0; + + /** + * IContentEncryptionParams::SetAuthenticationTag - Sets the authentication tag + * @param[in] nByteDataBufferSize - Number of elements in buffer + * @param[in] pByteDataBuffer - The authentication tag size + */ + virtual void SetAuthenticationTag(const Lib3MF_uint64 nByteDataBufferSize, const Lib3MF_uint8 * pByteDataBuffer) = 0; + + /** + * IContentEncryptionParams::GetAdditionalAuthenticationData - A handler descriptor that uniquely identifies the context of the resource. Each resource will be assigned a different value + * @param[in] nByteDataBufferSize - Number of elements in buffer + * @param[out] pByteDataNeededCount - will be filled with the count of the written structs, or needed buffer size. + * @param[out] pByteDataBuffer - uint8 buffer of Buffer where the data will be placed + */ + virtual void GetAdditionalAuthenticationData(Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64* pByteDataNeededCount, Lib3MF_uint8 * pByteDataBuffer) = 0; + + /** + * IContentEncryptionParams::GetDescriptor - A handler descriptor that uniquely identifies the context of the resource. Each resource will be assigned a different value + * @return + */ + virtual Lib3MF_uint64 GetDescriptor() = 0; + + /** + * IContentEncryptionParams::GetKeyUUID - Gets the resourcedatagroup keyuuid + * @return The resourcedatagroup keyuuid that may be use to reference an external key + */ + virtual std::string GetKeyUUID() = 0; + +}; + +typedef IBaseSharedPtr PIContentEncryptionParams; + + +/************************************************************************************************************************* + Class interface for ResourceData +**************************************************************************************************************************/ + +class IResourceData : public virtual IBase { +public: + /** + * IResourceData::GetPath - Gets the encrypted part path + * @return The part path + */ + virtual IPackagePart * GetPath() = 0; + + /** + * IResourceData::GetEncryptionAlgorithm - Gets the encryption algorithm used to encrypt this ResourceData + * @return The encryption algorithm + */ + virtual Lib3MF::eEncryptionAlgorithm GetEncryptionAlgorithm() = 0; + + /** + * IResourceData::GetCompression - Tells whether this ResourceData is compressed or not + * @return The compression method + */ + virtual Lib3MF::eCompression GetCompression() = 0; + + /** + * IResourceData::GetAdditionalAuthenticationData - Tells whether this ResourceData is compressed or not + * @param[in] nByteDataBufferSize - Number of elements in buffer + * @param[out] pByteDataNeededCount - will be filled with the count of the written structs, or needed buffer size. + * @param[out] pByteDataBuffer - uint8 buffer of The compression method + */ + virtual void GetAdditionalAuthenticationData(Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64* pByteDataNeededCount, Lib3MF_uint8 * pByteDataBuffer) = 0; + +}; + +typedef IBaseSharedPtr PIResourceData; + + +/************************************************************************************************************************* + Class interface for ResourceDataGroup +**************************************************************************************************************************/ + +class IResourceDataGroup : public virtual IBase { +public: + /** + * IResourceDataGroup::GetKeyUUID - Sets the resourcedatagroup keyuuid + * @return The new resourcedatagroup keyuuid. + */ + virtual std::string GetKeyUUID() = 0; + + /** + * IResourceDataGroup::AddAccessRight - Add accessright to resourcedatagroup element + * @param[in] pConsumer - The Consumer reference + * @param[in] eWrappingAlgorithm - The key wrapping algorithm to be used + * @param[in] eMgfAlgorithm - The mask generation function to be used + * @param[in] eDigestMethod - The digest mechanism to be used + * @return The acess right instance + */ + virtual IAccessRight * AddAccessRight(IConsumer* pConsumer, const Lib3MF::eWrappingAlgorithm eWrappingAlgorithm, const Lib3MF::eMgfAlgorithm eMgfAlgorithm, const Lib3MF::eDigestMethod eDigestMethod) = 0; + + /** + * IResourceDataGroup::FindAccessRightByConsumer - Finds the AccessRight associated with a Consumer + * @param[in] pConsumer - The Consumer instance + * @return The AcessRight instance + */ + virtual IAccessRight * FindAccessRightByConsumer(IConsumer* pConsumer) = 0; + + /** + * IResourceDataGroup::RemoveAccessRight - Removes access from a Consumer on this resource data group + * @param[in] pConsumer - The Consumer instance + */ + virtual void RemoveAccessRight(IConsumer* pConsumer) = 0; + +}; + +typedef IBaseSharedPtr PIResourceDataGroup; + + +/************************************************************************************************************************* + Class interface for KeyStore +**************************************************************************************************************************/ + +class IKeyStore : public virtual IBase { +public: + /** + * IKeyStore::AddConsumer - Adds a consumer to the keystore + * @param[in] sConsumerID - A unique identifier for the consumer + * @param[in] sKeyID - The id of the key of the consumer + * @param[in] sKeyValue - The public key for this consumer in PEM format + * @return The consumer instance + */ + virtual IConsumer * AddConsumer(const std::string & sConsumerID, const std::string & sKeyID, const std::string & sKeyValue) = 0; + + /** + * IKeyStore::GetConsumerCount - Gets the number of consumers in the keystore + * @return The consumer count + */ + virtual Lib3MF_uint64 GetConsumerCount() = 0; + + /** + * IKeyStore::GetConsumer - Get a consumer from the keystore + * @param[in] nConsumerIndex - The index of the consumer + * @return The consumer instance + */ + virtual IConsumer * GetConsumer(const Lib3MF_uint64 nConsumerIndex) = 0; + + /** + * IKeyStore::RemoveConsumer - Removes a consumer from the keystore + * @param[in] pConsumer - The consumer instance to remove + */ + virtual void RemoveConsumer(IConsumer* pConsumer) = 0; + + /** + * IKeyStore::FindConsumer - Finds a consumer by ID + * @param[in] sConsumerID - The ID of the consumer + * @return The consumer instance + */ + virtual IConsumer * FindConsumer(const std::string & sConsumerID) = 0; + + /** + * IKeyStore::GetResourceDataGroupCount - Gets the number of resource data group in the keysore + * @return The number of resource data available + */ + virtual Lib3MF_uint64 GetResourceDataGroupCount() = 0; + + /** + * IKeyStore::AddResourceDataGroup - Adds a resource data group into the keystore. + * @return The resource data group instance + */ + virtual IResourceDataGroup * AddResourceDataGroup() = 0; + + /** + * IKeyStore::GetResourceDataGroup - Gets a resource data group + * @param[in] nResourceDataIndex - The index of the resource data + * @return The resource data group instance + */ + virtual IResourceDataGroup * GetResourceDataGroup(const Lib3MF_uint64 nResourceDataIndex) = 0; + + /** + * IKeyStore::RemoveResourceDataGroup - Removes a resource data group + * @param[in] pResourceDataGroup - The resource data group instance + */ + virtual void RemoveResourceDataGroup(IResourceDataGroup* pResourceDataGroup) = 0; + + /** + * IKeyStore::FindResourceDataGroup - Finds a resource data group that contains a particular resourcedata + * @param[in] pPartPath - The target path for the resourcedata hold by the resource data group + * @return The data resource instance + */ + virtual IResourceDataGroup * FindResourceDataGroup(IPackagePart* pPartPath) = 0; + + /** + * IKeyStore::AddResourceData - Add resourcedata to resourcedatagroup element + * @param[in] pResourceDataGroup - The resource data group where to add this resource data + * @param[in] pPartPath - The path of the part to be encrypted + * @param[in] eAlgorithm - The encryption algorithm to be used to encrypt this resource + * @param[in] eCompression - Whether compression should be used prior to encryption + * @param[in] nAdditionalAuthenticationDataBufferSize - Number of elements in buffer + * @param[in] pAdditionalAuthenticationDataBuffer - Additional data to be encrypted along the contents for better security + * @return The data resource instance + */ + virtual IResourceData * AddResourceData(IResourceDataGroup* pResourceDataGroup, IPackagePart* pPartPath, const Lib3MF::eEncryptionAlgorithm eAlgorithm, const Lib3MF::eCompression eCompression, const Lib3MF_uint64 nAdditionalAuthenticationDataBufferSize, const Lib3MF_uint8 * pAdditionalAuthenticationDataBuffer) = 0; + + /** + * IKeyStore::RemoveResourceData - Removes a resource data + * @param[in] pResourceData - The resource data to be removed + */ + virtual void RemoveResourceData(IResourceData* pResourceData) = 0; + + /** + * IKeyStore::FindResourceData - Finds a resource data on this resource group + * @param[in] pResourcePath - The target path for the resourcedata + * @return The resource data instance + */ + virtual IResourceData * FindResourceData(IPackagePart* pResourcePath) = 0; + + /** + * IKeyStore::GetResourceDataCount - Gets the number of resource data in the keysore + * @return The number of resource data available + */ + virtual Lib3MF_uint64 GetResourceDataCount() = 0; + + /** + * IKeyStore::GetResourceData - Gets a resource data + * @param[in] nResourceDataIndex - The index of the resource data + * @return The data resource instance + */ + virtual IResourceData * GetResourceData(const Lib3MF_uint64 nResourceDataIndex) = 0; + + /** + * IKeyStore::GetUUID - Gets the keystore UUID + * @param[out] bHasUUID - flag whether the keystore has a UUID + * @return returns the keystore uuid. + */ + virtual std::string GetUUID(bool & bHasUUID) = 0; + + /** + * IKeyStore::SetUUID - Sets the keystore UUID + * @param[in] sUUID - The new keystore uuid. + */ + virtual void SetUUID(const std::string & sUUID) = 0; + +}; + +typedef IBaseSharedPtr PIKeyStore; + + +/************************************************************************************************************************* + Class interface for Model +**************************************************************************************************************************/ + +class IModel : public virtual IBase { +public: + /** + * IModel::RootModelPart - Returns the PackagePart within the OPC package that holds the root model. + * @return the PackagePart within the OPC package that holds the model-file + */ + virtual IPackagePart * RootModelPart() = 0; + + /** + * IModel::FindOrCreatePackagePart - Returns a new PackagePart for use within the OPC package. + * @param[in] sAbsolutePath - the absolute Path (physical location) within the OPC package + * @return the new PackagePart within the OPC package + */ + virtual IPackagePart * FindOrCreatePackagePart(const std::string & sAbsolutePath) = 0; + + /** + * IModel::SetUnit - sets the units of a model. + * @param[in] eUnit - Unit enum value for the model unit + */ + virtual void SetUnit(const Lib3MF::eModelUnit eUnit) = 0; + + /** + * IModel::GetUnit - returns the units of a model. + * @return Unit enum value for the model unit + */ + virtual Lib3MF::eModelUnit GetUnit() = 0; + + /** + * IModel::GetLanguage - retrieves the language of a model + * @return language identifier + */ + virtual std::string GetLanguage() = 0; + + /** + * IModel::SetLanguage - sets the language of a model + * @param[in] sLanguage - language identifier + */ + virtual void SetLanguage(const std::string & sLanguage) = 0; + + /** + * IModel::QueryWriter - creates a model writer instance for a specific file type + * @param[in] sWriterClass - string identifier for the file type + * @return string identifier for the file type + */ + virtual IWriter * QueryWriter(const std::string & sWriterClass) = 0; + + /** + * IModel::QueryReader - creates a model reader instance for a specific file type + * @param[in] sReaderClass - string identifier for the file type + * @return string identifier for the file type + */ + virtual IReader * QueryReader(const std::string & sReaderClass) = 0; + + /** + * IModel::GetTexture2DByID - finds a model texture by its UniqueResourceID + * @param[in] nUniqueResourceID - UniqueResourceID + * @return returns the texture2d instance + */ + virtual ITexture2D * GetTexture2DByID(const Lib3MF_uint32 nUniqueResourceID) = 0; + + /** + * IModel::GetPropertyTypeByID - returns a Property's type + * @param[in] nUniqueResourceID - Resource ID of the Property to Query + * @return returns a Property's type + */ + virtual Lib3MF::ePropertyType GetPropertyTypeByID(const Lib3MF_uint32 nUniqueResourceID) = 0; + + /** + * IModel::GetBaseMaterialGroupByID - finds a model base material group by its UniqueResourceID + * @param[in] nUniqueResourceID - UniqueResourceID + * @return returns the BaseMaterialGroup instance + */ + virtual IBaseMaterialGroup * GetBaseMaterialGroupByID(const Lib3MF_uint32 nUniqueResourceID) = 0; + + /** + * IModel::GetTexture2DGroupByID - finds a model texture2d group by its UniqueResourceID + * @param[in] nUniqueResourceID - UniqueResourceID + * @return returns the Texture2DGroup instance + */ + virtual ITexture2DGroup * GetTexture2DGroupByID(const Lib3MF_uint32 nUniqueResourceID) = 0; + + /** + * IModel::GetCompositeMaterialsByID - finds a model CompositeMaterials by its UniqueResourceID + * @param[in] nUniqueResourceID - UniqueResourceID + * @return returns the CompositeMaterials instance + */ + virtual ICompositeMaterials * GetCompositeMaterialsByID(const Lib3MF_uint32 nUniqueResourceID) = 0; + + /** + * IModel::GetMultiPropertyGroupByID - finds a model MultiPropertyGroup by its UniqueResourceID + * @param[in] nUniqueResourceID - UniqueResourceID + * @return returns the MultiPropertyGroup instance + */ + virtual IMultiPropertyGroup * GetMultiPropertyGroupByID(const Lib3MF_uint32 nUniqueResourceID) = 0; + + /** + * IModel::GetMeshObjectByID - finds a mesh object by its UniqueResourceID + * @param[in] nUniqueResourceID - UniqueResourceID + * @return returns the mesh object instance + */ + virtual IMeshObject * GetMeshObjectByID(const Lib3MF_uint32 nUniqueResourceID) = 0; + + /** + * IModel::GetComponentsObjectByID - finds a components object by its UniqueResourceID + * @param[in] nUniqueResourceID - UniqueResourceID + * @return returns the components object instance + */ + virtual IComponentsObject * GetComponentsObjectByID(const Lib3MF_uint32 nUniqueResourceID) = 0; + + /** + * IModel::GetColorGroupByID - finds a model color group by its UniqueResourceID + * @param[in] nUniqueResourceID - UniqueResourceID + * @return returns the ColorGroup instance + */ + virtual IColorGroup * GetColorGroupByID(const Lib3MF_uint32 nUniqueResourceID) = 0; + + /** + * IModel::GetSliceStackByID - finds a model slicestack by its UniqueResourceID + * @param[in] nUniqueResourceID - UniqueResourceID + * @return returns the slicestack instance + */ + virtual ISliceStack * GetSliceStackByID(const Lib3MF_uint32 nUniqueResourceID) = 0; + + /** + * IModel::GetBuildUUID - returns, whether a build has a UUID and, if true, the build's UUID + * @param[out] bHasUUID - flag whether the build has a UUID + * @return the UUID as string of the form 'xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx' + */ + virtual std::string GetBuildUUID(bool & bHasUUID) = 0; + + /** + * IModel::SetBuildUUID - sets the build's UUID + * @param[in] sUUID - the UUID as string of the form 'xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx' + */ + virtual void SetBuildUUID(const std::string & sUUID) = 0; + + /** + * IModel::GetBuildItems - creates a build item iterator instance with all build items. + * @return returns the iterator instance. + */ + virtual IBuildItemIterator * GetBuildItems() = 0; + + /** + * IModel::GetOutbox - Returns the outbox of a Model + * @return Outbox of this Model + */ + virtual Lib3MF::sBox GetOutbox() = 0; + + /** + * IModel::GetResources - creates a resource iterator instance with all resources. + * @return returns the iterator instance. + */ + virtual IResourceIterator * GetResources() = 0; + + /** + * IModel::GetObjects - creates a resource iterator instance with all object resources. + * @return returns the iterator instance. + */ + virtual IObjectIterator * GetObjects() = 0; + + /** + * IModel::GetMeshObjects - creates a resource iterator instance with all mesh object resources. + * @return returns the iterator instance. + */ + virtual IMeshObjectIterator * GetMeshObjects() = 0; + + /** + * IModel::GetComponentsObjects - creates a resource iterator instance with all components object resources. + * @return returns the iterator instance. + */ + virtual IComponentsObjectIterator * GetComponentsObjects() = 0; + + /** + * IModel::GetTexture2Ds - creates a Texture2DIterator instance with all texture2d resources. + * @return returns the iterator instance. + */ + virtual ITexture2DIterator * GetTexture2Ds() = 0; + + /** + * IModel::GetBaseMaterialGroups - creates a BaseMaterialGroupIterator instance with all base material resources. + * @return returns the iterator instance. + */ + virtual IBaseMaterialGroupIterator * GetBaseMaterialGroups() = 0; + + /** + * IModel::GetColorGroups - creates a ColorGroupIterator instance with all ColorGroup resources. + * @return returns the iterator instance. + */ + virtual IColorGroupIterator * GetColorGroups() = 0; + + /** + * IModel::GetTexture2DGroups - creates a Texture2DGroupIterator instance with all base material resources. + * @return returns the iterator instance. + */ + virtual ITexture2DGroupIterator * GetTexture2DGroups() = 0; + + /** + * IModel::GetCompositeMaterials - creates a CompositeMaterialsIterator instance with all CompositeMaterials resources. + * @return returns the iterator instance. + */ + virtual ICompositeMaterialsIterator * GetCompositeMaterials() = 0; + + /** + * IModel::GetMultiPropertyGroups - creates a MultiPropertyGroupsIterator instance with all MultiPropertyGroup resources. + * @return returns the iterator instance. + */ + virtual IMultiPropertyGroupIterator * GetMultiPropertyGroups() = 0; + + /** + * IModel::GetSliceStacks - creates a resource iterator instance with all slice stack resources. + * @return returns the iterator instance. + */ + virtual ISliceStackIterator * GetSliceStacks() = 0; + + /** + * IModel::MergeToModel - Merges all components and objects which are referenced by a build item into a mesh. The memory is duplicated and a new model is created. + * @return returns the merged model instance + */ + virtual IModel * MergeToModel() = 0; + + /** + * IModel::AddMeshObject - adds an empty mesh object to the model. + * @return returns the mesh object instance + */ + virtual IMeshObject * AddMeshObject() = 0; + + /** + * IModel::AddComponentsObject - adds an empty component object to the model. + * @return returns the components object instance + */ + virtual IComponentsObject * AddComponentsObject() = 0; + + /** + * IModel::AddSliceStack - creates a new model slicestack by its id + * @param[in] dZBottom - Bottom Z value of the slicestack + * @return returns the new slicestack instance + */ + virtual ISliceStack * AddSliceStack(const Lib3MF_double dZBottom) = 0; + + /** + * IModel::AddTexture2DFromAttachment - adds a texture2d resource to the model. Its path is given by that of an existing attachment. + * @param[in] pTextureAttachment - attachment containing the image data. + * @return returns the new texture instance. + */ + virtual ITexture2D * AddTexture2DFromAttachment(IAttachment* pTextureAttachment) = 0; + + /** + * IModel::AddBaseMaterialGroup - adds an empty BaseMaterialGroup resource to the model. + * @return returns the new base material instance. + */ + virtual IBaseMaterialGroup * AddBaseMaterialGroup() = 0; + + /** + * IModel::AddColorGroup - adds an empty ColorGroup resource to the model. + * @return returns the new ColorGroup instance. + */ + virtual IColorGroup * AddColorGroup() = 0; + + /** + * IModel::AddTexture2DGroup - adds an empty Texture2DGroup resource to the model. + * @param[in] pTexture2DInstance - The texture2D instance of the created Texture2DGroup. + * @return returns the new Texture2DGroup instance. + */ + virtual ITexture2DGroup * AddTexture2DGroup(ITexture2D* pTexture2DInstance) = 0; + + /** + * IModel::AddCompositeMaterials - adds an empty CompositeMaterials resource to the model. + * @param[in] pBaseMaterialGroupInstance - The BaseMaterialGroup instance of the created CompositeMaterials. + * @return returns the new CompositeMaterials instance. + */ + virtual ICompositeMaterials * AddCompositeMaterials(IBaseMaterialGroup* pBaseMaterialGroupInstance) = 0; + + /** + * IModel::AddMultiPropertyGroup - adds an empty MultiPropertyGroup resource to the model. + * @return returns the new MultiPropertyGroup instance. + */ + virtual IMultiPropertyGroup * AddMultiPropertyGroup() = 0; + + /** + * IModel::AddBuildItem - adds a build item to the model. + * @param[in] pObject - Object instance. + * @param[in] Transform - Transformation matrix. + * @return returns the build item instance. + */ + virtual IBuildItem * AddBuildItem(IObject* pObject, const Lib3MF::sTransform Transform) = 0; + + /** + * IModel::RemoveBuildItem - removes a build item from the model + * @param[in] pBuildItemInstance - Build item to remove. + */ + virtual void RemoveBuildItem(IBuildItem* pBuildItemInstance) = 0; + + /** + * IModel::GetMetaDataGroup - Returns the metadata of the model as MetaDataGroup + * @return returns an Instance of the metadatagroup of the model + */ + virtual IMetaDataGroup * GetMetaDataGroup() = 0; + + /** + * IModel::AddAttachment - adds an attachment stream to the model. The OPC part will be related to the model stream with a certain relationship type. + * @param[in] sURI - Path of the attachment + * @param[in] sRelationShipType - Relationship type of the attachment + * @return Instance of the attachment object + */ + virtual IAttachment * AddAttachment(const std::string & sURI, const std::string & sRelationShipType) = 0; + + /** + * IModel::RemoveAttachment - Removes attachment from the model. + * @param[in] pAttachmentInstance - Attachment instance to remove + */ + virtual void RemoveAttachment(IAttachment* pAttachmentInstance) = 0; + + /** + * IModel::GetAttachment - retrieves an attachment stream object from the model.. + * @param[in] nIndex - Index of the attachment stream + * @return Instance of the attachment object + */ + virtual IAttachment * GetAttachment(const Lib3MF_uint32 nIndex) = 0; + + /** + * IModel::FindAttachment - retrieves an attachment stream object from the model. + * @param[in] sURI - Path URI in the package + * @return Instance of the attachment object + */ + virtual IAttachment * FindAttachment(const std::string & sURI) = 0; + + /** + * IModel::GetAttachmentCount - retrieves the number of attachments of the model. + * @return Returns the number of attachments. + */ + virtual Lib3MF_uint32 GetAttachmentCount() = 0; + + /** + * IModel::HasPackageThumbnailAttachment - Retrieve whether the OPC package contains a package thumbnail. + * @return returns whether the OPC package contains a package thumbnail + */ + virtual bool HasPackageThumbnailAttachment() = 0; + + /** + * IModel::CreatePackageThumbnailAttachment - Create a new or the existing package thumbnail for the OPC package. + * @return Instance of a new or the existing thumbnailattachment object. + */ + virtual IAttachment * CreatePackageThumbnailAttachment() = 0; + + /** + * IModel::GetPackageThumbnailAttachment - Get the attachment to the OPC package containing the package thumbnail. + * @return Instance of the thumbnailattachment object or NULL. + */ + virtual IAttachment * GetPackageThumbnailAttachment() = 0; + + /** + * IModel::RemovePackageThumbnailAttachment - Remove the attachment to the OPC package containing the package thumbnail. + */ + virtual void RemovePackageThumbnailAttachment() = 0; + + /** + * IModel::AddCustomContentType - Adds a new Content Type to the model. + * @param[in] sExtension - File Extension + * @param[in] sContentType - Content Type Identifier + */ + virtual void AddCustomContentType(const std::string & sExtension, const std::string & sContentType) = 0; + + /** + * IModel::RemoveCustomContentType - Removes a custom Content Type from the model (UTF8 version). + * @param[in] sExtension - File Extension + */ + virtual void RemoveCustomContentType(const std::string & sExtension) = 0; + + /** + * IModel::SetRandomNumberCallback - Sets the random number generator callback for use in the library + * @param[in] pTheCallback - callback function + * @param[in] nUserData - Userdata to be passed to the callback function + */ + virtual void SetRandomNumberCallback(const Lib3MF::RandomNumberCallback pTheCallback, const Lib3MF_pvoid pUserData) = 0; + + /** + * IModel::GetKeyStore - Gets the keystore associated with this model + * @return The package keystore + */ + virtual IKeyStore * GetKeyStore() = 0; + +}; + +typedef IBaseSharedPtr PIModel; + + +/************************************************************************************************************************* + Global functions declarations +**************************************************************************************************************************/ +class CWrapper { +public: + /** + * Ilib3mf::GetLibraryVersion - retrieves the binary version of this library. + * @param[out] nMajor - returns the major version of this library + * @param[out] nMinor - returns the minor version of this library + * @param[out] nMicro - returns the micro version of this library + */ + static void GetLibraryVersion(Lib3MF_uint32 & nMajor, Lib3MF_uint32 & nMinor, Lib3MF_uint32 & nMicro); + + /** + * Ilib3mf::GetPrereleaseInformation - retrieves prerelease information of this library. + * @return Does the library provide prerelease version? + * @param[out] sPrereleaseInfo - retrieves prerelease information of this library. + */ + static bool GetPrereleaseInformation(std::string & sPrereleaseInfo); + + /** + * Ilib3mf::GetBuildInformation - retrieves build information of this library. + * @return Does the library provide build version? + * @param[out] sBuildInformation - retrieves build information of this library. + */ + static bool GetBuildInformation(std::string & sBuildInformation); + + /** + * Ilib3mf::GetSpecificationVersion - retrieves whether a specification is supported, and if so, which version. + * @param[in] sSpecificationURL - URL of extension to check + * @param[out] bIsSupported - returns whether this specification is supported + * @param[out] nMajor - returns the major version of the extension (if IsSupported) + * @param[out] nMinor - returns the minor version of the extension (if IsSupported) + * @param[out] nMicro - returns the micro version of the extension (if IsSupported) + */ + static void GetSpecificationVersion(const std::string & sSpecificationURL, bool & bIsSupported, Lib3MF_uint32 & nMajor, Lib3MF_uint32 & nMinor, Lib3MF_uint32 & nMicro); + + /** + * Ilib3mf::CreateModel - creates an empty model instance. + * @return returns an empty model instance + */ + static IModel * CreateModel(); + + /** + * Ilib3mf::Release - releases shared ownership of an object instance + * @param[in] pInstance - the object instance to release + */ + static void Release(IBase* pInstance); + + /** + * Ilib3mf::Acquire - acquires shared ownership of an object instance + * @param[in] pInstance - the object instance to acquire + */ + static void Acquire(IBase* pInstance); + + /** + * Ilib3mf::GetLastError - Retrieves the last error string of an instance + * @param[in] pInstance - Object where the error occured. + * @param[out] sLastErrorString - Last Error String + * @return Returns if the instance has a last error. + */ + static bool GetLastError(IBase* pInstance, std::string & sLastErrorString); + + /** + * Ilib3mf::RetrieveProgressMessage - Return an English text for a progress identifier.|Note: this is the only function you can call from your callback function. + * @param[in] eTheProgressIdentifier - the progress identifier that is passed to the callback function + * @param[out] sProgressMessage - English text for the progress identifier + */ + static void RetrieveProgressMessage(const Lib3MF::eProgressIdentifier eTheProgressIdentifier, std::string & sProgressMessage); + + /** + * Ilib3mf::RGBAToColor - Creates a Color from uint8 RGBA values + * @param[in] nRed - Red value of color (0-255) + * @param[in] nGreen - Green value of color (0-255) + * @param[in] nBlue - Blue value of color (0-255) + * @param[in] nAlpha - Alpha value of color (0-255) + * @return Assembled color + */ + static Lib3MF::sColor RGBAToColor(const Lib3MF_uint8 nRed, const Lib3MF_uint8 nGreen, const Lib3MF_uint8 nBlue, const Lib3MF_uint8 nAlpha); + + /** + * Ilib3mf::FloatRGBAToColor - Creates a Color from uint8 RGBA values + * @param[in] fRed - Red value of color (0-1) + * @param[in] fGreen - Green value of color (0-1) + * @param[in] fBlue - Blue value of color (0-1) + * @param[in] fAlpha - Alpha value of color (0-1) + * @return Assembled color + */ + static Lib3MF::sColor FloatRGBAToColor(const Lib3MF_single fRed, const Lib3MF_single fGreen, const Lib3MF_single fBlue, const Lib3MF_single fAlpha); + + /** + * Ilib3mf::ColorToRGBA - Calculates uint8-RGBA-values from a Color + * @param[in] TheColor - Color to handle + * @param[out] nRed - Red value of color (0-255) + * @param[out] nGreen - Green value of color (0-255) + * @param[out] nBlue - Blue value of color (0-255) + * @param[out] nAlpha - Alpha value of color (0-255) + */ + static void ColorToRGBA(const Lib3MF::sColor TheColor, Lib3MF_uint8 & nRed, Lib3MF_uint8 & nGreen, Lib3MF_uint8 & nBlue, Lib3MF_uint8 & nAlpha); + + /** + * Ilib3mf::ColorToFloatRGBA - Calculates float-RGBA-values from a Color + * @param[in] TheColor - Color to handle + * @param[out] fRed - Red value of color (0-1) + * @param[out] fGreen - Green value of color (0-1) + * @param[out] fBlue - Blue value of color (0-1) + * @param[out] fAlpha - Alpha value of color (0-1) + */ + static void ColorToFloatRGBA(const Lib3MF::sColor TheColor, Lib3MF_single & fRed, Lib3MF_single & fGreen, Lib3MF_single & fBlue, Lib3MF_single & fAlpha); + + /** + * Ilib3mf::GetIdentityTransform - Creates an identity transform + * @return Transformation matrix. + */ + static Lib3MF::sTransform GetIdentityTransform(); + + /** + * Ilib3mf::GetUniformScaleTransform - Creates a uniform scale transform + * @param[in] fFactor - Factor in X, Y and Z + * @return Transformation matrix. + */ + static Lib3MF::sTransform GetUniformScaleTransform(const Lib3MF_single fFactor); + + /** + * Ilib3mf::GetScaleTransform - Creates a scale transform + * @param[in] fFactorX - Factor in X + * @param[in] fFactorY - Factor in Y + * @param[in] fFactorZ - Factor in Z + * @return Transformation matrix. + */ + static Lib3MF::sTransform GetScaleTransform(const Lib3MF_single fFactorX, const Lib3MF_single fFactorY, const Lib3MF_single fFactorZ); + + /** + * Ilib3mf::GetTranslationTransform - Creates an translation transform + * @param[in] fVectorX - Translation in X + * @param[in] fVectorY - Translation in Y + * @param[in] fVectorZ - Translation in Z + * @return Transformation matrix. + */ + static Lib3MF::sTransform GetTranslationTransform(const Lib3MF_single fVectorX, const Lib3MF_single fVectorY, const Lib3MF_single fVectorZ); + +}; + +} // namespace Impl +} // namespace Lib3MF + +#endif // __LIB3MF_CPPINTERFACES diff --git a/Include/lib3mf_types.hpp b/Include/lib3mf_types.hpp new file mode 100644 index 0000000..c13c034 --- /dev/null +++ b/Include/lib3mf_types.hpp @@ -0,0 +1,502 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +This file has been generated by the Automatic Component Toolkit (ACT) version 1.6.0. + +Abstract: This is an autogenerated C++-Header file with basic types in +order to allow an easy use of the 3MF Library + +Interface version: 2.2.0 + +*/ + +#ifndef __LIB3MF_TYPES_HEADER_CPP +#define __LIB3MF_TYPES_HEADER_CPP + + +/************************************************************************************************************************* + Scalar types definition +**************************************************************************************************************************/ + +#ifdef LIB3MF_USELEGACYINTEGERTYPES + +typedef unsigned char Lib3MF_uint8; +typedef unsigned short Lib3MF_uint16 ; +typedef unsigned int Lib3MF_uint32; +typedef unsigned long long Lib3MF_uint64; +typedef char Lib3MF_int8; +typedef short Lib3MF_int16; +typedef int Lib3MF_int32; +typedef long long Lib3MF_int64; + +#else // LIB3MF_USELEGACYINTEGERTYPES + +#include + +typedef uint8_t Lib3MF_uint8; +typedef uint16_t Lib3MF_uint16; +typedef uint32_t Lib3MF_uint32; +typedef uint64_t Lib3MF_uint64; +typedef int8_t Lib3MF_int8; +typedef int16_t Lib3MF_int16; +typedef int32_t Lib3MF_int32; +typedef int64_t Lib3MF_int64 ; + +#endif // LIB3MF_USELEGACYINTEGERTYPES + +typedef float Lib3MF_single; +typedef double Lib3MF_double; + +/************************************************************************************************************************* + General type definitions +**************************************************************************************************************************/ + +typedef Lib3MF_int32 Lib3MFResult; +typedef void * Lib3MFHandle; +typedef void * Lib3MF_pvoid; + +/************************************************************************************************************************* + Version for Lib3MF +**************************************************************************************************************************/ + +#define LIB3MF_VERSION_MAJOR 2 +#define LIB3MF_VERSION_MINOR 2 +#define LIB3MF_VERSION_MICRO 0 +#define LIB3MF_VERSION_PRERELEASEINFO "" +#define LIB3MF_VERSION_BUILDINFO "" + +/************************************************************************************************************************* + Error constants for Lib3MF +**************************************************************************************************************************/ + +#define LIB3MF_SUCCESS 0 +#define LIB3MF_ERROR_NOTIMPLEMENTED 1 +#define LIB3MF_ERROR_INVALIDPARAM 2 +#define LIB3MF_ERROR_INVALIDCAST 3 +#define LIB3MF_ERROR_BUFFERTOOSMALL 4 +#define LIB3MF_ERROR_GENERICEXCEPTION 5 +#define LIB3MF_ERROR_COULDNOTLOADLIBRARY 6 +#define LIB3MF_ERROR_COULDNOTFINDLIBRARYEXPORT 7 +#define LIB3MF_ERROR_INCOMPATIBLEBINARYVERSION 8 +#define LIB3MF_ERROR_CALCULATIONABORTED 10 +#define LIB3MF_ERROR_SHOULDNOTBECALLED 11 +#define LIB3MF_ERROR_READERCLASSUNKNOWN 100 +#define LIB3MF_ERROR_WRITERCLASSUNKNOWN 101 +#define LIB3MF_ERROR_ITERATORINVALIDINDEX 102 +#define LIB3MF_ERROR_INVALIDMODELRESOURCE 103 +#define LIB3MF_ERROR_RESOURCENOTFOUND 104 +#define LIB3MF_ERROR_INVALIDMODEL 105 +#define LIB3MF_ERROR_INVALIDOBJECT 106 +#define LIB3MF_ERROR_INVALIDMESHOBJECT 107 +#define LIB3MF_ERROR_INVALIDCOMPONENTSOBJECT 108 +#define LIB3MF_ERROR_INVALIDCOMPONENT 109 +#define LIB3MF_ERROR_INVALIDBUILDITEM 110 +#define LIB3MF_ERROR_INVALIDBASEMATERIALGROUP 111 +#define LIB3MF_ERROR_INVALIDSLICESTACKRESOURCE 112 +#define LIB3MF_ERROR_INVALIDTEXTURERESOURCE 113 +#define LIB3MF_ERROR_INVALIDCOLORGROUP 114 +#define LIB3MF_ERROR_INVALIDTEXTURE2DGROUP 115 +#define LIB3MF_ERROR_INVALIDCOMPOSITEMATERIALS 116 +#define LIB3MF_ERROR_INVALIDMULTIPROPERTYGROUP 117 +#define LIB3MF_ERROR_INVALIDRESOURCEINDEX 120 +#define LIB3MF_ERROR_ATTACHMENTNOTFOUND 121 +#define LIB3MF_ERROR_FORBIDDENCYCLICREFERENCE 130 +#define LIB3MF_ERROR_INVALIDATTACHMENTSTREAM 131 +#define LIB3MF_ERROR_INVALIDPROPERTYCOUNT 132 +#define LIB3MF_ERROR_UNKOWNPROGRESSIDENTIFIER 140 +#define LIB3MF_ERROR_ELEMENTCOUNTEXCEEDSLIMIT 141 +#define LIB3MF_ERROR_BEAMLATTICE_INVALID_OBJECTTYPE 2000 +#define LIB3MF_ERROR_INVALIDKEYSTORE 3000 +#define LIB3MF_ERROR_INVALIDKEYSTORECONSUMER 3001 +#define LIB3MF_ERROR_KEYSTORECONSUMERNOTFOUND 3002 +#define LIB3MF_ERROR_KEYSTORERESOURCEDATANOTFOUND 3003 +#define LIB3MF_ERROR_SECURECONTEXTNOTREGISTERED 3004 + +/************************************************************************************************************************* + Declaration of handle classes +**************************************************************************************************************************/ + +typedef Lib3MFHandle Lib3MF_Base; +typedef Lib3MFHandle Lib3MF_Writer; +typedef Lib3MFHandle Lib3MF_Reader; +typedef Lib3MFHandle Lib3MF_PackagePart; +typedef Lib3MFHandle Lib3MF_Resource; +typedef Lib3MFHandle Lib3MF_ResourceIterator; +typedef Lib3MFHandle Lib3MF_SliceStackIterator; +typedef Lib3MFHandle Lib3MF_ObjectIterator; +typedef Lib3MFHandle Lib3MF_MeshObjectIterator; +typedef Lib3MFHandle Lib3MF_ComponentsObjectIterator; +typedef Lib3MFHandle Lib3MF_Texture2DIterator; +typedef Lib3MFHandle Lib3MF_BaseMaterialGroupIterator; +typedef Lib3MFHandle Lib3MF_ColorGroupIterator; +typedef Lib3MFHandle Lib3MF_Texture2DGroupIterator; +typedef Lib3MFHandle Lib3MF_CompositeMaterialsIterator; +typedef Lib3MFHandle Lib3MF_MultiPropertyGroupIterator; +typedef Lib3MFHandle Lib3MF_MetaData; +typedef Lib3MFHandle Lib3MF_MetaDataGroup; +typedef Lib3MFHandle Lib3MF_Object; +typedef Lib3MFHandle Lib3MF_MeshObject; +typedef Lib3MFHandle Lib3MF_BeamLattice; +typedef Lib3MFHandle Lib3MF_Component; +typedef Lib3MFHandle Lib3MF_ComponentsObject; +typedef Lib3MFHandle Lib3MF_BeamSet; +typedef Lib3MFHandle Lib3MF_BaseMaterialGroup; +typedef Lib3MFHandle Lib3MF_ColorGroup; +typedef Lib3MFHandle Lib3MF_Texture2DGroup; +typedef Lib3MFHandle Lib3MF_CompositeMaterials; +typedef Lib3MFHandle Lib3MF_MultiPropertyGroup; +typedef Lib3MFHandle Lib3MF_Attachment; +typedef Lib3MFHandle Lib3MF_Texture2D; +typedef Lib3MFHandle Lib3MF_BuildItem; +typedef Lib3MFHandle Lib3MF_BuildItemIterator; +typedef Lib3MFHandle Lib3MF_Slice; +typedef Lib3MFHandle Lib3MF_SliceStack; +typedef Lib3MFHandle Lib3MF_Consumer; +typedef Lib3MFHandle Lib3MF_AccessRight; +typedef Lib3MFHandle Lib3MF_ContentEncryptionParams; +typedef Lib3MFHandle Lib3MF_ResourceData; +typedef Lib3MFHandle Lib3MF_ResourceDataGroup; +typedef Lib3MFHandle Lib3MF_KeyStore; +typedef Lib3MFHandle Lib3MF_Model; + +namespace Lib3MF { + + /************************************************************************************************************************* + Declaration of enums + **************************************************************************************************************************/ + + enum class ePropertyType : Lib3MF_int32 { + NoPropertyType = 0, + BaseMaterial = 1, + TexCoord = 2, + Colors = 3, + Composite = 4, + Multi = 5 + }; + + enum class eSlicesMeshResolution : Lib3MF_int32 { + Fullres = 0, + Lowres = 1 + }; + + enum class eModelUnit : Lib3MF_int32 { + MicroMeter = 0, + MilliMeter = 1, + CentiMeter = 2, + Inch = 3, + Foot = 4, + Meter = 5 + }; + + enum class eObjectType : Lib3MF_int32 { + Other = 0, + Model = 1, + Support = 2, + SolidSupport = 3 + }; + + enum class eTextureType : Lib3MF_int32 { + Unknown = 0, + PNG = 1, + JPEG = 2 + }; + + enum class eTextureTileStyle : Lib3MF_int32 { + Wrap = 0, + Mirror = 1, + Clamp = 2, + NoTileStyle = 3 + }; + + enum class eTextureFilter : Lib3MF_int32 { + Auto = 0, + Linear = 1, + Nearest = 2 + }; + + enum class eBeamLatticeCapMode : Lib3MF_int32 { + Sphere = 0, + HemiSphere = 1, + Butt = 2 + }; + + enum class eBeamLatticeClipMode : Lib3MF_int32 { + NoClipMode = 0, + Inside = 1, + Outside = 2 + }; + + enum class eBeamLatticeBallMode : Lib3MF_int32 { + None = 0, + Mixed = 1, + All = 2 + }; + + enum class eProgressIdentifier : Lib3MF_int32 { + QUERYCANCELED = 0, + DONE = 1, + CLEANUP = 2, + READSTREAM = 3, + EXTRACTOPCPACKAGE = 4, + READNONROOTMODELS = 5, + READROOTMODEL = 6, + READRESOURCES = 7, + READMESH = 8, + READSLICES = 9, + READBUILD = 10, + READCUSTOMATTACHMENT = 11, + READTEXTURETACHMENTS = 12, + CREATEOPCPACKAGE = 13, + WRITEMODELSTOSTREAM = 14, + WRITEROOTMODEL = 15, + WRITENONROOTMODELS = 16, + WRITEATTACHMENTS = 17, + WRITECONTENTTYPES = 18, + WRITENOBJECTS = 19, + WRITENODES = 20, + WRITETRIANGLES = 21, + WRITESLICES = 22, + WRITEKEYSTORE = 23 + }; + + enum class eBlendMethod : Lib3MF_int32 { + NoBlendMethod = 0, + Mix = 1, + Multiply = 2 + }; + + enum class eEncryptionAlgorithm : Lib3MF_int32 { + AES256_GCM = 1 + }; + + enum class eWrappingAlgorithm : Lib3MF_int32 { + RSA_OAEP = 0 + }; + + enum class eMgfAlgorithm : Lib3MF_int32 { + MGF1_SHA1 = 160, + MGF1_SHA224 = 224, + MGF1_SHA256 = 256, + MGF1_SHA384 = 384, + MGF1_SHA512 = 512 + }; + + enum class eDigestMethod : Lib3MF_int32 { + SHA1 = 160, + SHA256 = 256 + }; + + enum class eCompression : Lib3MF_int32 { + NoCompression = 0, + Deflate = 1 + }; + + /************************************************************************************************************************* + Declaration of structs + **************************************************************************************************************************/ + + #pragma pack (1) + + typedef struct { + Lib3MF_uint32 m_Indices[3]; + } sTriangle; + + typedef struct { + Lib3MF_uint32 m_ResourceID; + Lib3MF_uint32 m_PropertyIDs[3]; + } sTriangleProperties; + + typedef struct { + Lib3MF_single m_Coordinates[3]; + } sPosition; + + typedef struct { + Lib3MF_single m_Coordinates[2]; + } sPosition2D; + + typedef struct { + Lib3MF_uint32 m_PropertyID; + Lib3MF_double m_MixingRatio; + } sCompositeConstituent; + + typedef struct { + Lib3MF_uint32 m_ResourceID; + eBlendMethod m_TheBlendMethod; + } sMultiPropertyLayer; + + typedef struct { + Lib3MF_double m_U; + Lib3MF_double m_V; + } sTex2Coord; + + typedef struct { + Lib3MF_single m_Fields[4][3]; + } sTransform; + + typedef struct { + Lib3MF_single m_MinCoordinate[3]; + Lib3MF_single m_MaxCoordinate[3]; + } sBox; + + typedef struct { + Lib3MF_uint8 m_Red; + Lib3MF_uint8 m_Green; + Lib3MF_uint8 m_Blue; + Lib3MF_uint8 m_Alpha; + } sColor; + + typedef struct { + Lib3MF_uint32 m_Indices[2]; + Lib3MF_double m_Radii[2]; + eBeamLatticeCapMode m_CapModes[2]; + } sBeam; + + typedef struct { + Lib3MF_uint32 m_Index; + Lib3MF_double m_Radius; + } sBall; + + #pragma pack () + + /************************************************************************************************************************* + Declaration of function pointers + **************************************************************************************************************************/ + + /** + * ProgressCallback - A callback function + * + * @param[out] pAbort - Returns whether the calculation should be aborted + * @param[in] dProgressValue - The value of the progress function: values in the interval [0,1] are progress; < mean no progress update + * @param[in] eProgressIdentifier - An identifier of progress + * @param[in] pUserData - Userdata that is passed to the callback function + */ + typedef void(*ProgressCallback)(bool *, Lib3MF_double, Lib3MF::eProgressIdentifier, Lib3MF_pvoid); + + /** + * WriteCallback - Callback to call for writing a data chunk + * + * @param[in] nByteData - Pointer to the data to be written + * @param[in] nNumBytes - Number of bytes to write + * @param[in] pUserData - Userdata that is passed to the callback function + */ + typedef void(*WriteCallback)(Lib3MF_uint64, Lib3MF_uint64, Lib3MF_pvoid); + + /** + * ReadCallback - Callback to call for reading a data chunk + * + * @param[in] nByteData - Pointer to a buffer to read data into + * @param[in] nNumBytes - Number of bytes to read + * @param[in] pUserData - Userdata that is passed to the callback function + */ + typedef void(*ReadCallback)(Lib3MF_uint64, Lib3MF_uint64, Lib3MF_pvoid); + + /** + * SeekCallback - Callback to call for seeking in the stream + * + * @param[in] nPosition - Position in the stream to move to + * @param[in] pUserData - Userdata that is passed to the callback function + */ + typedef void(*SeekCallback)(Lib3MF_uint64, Lib3MF_pvoid); + + /** + * RandomNumberCallback - Callback to generate random numbers + * + * @param[in] nByteData - Pointer to a buffer to read data into + * @param[in] nNumBytes - Size of available bytes in the buffer + * @param[in] pUserData - Userdata that is passed to the callback function + * @param[out] pBytesWritten - Number of bytes generated when succeed. 0 or less if failed. + */ + typedef void(*RandomNumberCallback)(Lib3MF_uint64, Lib3MF_uint64, Lib3MF_pvoid, Lib3MF_uint64 *); + + /** + * KeyWrappingCallback - A callback used to wrap (encrypt) the content key available in keystore resource group + * + * @param[in] pKEKParams - The information about the parameters used used to wrap the key to the contents + * @param[in] nInBufferBufferSize - Number of elements in buffer + * @param[in] pInBufferBuffer - uint8 buffer of Buffer to the input value. When encrypting, this should be the plain key. When decrypting, this should be the key cipher. + * @param[in] nOutBufferBufferSize - Number of elements in buffer + * @param[out] pOutBufferNeededCount - will be filled with the count of the written elements, or needed buffer size. + * @param[out] pOutBufferBuffer - uint8 buffer of Buffer where the data will be placed. When encrypting, this will be the key cipher. When decrypting, this will be the plain key. When buffer is null, neededBytes contains the required bytes to run. + * @param[in] pUserData - Userdata that is passed to the callback function + * @param[out] pStatus - The needed/encrypted/decrypted bytes when succeed or zero when error. + */ + typedef void(*KeyWrappingCallback)(Lib3MF_AccessRight, Lib3MF_uint64, const Lib3MF_uint8 *, const Lib3MF_uint64, Lib3MF_uint64*, Lib3MF_uint8 *, Lib3MF_pvoid, Lib3MF_uint64 *); + + /** + * ContentEncryptionCallback - A callback to encrypt/decrypt content called on each resource encrypted. This might be called several times depending on content size. If Input is not available(either null or size is 0), clients must return the result of authenticated tag generation/validation. + * + * @param[in] pCEKParams - The params of the encryption process. Client must set/check AuthenticationTag when closing the encryption/decryption process. + * @param[in] nInputBufferSize - Number of elements in buffer + * @param[in] pInputBuffer - uint8 buffer of Buffer to the original data. In encrypting, this will be the plain data. If decrypting, this will be the cipher data + * @param[in] nOutputBufferSize - Number of elements in buffer + * @param[out] pOutputNeededCount - will be filled with the count of the written elements, or needed buffer size. + * @param[out] pOutputBuffer - uint8 buffer of Buffer to hold the transformed data. When encrypting, this will be the cipher data. When decrypting, this shall be the plain data. If buffer is null, neededBytes return the necessary amount of bytes. + * @param[in] pUserData - Userdata that is passed to the callback function + * @param[out] pStatus - The needed/encrypted/decrypted/verified bytes when succeed or zero when error. + */ + typedef void(*ContentEncryptionCallback)(Lib3MF_ContentEncryptionParams, Lib3MF_uint64, const Lib3MF_uint8 *, const Lib3MF_uint64, Lib3MF_uint64*, Lib3MF_uint8 *, Lib3MF_pvoid, Lib3MF_uint64 *); + +} // namespace Lib3MF; + +// define legacy C-names for enums, structs and function types +typedef Lib3MF::ePropertyType eLib3MFPropertyType; +typedef Lib3MF::eSlicesMeshResolution eLib3MFSlicesMeshResolution; +typedef Lib3MF::eModelUnit eLib3MFModelUnit; +typedef Lib3MF::eObjectType eLib3MFObjectType; +typedef Lib3MF::eTextureType eLib3MFTextureType; +typedef Lib3MF::eTextureTileStyle eLib3MFTextureTileStyle; +typedef Lib3MF::eTextureFilter eLib3MFTextureFilter; +typedef Lib3MF::eBeamLatticeCapMode eLib3MFBeamLatticeCapMode; +typedef Lib3MF::eBeamLatticeClipMode eLib3MFBeamLatticeClipMode; +typedef Lib3MF::eBeamLatticeBallMode eLib3MFBeamLatticeBallMode; +typedef Lib3MF::eProgressIdentifier eLib3MFProgressIdentifier; +typedef Lib3MF::eBlendMethod eLib3MFBlendMethod; +typedef Lib3MF::eEncryptionAlgorithm eLib3MFEncryptionAlgorithm; +typedef Lib3MF::eWrappingAlgorithm eLib3MFWrappingAlgorithm; +typedef Lib3MF::eMgfAlgorithm eLib3MFMgfAlgorithm; +typedef Lib3MF::eDigestMethod eLib3MFDigestMethod; +typedef Lib3MF::eCompression eLib3MFCompression; +typedef Lib3MF::sTriangle sLib3MFTriangle; +typedef Lib3MF::sTriangleProperties sLib3MFTriangleProperties; +typedef Lib3MF::sPosition sLib3MFPosition; +typedef Lib3MF::sPosition2D sLib3MFPosition2D; +typedef Lib3MF::sCompositeConstituent sLib3MFCompositeConstituent; +typedef Lib3MF::sMultiPropertyLayer sLib3MFMultiPropertyLayer; +typedef Lib3MF::sTex2Coord sLib3MFTex2Coord; +typedef Lib3MF::sTransform sLib3MFTransform; +typedef Lib3MF::sBox sLib3MFBox; +typedef Lib3MF::sColor sLib3MFColor; +typedef Lib3MF::sBeam sLib3MFBeam; +typedef Lib3MF::sBall sLib3MFBall; +typedef Lib3MF::ProgressCallback Lib3MFProgressCallback; +typedef Lib3MF::WriteCallback Lib3MFWriteCallback; +typedef Lib3MF::ReadCallback Lib3MFReadCallback; +typedef Lib3MF::SeekCallback Lib3MFSeekCallback; +typedef Lib3MF::RandomNumberCallback Lib3MFRandomNumberCallback; +typedef Lib3MF::KeyWrappingCallback Lib3MFKeyWrappingCallback; +typedef Lib3MF::ContentEncryptionCallback Lib3MFContentEncryptionCallback; + +#endif // __LIB3MF_TYPES_HEADER_CPP diff --git a/Lib3MF.rc b/Lib3MF.rc new file mode 100644 index 0000000..aa78c90 --- /dev/null +++ b/Lib3MF.rc @@ -0,0 +1,143 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// Inglese (Stati Uniti) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + +#endif // Inglese (Stati Uniti) resources +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// Italiano (Italia) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ITA) +LANGUAGE LANG_ITALIAN, SUBLANG_ITALIAN +#pragma code_page(1252) + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 1,0,0,1 + PRODUCTVERSION 1,0,0,1 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x40004L + FILETYPE 0x2L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "041004b0" + BEGIN + VALUE "CompanyName", "TODO: " + VALUE "FileDescription", "TODO: " + VALUE "FileVersion", "1.0.0.1" + VALUE "InternalName", "Lib3MF.dll" + VALUE "LegalCopyright", "Copyright (C) 2021" + VALUE "OriginalFilename", "Lib3MF.dll" + VALUE "ProductName", "TODO: " + VALUE "ProductVersion", "1.0.0.1" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x410, 1200 + END +END + +IDR_VERSION2 VERSIONINFO + FILEVERSION 1,0,0,1 + PRODUCTVERSION 1,0,0,1 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x40004L + FILETYPE 0x0L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "041004b0" + BEGIN + VALUE "CompanyName", "TODO: " + VALUE "FileDescription", "TODO: " + VALUE "FileVersion", "1.0.0.1" + VALUE "InternalName", "Lib3MF.rc" + VALUE "LegalCopyright", "Copyright (C) 2021" + VALUE "OriginalFilename", "Lib3MF.rc" + VALUE "ProductName", "TODO: " + VALUE "ProductVersion", "1.0.0.1" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x410, 1200 + END +END + +#endif // Italiano (Italia) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/Lib3MF.sln b/Lib3MF.sln new file mode 100644 index 0000000..4ca2b44 --- /dev/null +++ b/Lib3MF.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.31624.102 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Lib3MF", "Lib3MF.vcxproj", "{0A45738F-DFED-421D-85E5-E720334AE2C6}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {0A45738F-DFED-421D-85E5-E720334AE2C6}.Debug|x64.ActiveCfg = Debug|x64 + {0A45738F-DFED-421D-85E5-E720334AE2C6}.Debug|x64.Build.0 = Debug|x64 + {0A45738F-DFED-421D-85E5-E720334AE2C6}.Debug|x86.ActiveCfg = Debug|Win32 + {0A45738F-DFED-421D-85E5-E720334AE2C6}.Debug|x86.Build.0 = Debug|Win32 + {0A45738F-DFED-421D-85E5-E720334AE2C6}.Release|x64.ActiveCfg = Release|x64 + {0A45738F-DFED-421D-85E5-E720334AE2C6}.Release|x64.Build.0 = Release|x64 + {0A45738F-DFED-421D-85E5-E720334AE2C6}.Release|x86.ActiveCfg = Release|Win32 + {0A45738F-DFED-421D-85E5-E720334AE2C6}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {C6A43A5D-44C7-4CB5-AF4F-8A7D1BBB5996} + EndGlobalSection +EndGlobal diff --git a/Lib3MF.vcxproj b/Lib3MF.vcxproj new file mode 100644 index 0000000..8a8358a --- /dev/null +++ b/Lib3MF.vcxproj @@ -0,0 +1,557 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + Win32Proj + {0a45738f-dfed-421d-85e5-e720334ae2c6} + Lib3MF + 10.0.17763.0 + + + + DynamicLibrary + true + v120_xp + Unicode + + + DynamicLibrary + false + v120_xp + true + Unicode + + + DynamicLibrary + true + ClangCL + Unicode + + + DynamicLibrary + false + ClangCL + true + Unicode + + + + + + + + + + + + + + + + + + + + + true + $(Configuration)32\lib3mf.dir + lib3mfD32 + $(SolutionDir)$(Configuration)32\ + + + false + $(Configuration)32\lib3mf.dir + lib3mfR32 + $(SolutionDir)$(Configuration)32\ + + + true + $(Configuration)64\lib3mf.dir\ + lib3mfD64 + $(SolutionDir)\$(Configuration)64\ + + + false + $(Configuration)64\lib3mf.dir + lib3mfR64 + $(SolutionDir)\$(Configuration)64\ + + + + Level3 + true + __LIB3MF_EXPORTS ; NOMINMAX ; WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + /Lib3MF/Include ; /Lib3MF/Include/API ; /Lib3MF/Include/Libraries/zlib ; /Lib3MF/Include/Libraries/libzip + 4996 + + + Console + true + + + _DEB32; _USING_V110_SDK71_;%(PreprocessorDefinitions) + + + copy $(TargetDir)$(TargetName).pdb \EgtDev\Extern\lib3mf\Lib\ +copy $(TargetDir)$(TargetName).lib \EgtDev\Extern\lib3mf\Lib\ +copy $(TargetPath) \EgtProg\DllD32 + + + + + Level3 + true + true + true + __LIB3MF_EXPORTS; NOMINMAX ; WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + /Lib3MF/Include ; /Lib3MF/Include/API ; /Lib3MF/Include/Libraries/zlib ; /Lib3MF/Include/Libraries/libzip + 4996 + + + Console + true + true + true + + + NDEB32; _USING_V110_SDK71_;%(PreprocessorDefinitions) + + + copy $(TargetDir)$(TargetName).lib \EgtDev\Extern\lib3mf\Lib\ +copy $(TargetPath) \EgtProg\Dll32 + + + + + Level3 + true + __LIB3MF_EXPORTS; NOMINMAX; _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + /Lib3MF/Include ; /Lib3MF/Include/API ; /Lib3MF/Include/Libraries/zlib ; /Lib3MF/Include/Libraries/libzip + 4996 + + + Console + true + + + _DEB64; _UNICODE;UNICODE;%(PreprocessorDefinitions) + + + copy $(TargetDir)$(TargetName).pdb \EgtDev\Extern\lib3mf\Lib\ +copy $(TargetDir)$(TargetName).lib \EgtDev\Extern\lib3mf\Lib\ +copy $(TargetPath) \EgtProg\DllD64 + + + + + Level3 + true + true + true + __LIB3MF_EXPORTS; NOMINMAX; NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + /Lib3MF/Include ; /Lib3MF/Include/API ; /Lib3MF/Include/Libraries/zlib ; /Lib3MF/Include/Libraries/libzip + 4996 + false + + + Console + true + true + true + + + NDEB64; _UNICODE;UNICODE;%(PreprocessorDefinitions) + + + copy $(TargetDir)$(TargetName).lib \EgtDev\Extern\lib3mf\Lib\ +copy $(TargetPath) \EgtProg\Dll64 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Lib3MF.vcxproj.filters b/Lib3MF.vcxproj.filters new file mode 100644 index 0000000..0a33a44 --- /dev/null +++ b/Lib3MF.vcxproj.filters @@ -0,0 +1,1157 @@ + + + + + {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 + + + {3375fde0-3795-4ca9-8b83-548323208cf5} + + + {abb8cbe8-6814-4dd5-83a2-a39c1d07514e} + + + {f98db5d4-5dcc-4106-bb3a-6f3b9b89a791} + + + {b7ca3edc-22ac-4083-83e9-b99e8ccb82d9} + + + {2e574825-fa2f-44f3-b88c-48c789db762d} + + + {d7079a7d-0ae1-48d0-ac73-80dcdfe83a5e} + + + {a0ecc9f7-dba6-4e4a-870a-dc2c930d0c06} + + + {698ec7c8-76bf-401f-b8e3-db62f798b356} + + + {d0ff3e8b-614d-4e3c-9367-36974e8c7eec} + + + {470032e5-ed20-49d7-9579-2c0865b11ae1} + + + {48d75704-39fe-42a1-81b2-db8ba606d7c0} + + + {38b42d24-4f78-4dde-85b4-a0637bcb6bdf} + + + {eb89f557-b73c-4c17-9d3f-f5311f2398bf} + + + {86587afe-c90c-46e0-b7f6-5e4f1c030c49} + + + {954142a8-ee6b-4b13-b083-63ee6bbbda3c} + + + {af6e41ba-9238-4406-af4f-e2c3e21ae7f4} + + + {36f55930-c452-4b22-8f7d-1cb021dd2a17} + + + {ea86a00d-7bbd-4977-b9a1-fead893daca9} + + + {76e6c0c9-d5a5-4caa-9dd5-5ee6844928c2} + + + {9fa1519d-1b25-4486-b649-41a0e495357d} + + + {4ae65ce5-d4b8-4554-9412-202b1d30ffd4} + + + {91c20091-e21e-432a-9a2a-7f0976ad3480} + + + {526e5879-5ef4-49af-8742-ab92144ee416} + + + {c27152a2-72e5-4d8d-82d8-8fc37222bf29} + + + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\API + + + File di origine\Common + + + File di origine\Common + + + File di origine\Common + + + File di origine\Common + + + File di origine\Common + + + File di origine\Common + + + File di origine\Common + + + File di origine\Common\Math + + + File di origine\Common\Math + + + File di origine\Common\Math + + + File di origine\Common\Math + + + File di origine\Common\Mesh + + + File di origine\Common\Mesh + + + File di origine\Common\Mesh + + + File di origine\Common\MeshExport + + + File di origine\Common\MeshExport + + + File di origine\Common\MeshExport + + + File di origine\Common\MeshImport + + + File di origine\Common\MeshImport + + + File di origine\Common\MeshInformation + + + File di origine\Common\MeshInformation + + + File di origine\Common\MeshInformation + + + File di origine\Common\MeshInformation + + + File di origine\Common\MeshInformation + + + File di origine\Common\Platform + + + File di origine\Common\Platform + + + File di origine\Common\Platform + + + File di origine\Common\Platform + + + File di origine\Common\Platform + + + File di origine\Common\Platform + + + File di origine\Common\Platform + + + File di origine\Common\Platform + + + File di origine\Common\Platform + + + File di origine\Common\Platform + + + File di origine\Common\Platform + + + File di origine\Common\Platform + + + File di origine\Common\Platform + + + File di origine\Common\Platform + + + File di origine\Common\Platform + + + File di origine\Common\Platform + + + File di origine\Common\Platform + + + File di origine\Common\Platform + + + File di origine\Common\Platform + + + File di origine\Common\Platform + + + File di origine\Common\Platform + + + File di origine\Common\Platform + + + File di origine\Common\Platform + + + File di origine\Common\Platform + + + File di origine\Common\Platform + + + File di origine\Common\OPC + + + File di origine\Common\OPC + + + File di origine\Common\OPC + + + File di origine\Common\OPC + + + File di origine\Common\OPC + + + File di origine\Common\OPC + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip + + + File di origine\Libraries\libzip\Win + + + File di origine\Libraries\libzip\Win + + + File di origine\Libraries\libzip\Win + + + File di origine\Libraries\libzip\Win + + + File di origine\Libraries + + + File di origine\Model\Writer + + + File di origine\Model\Writer + + + File di origine\Model\Writer + + + File di origine\Model\Writer + + + File di origine\Model\Writer + + + File di origine\Model\Writer + + + File di origine\Model\Writer + + + File di origine\Model\Writer + + + File di origine\Model\Writer + + + File di origine\Model\Writer + + + File di origine\Model\Writer + + + File di origine\Model\Writer\SecureContent101 + + + File di origine\Model\Writer\v100 + + + File di origine\Model\Writer\v100 + + + File di origine\Model\Classes + + + File di origine\Model\Classes + + + File di origine\Model\Classes + + + File di origine\Model\Classes + + + File di origine\Model\Classes + + + File di origine\Model\Classes + + + File di origine\Model\Classes + + + File di origine\Model\Classes + + + File di origine\Model\Classes + + + File di origine\Model\Classes + + + File di origine\Model\Classes + + + File di origine\Model\Classes + + + File di origine\Model\Classes + + + File di origine\Model\Classes + + + File di origine\Model\Classes + + + File di origine\Model\Classes + + + File di origine\Model\Classes + + + File di origine\Model\Classes + + + File di origine\Model\Classes + + + File di origine\Model\Classes + + + File di origine\Model\Classes + + + File di origine\Model\Classes + + + File di origine\Model\Classes + + + File di origine\Model\Classes + + + File di origine\Model\Classes + + + File di origine\Model\Classes + + + File di origine\Model\Classes + + + File di origine\Model\Classes + + + File di origine\Model\Classes + + + File di origine\Model\Reader + + + File di origine\Model\Reader + + + File di origine\Model\Reader + + + File di origine\Model\Reader + + + File di origine\Model\Reader + + + File di origine\Model\Reader + + + File di origine\Model\Reader + + + File di origine\Model\Reader + + + File di origine\Model\Reader + + + File di origine\Model\Reader + + + File di origine\Model\Reader + + + File di origine\Model\Reader + + + File di origine\Model\Reader\BeamLattice1702 + + + File di origine\Model\Reader\BeamLattice1702 + + + File di origine\Model\Reader\BeamLattice1702 + + + File di origine\Model\Reader\BeamLattice1702 + + + File di origine\Model\Reader\BeamLattice1702 + + + File di origine\Model\Reader\BeamLattice1702 + + + File di origine\Model\Reader\BeamLattice1702 + + + File di origine\Model\Reader\BeamLattice1702 + + + File di origine\Model\Reader\BeamLattice1702 + + + File di origine\Model\Reader\v100 + + + File di origine\Model\Reader\v100 + + + File di origine\Model\Reader\v100 + + + File di origine\Model\Reader\v100 + + + File di origine\Model\Reader\v100 + + + File di origine\Model\Reader\v100 + + + File di origine\Model\Reader\v100 + + + File di origine\Model\Reader\v100 + + + File di origine\Model\Reader\v100 + + + File di origine\Model\Reader\v100 + + + File di origine\Model\Reader\v100 + + + File di origine\Model\Reader\v100 + + + File di origine\Model\Reader\v100 + + + File di origine\Model\Reader\v100 + + + File di origine\Model\Reader\v100 + + + File di origine\Model\Reader\v100 + + + File di origine\Model\Reader\v100 + + + File di origine\Model\Reader\v100 + + + File di origine\Model\Reader\v100 + + + File di origine\Model\Reader\v100 + + + File di origine\Model\Reader\v100 + + + File di origine\Model\Reader\v100 + + + File di origine\Model\Reader\v100 + + + File di origine\Model\Reader\v100 + + + File di origine\Model\Reader\v093 + + + File di origine\Model\Reader\v093 + + + File di origine\Model\Reader\v093 + + + File di origine\Model\Reader\v093 + + + File di origine\Model\Reader\v093 + + + File di origine\Model\Reader\v093 + + + File di origine\Model\Reader\v093 + + + File di origine\Model\Reader\v093 + + + File di origine\Model\Reader\v093 + + + File di origine\Model\Reader\v093 + + + File di origine\Model\Reader\v093 + + + File di origine\Model\Reader\v093 + + + File di origine\Model\Reader\v093 + + + File di origine\Model\Reader\v093 + + + File di origine\Model\Reader\v093 + + + File di origine\Model\Reader\v093 + + + File di origine\Model\Reader\Slice1507 + + + File di origine\Model\Reader\Slice1507 + + + File di origine\Model\Reader\Slice1507 + + + File di origine\Model\Reader\Slice1507 + + + File di origine\Model\Reader\Slice1507 + + + File di origine\Model\Reader\Slice1507 + + + File di origine\Model\Reader\Slice1507 + + + File di origine\Model\Reader\Slice1507 + + + File di origine\Model\Reader\Slice1507 + + + File di origine\Model\Reader\SecureContent101 + + + File di origine\Model\Reader\SecureContent101 + + + File di origine\Model\Reader\SecureContent101 + + + File di origine\Model\Reader\SecureContent101 + + + File di origine\Model\Reader\SecureContent101 + + + File di origine\Model\Reader\SecureContent101 + + + File di origine\Model\Reader\SecureContent101 + + + File di origine\Model\Reader\SecureContent101 + + + File di origine\Libraries\zlib + + + File di origine\Libraries\zlib + + + File di origine\Libraries\zlib + + + File di origine\Libraries\zlib + + + File di origine\Libraries\zlib + + + File di origine\Libraries\zlib + + + File di origine\Libraries\zlib + + + File di origine\Libraries\zlib + + + File di origine\Libraries\zlib + + + File di origine\Libraries\zlib + + + File di origine\Libraries\zlib + + + File di origine + + + File di origine + + + File di origine + + + + + File di intestazione + + + File di intestazione + + + File di intestazione + + + File di intestazione + + + File di intestazione + + + File di intestazione + + + File di intestazione + + + + + + \ No newline at end of file diff --git a/Resource.rc b/Resource.rc new file mode 100644 index 0000000..e308ac0 --- /dev/null +++ b/Resource.rc @@ -0,0 +1,211 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource2.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// Inglese (Stati Uniti) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource2.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(APSTUDIO_INVOKED) || defined(_DEB32) +#if defined(APSTUDIO_INVOKED) +VS_VERSION_INFO$(_DEB32) VERSIONINFO +#else +VS_VERSION_INFO VERSIONINFO +#endif + FILEVERSION 2,2,0,0 + PRODUCTVERSION 2,2,0,0 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x40004L + FILETYPE 0x2L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "FileDescription", "lib3mf Debug Version" + VALUE "FileVersion", "2.2.0.0" + VALUE "InternalName", "lib3mfD32.dll" + VALUE "OriginalFilename", "lib3mfD32.dll" + VALUE "ProductVersion", "2.2.0.0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END +#endif + +#if defined(APSTUDIO_INVOKED) || defined(NDEB32) +#if defined(APSTUDIO_INVOKED) +VS_VERSION_INFO$(NDEB32) VERSIONINFO +#else +VS_VERSION_INFO VERSIONINFO +#endif + FILEVERSION 2,2,0,0 + PRODUCTVERSION 2,2,0,0 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x40004L + FILETYPE 0x2L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "FileDescription", "lib3mf Release Version" + VALUE "FileVersion", "2.2.0.0" + VALUE "InternalName", "lib3mfR32.dll" + VALUE "OriginalFilename", "lib3mfR32.dll" + VALUE "ProductVersion", "2.2.0.0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END +#endif + +#if defined(APSTUDIO_INVOKED) || defined(_DEB64) +#if defined(APSTUDIO_INVOKED) +VS_VERSION_INFO$(_DEB64) VERSIONINFO +#else +VS_VERSION_INFO VERSIONINFO +#endif + FILEVERSION 2,2,0,0 + PRODUCTVERSION 2,2,0,0 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x40004L + FILETYPE 0x2L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "FileDescription", "lib3mf Debug Version" + VALUE "FileVersion", "2.2.0.0" + VALUE "InternalName", "lib3mfD64.dll" + VALUE "OriginalFilename", "lib3mfD64.dll" + VALUE "ProductVersion", "2.2.0.0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END +#endif + +#if defined(APSTUDIO_INVOKED) || defined(NDEB64) +#if defined(APSTUDIO_INVOKED) +VS_VERSION_INFO$(NDEB64) VERSIONINFO +#else +VS_VERSION_INFO VERSIONINFO +#endif + FILEVERSION 2,2,0,0 + PRODUCTVERSION 2,2,0,0 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x40004L + FILETYPE 0x2L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "FileDescription", "lib3mf Release Version" + VALUE "FileVersion", "2.2.0.0" + VALUE "InternalName", "lib3mfR64.dll" + VALUE "OriginalFilename", "lib3mfR64.dll" + VALUE "ProductVersion", "2.2.0.0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END +#endif + +#endif // Inglese (Stati Uniti) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/Source/API/lib3mf.cpp b/Source/API/lib3mf.cpp new file mode 100644 index 0000000..101a1c0 --- /dev/null +++ b/Source/API/lib3mf.cpp @@ -0,0 +1,260 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +This file has been generated by the Automatic Component Toolkit (ACT) version 1.5.0. + +Abstract: This is an autogenerated C++ implementation file in order to allow easy +development of the 3MF Library. It needs to be generated only once. + +Interface version: 2.2.0 + +*/ + +#include "lib3mf_abi.hpp" +#include "lib3mf_interfaces.hpp" +#include "lib3mf_interfaceexception.hpp" + +#include "lib3mf_model.hpp" + +#include "NMR_Spec_Version.h" +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/3MF_ProgressMonitor.h" +#include +#include + +using namespace Lib3MF::Impl; + +void CWrapper::GetLibraryVersion(Lib3MF_uint32 & nMajor, Lib3MF_uint32 & nMinor, Lib3MF_uint32 & nMicro) +{ + nMajor = LIB3MF_VERSION_MAJOR; + nMinor = LIB3MF_VERSION_MINOR; + nMicro = LIB3MF_VERSION_MICRO; +} + +bool CWrapper::GetPrereleaseInformation(std::string & sPrereleaseInfo) +{ + sPrereleaseInfo = LIB3MF_VERSION_PRERELEASEINFO; + return !sPrereleaseInfo.empty(); +} + +bool CWrapper::GetBuildInformation(std::string & sBuildInformation) +{ + sBuildInformation = LIB3MF_VERSION_BUILDINFO; + return !sBuildInformation.empty(); +} + + +void CWrapper::GetSpecificationVersion (const std::string & sSpecificationURL, bool & bIsSupported, Lib3MF_uint32 & nMajor, Lib3MF_uint32 & nMinor, Lib3MF_uint32 & nMicro) +{ + if (!sSpecificationURL.compare(std::string(XML_3MF_NAMESPACE_CORESPEC100))) { + nMajor = NMR_SPECVERSION_MAJOR; + nMinor = NMR_SPECVERSION_MINOR; + nMicro = NMR_SPECVERSION_MICRO; + bIsSupported = true; + } else if (!sSpecificationURL.compare( std::string(XML_3MF_NAMESPACE_MATERIALSPEC) )) { + nMajor = NMR_SPECVERSION_MATERIAL_MAJOR; + nMinor = NMR_SPECVERSION_MATERIAL_MINOR; + nMicro = NMR_SPECVERSION_MATERIAL_MICRO; + bIsSupported = true; + } else if (!sSpecificationURL.compare( std::string(XML_3MF_NAMESPACE_PRODUCTIONSPEC) )) { + nMajor = NMR_SPECVERSION_PRODUCTION_MAJOR; + nMinor = NMR_SPECVERSION_PRODUCTION_MINOR; + nMicro = NMR_SPECVERSION_PRODUCTION_MICRO; + bIsSupported = true; + } else if (!sSpecificationURL.compare( std::string(XML_3MF_NAMESPACE_BEAMLATTICESPEC) )) { + nMajor = NMR_SPECVERSION_BEAMLATTICE_MAJOR; + nMinor = NMR_SPECVERSION_BEAMLATTICE_MINOR; + nMicro = NMR_SPECVERSION_BEAMLATTICE_MICRO; + bIsSupported = true; + } + else if (!sSpecificationURL.compare(std::string(XML_3MF_NAMESPACE_SLICESPEC))) { + nMajor = NMR_SPECVERSION_SLICE_MAJOR; + nMinor = NMR_SPECVERSION_SLICE_MINOR; + nMicro = NMR_SPECVERSION_SLICE_MICRO; + bIsSupported = true; + } + else if (!sSpecificationURL.compare(std::string(XML_3MF_NAMESPACE_SECURECONTENTSPEC))) { + nMajor = NMR_SPECVERSION_SECURECONTENT_MAJOR; + nMinor = NMR_SPECVERSION_SECURECONTENT_MINOR; + nMicro = NMR_SPECVERSION_SECURECONTENT_MICRO; + bIsSupported = true; + } + else { + bIsSupported = false; + } +} + +IModel * CWrapper::CreateModel () +{ + return new CModel(); +} + +void CWrapper::Release (IBase* pInstance) +{ + IBase::ReleaseBaseClassInterface(pInstance); +} + +void CWrapper::Acquire(IBase* pInstance) +{ + IBase::AcquireBaseClassInterface(pInstance); +} + +NMR::ProgressIdentifier convertProgressIdentifier(const eLib3MFProgressIdentifier progressIdentifier) { + return NMR::ProgressIdentifier(progressIdentifier); + //switch (progressIdentifier) { + // case eLib3MFProgressIdentifier::eProgressIdentifierQUERYCANCELED: return NMR::PROGRESS_QUERYCANCELED; + // case eLib3MFProgressIdentifier::eProgressIdentifierDONE: return NMR::PROGRESS_DONE; + // case eLib3MFProgressIdentifier::eProgressIdentifierCLEANUP: return NMR::PROGRESS_CLEANUP; + // case eLib3MFProgressIdentifier::eProgressIdentifierREADSTREAM: return NMR::PROGRESS_READSTREAM; + // case eLib3MFProgressIdentifier::eProgressIdentifierEXTRACTOPCPACKAGE: return NMR::PROGRESS_EXTRACTOPCPACKAGE; + // case eLib3MFProgressIdentifier::eProgressIdentifierREADNONROOTMODELS: return NMR::PROGRESS_READNONROOTMODELS; + // case eLib3MFProgressIdentifier::eProgressIdentifierREADROOTMODEL: return NMR::PROGRESS_READROOTMODEL; + // case eLib3MFProgressIdentifier::eProgressIdentifierREADRESOURCES: return NMR::PROGRESS_READRESOURCES; + // case eLib3MFProgressIdentifier::eProgressIdentifierREADMESH: return NMR::PROGRESS_READMESH; + // case eLib3MFProgressIdentifier::eProgressIdentifierREADSLICES: return NMR::PROGRESS_READSLICES; + // case eLib3MFProgressIdentifier::eProgressIdentifierREADBUILD: return NMR::PROGRESS_READBUILD; + // case eLib3MFProgressIdentifier::eProgressIdentifierCREATEOPCPACKAGE: return NMR::PROGRESS_CREATEOPCPACKAGE; + // case eLib3MFProgressIdentifier::eProgressIdentifierWRITEMODELSTOSTREAM: return NMR::PROGRESS_WRITEMODELSTOSTREAM; + // case eLib3MFProgressIdentifier::eProgressIdentifierWRITEROOTMODEL: return NMR::PROGRESS_WRITEROOTMODEL; + // case eLib3MFProgressIdentifier::eProgressIdentifierWRITENONROOTMODELS: return NMR::PROGRESS_WRITENONROOTMODELS; + // case eLib3MFProgressIdentifier::eProgressIdentifierWRITEATTACHMENTS: return NMR::PROGRESS_WRITEATTACHMENTS; + // case eLib3MFProgressIdentifier::eProgressIdentifierWRITECONTENTTYPES: return NMR::PROGRESS_WRITECONTENTTYPES; + // case eLib3MFProgressIdentifier::eProgressIdentifierWRITENOBJECTS: return NMR::PROGRESS_WRITENOBJECTS; + // case eLib3MFProgressIdentifier::eProgressIdentifierWRITENODES: return NMR::PROGRESS_WRITENODES; + // case eLib3MFProgressIdentifier::eProgressIdentifierWRITETRIANGLES: return NMR::PROGRESS_WRITETRIANGLES; + // case eLib3MFProgressIdentifier::eProgressIdentifierWRITESLICES: return NMR::PROGRESS_WRITESLICES; + // default: throw ELib3MFInterfaceException(LIB3MF_ERROR_UNKOWNPROGRESSIDENTIFIER); + //} +} + +bool CWrapper::GetLastError (IBase* pInstance, std::string & sLastErrorString) +{ + if (pInstance != nullptr) + return pInstance->GetLastErrorMessage(sLastErrorString); + + return false; +} + +void CWrapper::RetrieveProgressMessage (const eLib3MFProgressIdentifier eProrgessIdentifier, std::string & sProgressMessage) +{ + NMR::CProgressMonitor::GetProgressMessage(convertProgressIdentifier(eProrgessIdentifier), sProgressMessage); +} + +sLib3MFColor CWrapper::RGBAToColor (const Lib3MF_uint8 nRed, const Lib3MF_uint8 nGreen, const Lib3MF_uint8 nBlue, const Lib3MF_uint8 nAlpha) +{ + sLib3MFColor s; + s.m_Red = nRed; + s.m_Green = nGreen; + s.m_Blue = nBlue; + s.m_Alpha = nAlpha; + return s; +} + +sLib3MFColor CWrapper::FloatRGBAToColor (const Lib3MF_single fRed, const Lib3MF_single fGreen, const Lib3MF_single fBlue, const Lib3MF_single fAlpha) +{ + sLib3MFColor s; + s.m_Red = (Lib3MF_uint8)std::round(std::max(std::min(fRed, 1.f), 0.f) * 255.0f); + s.m_Green = (Lib3MF_uint8)std::round(std::max(std::min(fGreen, 1.f), 0.f) * 255.0f); + s.m_Blue = (Lib3MF_uint8)std::round(std::max(std::min(fBlue, 1.f), 0.f) * 255.0f); + s.m_Alpha = (Lib3MF_uint8)std::round(std::max(std::min(fAlpha, 1.f), 0.f) * 255.0f); + return s; +} + +void CWrapper::ColorToRGBA (const sLib3MFColor TheColor, Lib3MF_uint8 & nRed, Lib3MF_uint8 & nGreen, Lib3MF_uint8 & nBlue, Lib3MF_uint8 & nAlpha) +{ + nRed = TheColor.m_Red; + nGreen = TheColor.m_Green; + nBlue = TheColor.m_Blue; + nAlpha = TheColor.m_Alpha; +} + +void CWrapper::ColorToFloatRGBA (const sLib3MFColor TheColor, Lib3MF_single & fRed, Lib3MF_single & fGreen, Lib3MF_single & fBlue, Lib3MF_single & fAlpha) +{ + fRed = TheColor.m_Red / 255.f; + fGreen = TheColor.m_Green / 255.f; + fBlue = TheColor.m_Blue / 255.f; + fAlpha = TheColor.m_Alpha / 255.f; +} + +sLib3MFTransform CWrapper::GetIdentityTransform () +{ + int i, j; + sLib3MFTransform Transform; + + for (i = 0; i < 4; i++) + for (j = 0; j < 3; j++) + Transform.m_Fields[i][j] = (i == j) ? 1.0f : 0.0f; + + return Transform; + +} + +sLib3MFTransform CWrapper::GetUniformScaleTransform (const Lib3MF_single fFactor) +{ + int i, j; + sLib3MFTransform Transform; + + for (i = 0; i < 4; i++) + for (j = 0; j < 3; j++) + Transform.m_Fields[i][j] = (i == j) ? fFactor : 0.0f; + + return Transform; +} + +sLib3MFTransform CWrapper::GetScaleTransform (const Lib3MF_single fFactorX, const Lib3MF_single fFactorY, const Lib3MF_single fFactorZ) +{ + int i, j; + sLib3MFTransform Transform; + + for (i = 0; i < 4; i++) + for (j = 0; j < 3; j++) + Transform.m_Fields[i][j] = (i == j) ? 1.0f : 0.0f; + + Transform.m_Fields[0][0] = fFactorX; + Transform.m_Fields[1][1] = fFactorY; + Transform.m_Fields[2][2] = fFactorZ; + + return Transform; + +} + +sLib3MFTransform CWrapper::GetTranslationTransform(const Lib3MF_single fVectorX, const Lib3MF_single fVectorY, const Lib3MF_single fVectorZ) +{ + int i, j; + sLib3MFTransform Transform; + + for (i = 0; i < 3; i++) + for (j = 0; j < 3; j++) + Transform.m_Fields[i][j] = (i == j) ? 1.0f : 0.0f; + + Transform.m_Fields[3][0] = fVectorX; + Transform.m_Fields[3][1] = fVectorY; + Transform.m_Fields[3][2] = fVectorZ; + + return Transform; +} + + diff --git a/Source/API/lib3mf_accessright.cpp b/Source/API/lib3mf_accessright.cpp new file mode 100644 index 0000000..db61aa1 --- /dev/null +++ b/Source/API/lib3mf_accessright.cpp @@ -0,0 +1,32 @@ +#include "lib3mf_accessright.hpp" +#include "lib3mf_interfaceexception.hpp" +#include "lib3mf_consumer.hpp" + +using namespace Lib3MF::Impl; + +Lib3MF::Impl::CAccessRight::CAccessRight(NMR::PKeyStoreAccessRight ar) { + m_pAccessRight = ar; +} + +IConsumer * Lib3MF::Impl::CAccessRight::GetConsumer() { + return new CConsumer(m_pAccessRight->getConsumer()); +} + +Lib3MF::eWrappingAlgorithm Lib3MF::Impl::CAccessRight::GetWrappingAlgorithm() { + NMR::eKeyStoreWrapAlgorithm ea = m_pAccessRight->getAlgorithm(); + return static_cast(ea); +} + +Lib3MF::eMgfAlgorithm Lib3MF::Impl::CAccessRight::GetMgfAlgorithm() { + NMR::eKeyStoreMaskGenerationFunction mgf = m_pAccessRight->getMgf(); + return static_cast(mgf); +} + +Lib3MF::eDigestMethod Lib3MF::Impl::CAccessRight::GetDigestMethod() { + NMR::eKeyStoreMessageDigest digest = m_pAccessRight->getDigest(); + return static_cast(digest); +} + +NMR::PKeyStoreAccessRight Lib3MF::Impl::CAccessRight::accessRight() const { + return m_pAccessRight; +} \ No newline at end of file diff --git a/Source/API/lib3mf_attachment.cpp b/Source/API/lib3mf_attachment.cpp new file mode 100644 index 0000000..9e8dfcf --- /dev/null +++ b/Source/API/lib3mf_attachment.cpp @@ -0,0 +1,163 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CAttachment + +*/ + +#include "lib3mf_attachment.hpp" +#include "lib3mf_interfaceexception.hpp" + +// Include custom headers here. +#include "Common/Platform/NMR_ImportStream_Unique_Memory.h" +#include "Common/Platform/NMR_ImportStream_Callback.h" +#include "Common/Platform/NMR_ImportStream.h" +#include "Common/Platform/NMR_Platform.h" +#include "Common/NMR_StringUtils.h" + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CAttachment +**************************************************************************************************************************/ + +CAttachment::CAttachment(NMR::PModelAttachment pModelAttachment) + : m_pModelAttachment(pModelAttachment) +{ + +} + +std::string CAttachment::GetPath () +{ + return m_pModelAttachment->getPathURI(); +} + +void CAttachment::SetPath (const std::string & sPath) +{ + NMR::CModel * pModel = m_pModelAttachment->getModel(); + NMR::PImportStream pStream = m_pModelAttachment->getStream(); + if (pModel->getPackageThumbnail() == m_pModelAttachment) { + // different handling for package-wide attachment + pModel->removePackageThumbnail(); + m_pModelAttachment = pModel->addPackageThumbnail(sPath, pStream); + } + else { + std::string sRelationshipType = m_pModelAttachment->getRelationShipType(); + pModel->removeAttachment(m_pModelAttachment->getPathURI()); + m_pModelAttachment = pModel->addAttachment(sPath, sRelationshipType, pStream); + } +} + +IPackagePart * CAttachment::PackagePart() +{ + throw ELib3MFInterfaceException(LIB3MF_ERROR_NOTIMPLEMENTED); +} + +std::string CAttachment::GetRelationShipType () +{ + return m_pModelAttachment->getRelationShipType(); +} + +void CAttachment::SetRelationShipType (const std::string & sPath) +{ + m_pModelAttachment->setRelationShipType(sPath); +} + +void CAttachment::WriteToFile (const std::string & sFileName) +{ + NMR::PImportStream pStream = m_pModelAttachment->getStream(); + + if (pStream.get() != nullptr) { + pStream->writeToFile(NMR::fnUTF8toUTF16(sFileName).c_str()); + } else { + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDATTACHMENTSTREAM); + } +} + +void CAttachment::ReadFromFile (const std::string & sFileName) +{ + NMR::PImportStream pImportStream = NMR::fnCreateImportStreamInstance(sFileName.c_str()); + + m_pModelAttachment->setStream(pImportStream); +} + +void CAttachment::ReadFromCallback(const Lib3MF::ReadCallback pTheReadCallback, const Lib3MF_uint64 nStreamSize, const Lib3MF::SeekCallback pTheSeekCallback, const Lib3MF_pvoid pUserData) +{ + NMR::ImportStream_ReadCallbackType lambdaReadCallback = + [pTheReadCallback](NMR::nfByte* pData, NMR::nfUint64 cbBytes, void* pUserData) + { + (*pTheReadCallback)(reinterpret_cast(pData), cbBytes, pUserData); + return 0; + }; + + NMR::ImportStream_SeekCallbackType lambdaSeekCallback = + [pTheSeekCallback](NMR::nfUint64 nPosition, void* pUserData) + { + (*pTheSeekCallback)(nPosition, pUserData); + return 0; + }; + + NMR::PImportStream pImportStream = std::make_shared( + lambdaReadCallback, lambdaSeekCallback, + pUserData, nStreamSize); + try { + m_pModelAttachment->setStream(pImportStream); + } + catch (NMR::CNMRException& e) { + if (e.getErrorCode() == NMR_USERABORTED) { + throw ELib3MFInterfaceException(LIB3MF_ERROR_CALCULATIONABORTED); + } + else throw e; + } +} + + +Lib3MF_uint64 CAttachment::GetStreamSize () +{ + NMR::PImportStream pStream = m_pModelAttachment->getStream(); + return pStream->retrieveSize(); +} + +void CAttachment::WriteToBuffer (Lib3MF_uint64 nBufferBufferSize, Lib3MF_uint64* pBufferNeededCount, Lib3MF_uint8 * pBufferBuffer) +{ + NMR::PImportStream pStream = m_pModelAttachment->getStream(); + + Lib3MF_uint64 cbStreamSize = pStream->retrieveSize(); + if (pBufferNeededCount) + *pBufferNeededCount = cbStreamSize; + + if (nBufferBufferSize >= cbStreamSize) { + pStream->seekPosition(0, true); + pStream->readIntoBuffer(pBufferBuffer, cbStreamSize, true); + } +} + +void CAttachment::ReadFromBuffer(const Lib3MF_uint64 nBufferBufferSize, const Lib3MF_uint8 * pBufferBuffer) +{ + NMR::PImportStream pImportStream = std::make_shared(pBufferBuffer, nBufferBufferSize); + m_pModelAttachment->setStream(pImportStream); +} + diff --git a/Source/API/lib3mf_base.cpp b/Source/API/lib3mf_base.cpp new file mode 100644 index 0000000..245813f --- /dev/null +++ b/Source/API/lib3mf_base.cpp @@ -0,0 +1,81 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CBase + +*/ + +#include "lib3mf_base.hpp" +#include "lib3mf_interfaceexception.hpp" + +// Include custom headers here. + + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CBase +**************************************************************************************************************************/ + +bool CBase::GetLastErrorMessage(std::string & sErrorMessage) +{ + if (m_pErrors && !m_pErrors->empty()) { + sErrorMessage = m_pErrors->back(); + return true; + } else { + sErrorMessage = ""; + return false; + } +} + +void CBase::ClearErrorMessages() +{ + m_pErrors.reset(); +} + +void CBase::RegisterErrorMessage(const std::string & sErrorMessage) +{ + if (!m_pErrors) { + m_pErrors.reset(new std::list()); + } + m_pErrors->clear(); + m_pErrors->push_back(sErrorMessage); +} + +void CBase::IncRefCount() +{ + ++m_nReferenceCount; +} + +bool CBase::DecRefCount() +{ + m_nReferenceCount--; + if (!m_nReferenceCount) { + delete this; + return true; + } + return false; +} diff --git a/Source/API/lib3mf_basematerialgroup.cpp b/Source/API/lib3mf_basematerialgroup.cpp new file mode 100644 index 0000000..ce985a5 --- /dev/null +++ b/Source/API/lib3mf_basematerialgroup.cpp @@ -0,0 +1,125 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CBaseMaterialGroup + +*/ + +#include "lib3mf_basematerialgroup.hpp" +#include "lib3mf_interfaceexception.hpp" + +// Include custom headers here. + + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CBaseMaterialGroup +**************************************************************************************************************************/ + +CBaseMaterialGroup::CBaseMaterialGroup(NMR::PModelBaseMaterialResource pResource) + : CResource(std::static_pointer_cast(pResource)) +{ +} + +NMR::CModelBaseMaterialResource& CBaseMaterialGroup::baseMaterialGroup() +{ + NMR::CModelBaseMaterialResource* pBaseMaterialGroup = dynamic_cast(resource().get()); + if (pBaseMaterialGroup == nullptr) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDBASEMATERIALGROUP); + return *pBaseMaterialGroup; +} + +Lib3MF_uint32 CBaseMaterialGroup::GetCount () +{ + return baseMaterialGroup().getCount(); +} + +Lib3MF_uint32 CBaseMaterialGroup::AddMaterial(const std::string & sName, const sLib3MFColor DisplayColor) +{ + NMR::nfColor cColor = DisplayColor.m_Red | (DisplayColor.m_Green << 8) | (DisplayColor.m_Blue << 16) | (DisplayColor.m_Alpha << 24); + + return baseMaterialGroup().addBaseMaterial(sName, cColor); +} + +void CBaseMaterialGroup::RemoveMaterial (const Lib3MF_uint32 nPropertyID) +{ + baseMaterialGroup().removeMaterial(nPropertyID); +} + +std::string CBaseMaterialGroup::GetName (const Lib3MF_uint32 nPropertyID) +{ + return baseMaterialGroup().getBaseMaterial(nPropertyID)->getName(); +} + +void CBaseMaterialGroup::SetName (const Lib3MF_uint32 nPropertyID, const std::string & sName) +{ + baseMaterialGroup().getBaseMaterial(nPropertyID)->setName(sName); +} + +void CBaseMaterialGroup::SetDisplayColor(const Lib3MF_uint32 nPropertyID, const sLib3MFColor TheColor) +{ + NMR::nfColor cColor = TheColor.m_Red | (TheColor.m_Green << 8) | (TheColor.m_Blue << 16) | (TheColor.m_Alpha << 24); + baseMaterialGroup().getBaseMaterial(nPropertyID)->setColor(cColor); +} + +sLib3MFColor CBaseMaterialGroup::GetDisplayColor(const Lib3MF_uint32 nPropertyID) +{ + NMR::nfColor cColor = baseMaterialGroup().getBaseMaterial(nPropertyID)->getDisplayColor(); + sLib3MFColor c; + c.m_Red = (cColor) & 0xff; + c.m_Green = (cColor >> 8) & 0xff; + c.m_Blue = (cColor >> 16) & 0xff; + c.m_Alpha = (cColor >> 24) & 0xff; + return c; +} + +void CBaseMaterialGroup::GetAllPropertyIDs(Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer) +{ + Lib3MF_uint32 nMaterialCount = baseMaterialGroup().getCount(); + + if (pPropertyIDsNeededCount) + *pPropertyIDsNeededCount = nMaterialCount; + + if (nPropertyIDsBufferSize >= nMaterialCount && pPropertyIDsBuffer) { + if (!baseMaterialGroup().hasResourceIndexMap()) { + baseMaterialGroup().buildResourceIndexMap(); + } + for (Lib3MF_uint32 i = 0; i < nMaterialCount; i++) { + DWORD nPropertyID; + if (baseMaterialGroup().mapResourceIndexToPropertyID(i, nPropertyID)) { + *pPropertyIDsBuffer = nPropertyID; + } + else { + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDRESOURCEINDEX); + } + pPropertyIDsBuffer++; + } + } + +} + + diff --git a/Source/API/lib3mf_basematerialgroupiterator.cpp b/Source/API/lib3mf_basematerialgroupiterator.cpp new file mode 100644 index 0000000..f6f8cba --- /dev/null +++ b/Source/API/lib3mf_basematerialgroupiterator.cpp @@ -0,0 +1,48 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CBaseMaterialGroupIterator + +*/ + +#include "lib3mf_basematerialgroupiterator.hpp" +#include "lib3mf_interfaceexception.hpp" +#include "lib3mf_basematerialgroup.hpp" +// Include custom headers here. + + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CBaseMaterialGroupIterator +**************************************************************************************************************************/ + +IBaseMaterialGroup * CBaseMaterialGroupIterator::GetCurrentBaseMaterialGroup() +{ + // Create specific API class + return new CBaseMaterialGroup(std::dynamic_pointer_cast(GetCurrentResource())); +} + diff --git a/Source/API/lib3mf_beamlattice.cpp b/Source/API/lib3mf_beamlattice.cpp new file mode 100644 index 0000000..53942b7 --- /dev/null +++ b/Source/API/lib3mf_beamlattice.cpp @@ -0,0 +1,486 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CBeamLattice + +*/ + +#include "lib3mf_beamlattice.hpp" +#include "lib3mf_interfaceexception.hpp" + +#include "lib3mf_beamset.hpp" +// Include custom headers here. + + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CBeamLattice +**************************************************************************************************************************/ + +CBeamLattice::CBeamLattice(NMR::PModelMeshObject pMeshObject, NMR::PModelMeshBeamLatticeAttributes pAttributes): + m_mesh(*pMeshObject->getMesh()), m_pAttributes(pAttributes), m_pMeshObject(pMeshObject) +{ + +} + +Lib3MF_double CBeamLattice::GetMinLength () +{ + return m_mesh.getBeamLatticeMinLength(); +} + +void CBeamLattice::SetMinLength (const Lib3MF_double dMinLength) +{ + return m_mesh.setBeamLatticeMinLength(dMinLength); +} + +void CBeamLattice::GetClipping(eLib3MFBeamLatticeClipMode & eClipMode, Lib3MF_uint32 & nUniqueResourceID) +{ + if (!m_pAttributes->m_bHasClippingMeshID) { + eClipMode = eBeamLatticeClipMode::NoClipMode; + nUniqueResourceID = 0; + } + else { + eClipMode = eBeamLatticeClipMode(m_pAttributes->m_eClipMode); + nUniqueResourceID = m_pAttributes->m_pClippingMeshUniqueID->getUniqueID(); + } +} + +void CBeamLattice::SetClipping(const eLib3MFBeamLatticeClipMode eClipMode, const Lib3MF_uint32 nUniqueResourceID) +{ + if ( ((int)eClipMode == (NMR::eModelBeamLatticeClipMode::MODELBEAMLATTICECLIPMODE_NONE)) || (nUniqueResourceID == 0) ){ + m_pAttributes->m_eClipMode = NMR::eModelBeamLatticeClipMode(eClipMode); + m_pAttributes->m_bHasClippingMeshID = false; + m_pAttributes->m_pClippingMeshUniqueID = nullptr; + } + else { + NMR::CModel* pModel = m_pMeshObject->getModel(); + + NMR::CModelMeshObject * pClippingObject = dynamic_cast(pModel->findObject(nUniqueResourceID)); + if (pClippingObject == nullptr) { + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + } + // check, if this object will be written before + NMR::nfInt32 nComp = pModel->compareObjectsByResourceID(pClippingObject, m_pMeshObject.get()); + if (nComp < 0) { // pClippingObject has been defined after m_pMeshObject + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + } + + m_pAttributes->m_eClipMode = NMR::eModelBeamLatticeClipMode(eClipMode);; + m_pAttributes->m_bHasClippingMeshID = true; + m_pAttributes->m_pClippingMeshUniqueID = pClippingObject->getPackageResourceID(); + } +} + +bool CBeamLattice::GetRepresentation (Lib3MF_uint32 & nUniqueResourceID) +{ + if (m_pAttributes->m_bHasRepresentationMeshID) { + nUniqueResourceID = m_pAttributes->m_pRepresentationUniqueID->getUniqueID(); + return true; + } + else { + nUniqueResourceID = 0; + return false; + } +} + +void CBeamLattice::SetRepresentation (const Lib3MF_uint32 nUniqueResourceID) +{ + if (nUniqueResourceID == 0) { + m_pAttributes->m_bHasRepresentationMeshID = false; + m_pAttributes->m_pRepresentationUniqueID = nullptr; + } + else { + NMR::CModel* pModel = m_pMeshObject->getModel(); + + NMR::CModelMeshObject * pRepresentationObject = dynamic_cast(pModel->findObject(nUniqueResourceID)); + if (pRepresentationObject == nullptr) { + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + } + // check, if this object will be written before + NMR::nfInt32 nComp = pModel->compareObjectsByResourceID(pRepresentationObject, m_pMeshObject.get()); + if (nComp < 0) { // pClippingObject has been defined after m_pMeshObject + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + } + + m_pAttributes->m_bHasRepresentationMeshID = true; + m_pAttributes->m_pRepresentationUniqueID = pRepresentationObject->getPackageResourceID(); + } +} + +void CBeamLattice::GetBallOptions (eLib3MFBeamLatticeBallMode & eBallMode, Lib3MF_double & dBallRadius) +{ + eBallMode = (eLib3MFBeamLatticeBallMode)m_mesh.getBeamLatticeBallMode(); + dBallRadius = m_mesh.getDefaultBallRadius(); +} + +void CBeamLattice::SetBallOptions (const eLib3MFBeamLatticeBallMode eBallMode, const Lib3MF_double dBallRadius) +{ + if (eBallMode == eLib3MFBeamLatticeBallMode::None || dBallRadius > 0.0) { + m_mesh.setBeamLatticeBallMode((NMR::eModelBeamLatticeBallMode)eBallMode); + m_mesh.setDefaultBallRadius(dBallRadius); + } + else { + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + } +} + +Lib3MF_uint32 CBeamLattice::GetBeamCount () +{ + return m_mesh.getBeamCount(); +} + +sLib3MFBeam CBeamLattice::GetBeam (const Lib3MF_uint32 nIndex) +{ + sLib3MFBeam beam; + NMR::MESHBEAM* meshBeam = m_mesh.getBeam(nIndex); + beam.m_CapModes[0] = (eLib3MFBeamLatticeCapMode)(meshBeam->m_capMode[0]); + beam.m_CapModes[1] = (eLib3MFBeamLatticeCapMode)meshBeam->m_capMode[1]; + + beam.m_Indices[0] = meshBeam->m_nodeindices[0]; + beam.m_Indices[1] = meshBeam->m_nodeindices[1]; + + beam.m_Radii[0] = meshBeam->m_radius[0]; + beam.m_Radii[1] = meshBeam->m_radius[1]; + return beam; +} + +bool isBeamValid(const Lib3MF_uint32 nNodeCount, const sLib3MFBeam& BeamInfo) +{ + for (int j = 0; j < 2; j++) { + if (BeamInfo.m_Indices[j] >= nNodeCount) + return false; + if (BeamInfo.m_Radii[j] <= 0) + return false; + } + if (BeamInfo.m_Indices[0] == BeamInfo.m_Indices[1]) + return false; + return true; +} + +Lib3MF_uint32 CBeamLattice::AddBeam (const sLib3MFBeam BeamInfo) +{ + if (!m_pMeshObject->isValidForBeamLattices()) + throw ELib3MFInterfaceException(LIB3MF_ERROR_BEAMLATTICE_INVALID_OBJECTTYPE); + + // Check for input validity + if (!isBeamValid(m_mesh.getNodeCount(), BeamInfo)) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + + // retrieve nodes and add beam + NMR::MESHNODE * pNodes[2]; + for (int j = 0; j < 2; j++) + pNodes[j] = m_mesh.getNode(BeamInfo.m_Indices[j]); + + NMR::MESHBEAM * pMeshBeam = m_mesh.addBeam(pNodes[0], pNodes[1], BeamInfo.m_Radii[0], BeamInfo.m_Radii[1], (int)BeamInfo.m_CapModes[0], (int)BeamInfo.m_CapModes[1]); + return pMeshBeam->m_index; +} + +void CBeamLattice::SetBeam (const Lib3MF_uint32 nIndex, const sLib3MFBeam BeamInfo) +{ + if (!isBeamValid(m_mesh.getNodeCount(), BeamInfo)) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + + NMR::MESHBEAM* meshBeam = m_mesh.getBeam(nIndex); + meshBeam->m_capMode[0] = (int)BeamInfo.m_CapModes[0]; + meshBeam->m_capMode[1] = (int)BeamInfo.m_CapModes[1]; + + meshBeam->m_nodeindices[0] = BeamInfo.m_Indices[0]; + meshBeam->m_nodeindices[1] = BeamInfo.m_Indices[1]; + + meshBeam->m_radius[0] = BeamInfo.m_Radii[0]; + meshBeam->m_radius[1] = BeamInfo.m_Radii[1]; + + // Occupied nodes may have changed, need to validate + m_mesh.scanOccupiedNodes(); + m_mesh.validateBeamLatticeBalls(); +} + +void CBeamLattice::SetBeams(const Lib3MF_uint64 nBeamInfoBufferSize, const sLib3MFBeam * pBeamInfoBuffer) +{ + if ((nBeamInfoBufferSize>0) && (!m_pMeshObject->isValidForBeamLattices())) + throw ELib3MFInterfaceException(LIB3MF_ERROR_BEAMLATTICE_INVALID_OBJECTTYPE); + + m_mesh.clearBeamLatticeBeams(); + + const sLib3MFBeam* pBeamInfoCurrent = pBeamInfoBuffer; + for (Lib3MF_uint32 nIndex = 0; nIndex < nBeamInfoBufferSize; nIndex++) + { + if (!isBeamValid(m_mesh.getNodeCount(), *pBeamInfoCurrent)) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + + NMR::MESHNODE * pNodes[2]; + for (int j = 0; j < 2; j++) + pNodes[j] = m_mesh.getNode(pBeamInfoCurrent->m_Indices[j]); + + m_mesh.addBeam(pNodes[0], pNodes[1], pBeamInfoCurrent->m_Radii[0], pBeamInfoCurrent->m_Radii[1], (int)pBeamInfoCurrent->m_CapModes[0], (int)pBeamInfoCurrent->m_CapModes[1]); + pBeamInfoCurrent++; + } + + // Occupied nodes may have changed, need to validate + m_mesh.validateBeamLatticeBalls(); +} + +void CBeamLattice::GetBeams(Lib3MF_uint64 nBeamInfoBufferSize, Lib3MF_uint64* pBeamInfoNeededCount, sLib3MFBeam * pBeamInfoBuffer) +{ + Lib3MF_uint32 beamCount = m_mesh.getBeamCount(); + if (pBeamInfoNeededCount) + *pBeamInfoNeededCount = beamCount; + + if (nBeamInfoBufferSize >= beamCount && pBeamInfoBuffer) + { + sLib3MFBeam* beam = pBeamInfoBuffer; + for (Lib3MF_uint32 i = 0; i < beamCount; i++) + { + const NMR::MESHBEAM* meshBeam = m_mesh.getBeam(i); + beam->m_CapModes[0] = (eLib3MFBeamLatticeCapMode)meshBeam->m_capMode[0]; + beam->m_CapModes[1] = (eLib3MFBeamLatticeCapMode)meshBeam->m_capMode[1]; + + beam->m_Indices[0] = meshBeam->m_nodeindices[0]; + beam->m_Indices[1] = meshBeam->m_nodeindices[1]; + + beam->m_Radii[0] = meshBeam->m_radius[0]; + beam->m_Radii[1] = meshBeam->m_radius[1]; + beam++; + } + } +} + +Lib3MF_uint32 CBeamLattice::GetBallCount () +{ + eBeamLatticeBallMode ballMode = (eBeamLatticeBallMode)m_mesh.getBeamLatticeBallMode(); + + if (ballMode == eBeamLatticeBallMode::Mixed) { + return m_mesh.getBallCount(); + } + else if (ballMode == eBeamLatticeBallMode::All) { + return m_mesh.getOccupiedNodeCount(); + } + else { + return 0; + } +} + +sLib3MFBall CBeamLattice::GetBall (const Lib3MF_uint32 nIndex) +{ + sLib3MFBall ball; + + eBeamLatticeBallMode ballMode; + Lib3MF_double defaultBallRadius; + GetBallOptions(ballMode, defaultBallRadius); + + Lib3MF_uint32 ballCount = GetBallCount(); + if (nIndex >= ballCount) { + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDRESOURCEINDEX); + } + + if (ballMode == eBeamLatticeBallMode::Mixed) { + NMR::MESHBALL * meshBall = m_mesh.getBall(nIndex); + + ball.m_Index = meshBall->m_nodeindex; + + ball.m_Radius = meshBall->m_radius; + + return ball; + } + else if (ballMode == eBeamLatticeBallMode::All) { + Lib3MF_uint32 ballNodeIndex = m_mesh.getOccupiedNode(nIndex)->m_index; + + Lib3MF_uint32 meshBallCount = m_mesh.getBallCount(); + for (Lib3MF_uint32 iBall = 0; iBall < meshBallCount; iBall++) { + NMR::MESHBALL * meshBall = m_mesh.getBall(iBall); + + if (meshBall->m_nodeindex == ballNodeIndex) { + ball.m_Index = meshBall->m_nodeindex; + + ball.m_Radius = meshBall->m_radius; + + return ball; + } + } + + ball.m_Index = ballNodeIndex; + + ball.m_Radius = defaultBallRadius; + + return ball; + } + else { + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + } +} + +bool isBallValid(const Lib3MF_uint32 nNodeCount, const sLib3MFBall& BallInfo) +{ + if (BallInfo.m_Index >= nNodeCount) + return false; + if (BallInfo.m_Radius <= 0) + return false; + return true; +} + +Lib3MF_uint32 CBeamLattice::AddBall (const sLib3MFBall BallInfo) +{ + if (!m_pMeshObject->isValidForBeamLattices()) + throw ELib3MFInterfaceException(LIB3MF_ERROR_BEAMLATTICE_INVALID_OBJECTTYPE); + + // Check for input validity + if (!isBallValid(m_mesh.getNodeCount(), BallInfo)) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + + // retrieve node and add ball + NMR::MESHNODE * pNode = m_mesh.getNode(BallInfo.m_Index); + + NMR::MESHBALL * pMeshBall = m_mesh.addBall(pNode, BallInfo.m_Radius); + return pMeshBall->m_index; +} + +void CBeamLattice::SetBall (const Lib3MF_uint32 nIndex, const sLib3MFBall BallInfo) +{ + if (!isBallValid(m_mesh.getNodeCount(), BallInfo)) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + + if (!m_mesh.isNodeOccupied(BallInfo.m_Index)) { + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + } + + eBeamLatticeBallMode ballMode = (eBeamLatticeBallMode(m_mesh.getBeamLatticeBallMode())); + + if (ballMode == eBeamLatticeBallMode::Mixed) { + NMR::MESHBALL * meshBall = m_mesh.getBall(nIndex); + + meshBall->m_nodeindex = BallInfo.m_Index; + + meshBall->m_radius = BallInfo.m_Radius; + } + else if (ballMode == eBeamLatticeBallMode::All) { + Lib3MF_uint32 ballNodeIndex = m_mesh.getOccupiedNode(nIndex)->m_index; + Lib3MF_uint32 meshBallCount = m_mesh.getBallCount(); + for (Lib3MF_uint32 iBall = 0; iBall < meshBallCount; iBall++) { + NMR::MESHBALL * meshBall = m_mesh.getBall(iBall); + + if (meshBall->m_nodeindex == ballNodeIndex) { + meshBall->m_nodeindex = BallInfo.m_Index; + meshBall->m_radius = BallInfo.m_Radius; + return; + } + } + + // Not in mesh, add the ball + NMR::MESHNODE * pNode = m_mesh.getNode(BallInfo.m_Index); + + m_mesh.addBall(pNode, BallInfo.m_Radius); + } + else { + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + } +} + +void CBeamLattice::SetBalls (const Lib3MF_uint64 nBallInfoBufferSize, const sLib3MFBall * pBallInfoBuffer) +{ + if ((nBallInfoBufferSize > 0) && (!m_pMeshObject->isValidForBeamLattices())) + throw ELib3MFInterfaceException(LIB3MF_ERROR_BEAMLATTICE_INVALID_OBJECTTYPE); + + m_mesh.clearBeamLatticeBalls(); + + const sLib3MFBall * pBallInfoCurrent = pBallInfoBuffer; + for (Lib3MF_uint32 nIndex = 0; nIndex < nBallInfoBufferSize; nIndex++) + { + if (!isBallValid(m_mesh.getNodeCount(), *pBallInfoCurrent)) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + + NMR::MESHNODE * pNode = m_mesh.getNode(pBallInfoCurrent->m_Index); + + m_mesh.addBall(pNode, pBallInfoCurrent->m_Radius); + pBallInfoCurrent++; + } +} + +void CBeamLattice::GetBalls(Lib3MF_uint64 nBallInfoBufferSize, Lib3MF_uint64 * pBallInfoNeededCount, sLib3MFBall * pBallInfoBuffer) +{ + Lib3MF_uint32 ballCount = GetBallCount(); + if (pBallInfoNeededCount) + *pBallInfoNeededCount = ballCount; + + if (nBallInfoBufferSize >= ballCount && pBallInfoBuffer) { + eBeamLatticeBallMode ballMode; + Lib3MF_double defaultBallRadius; + GetBallOptions(ballMode, defaultBallRadius); + + if (ballMode == eBeamLatticeBallMode::Mixed) { + sLib3MFBall * ball = pBallInfoBuffer; + for (Lib3MF_uint32 iBall = 0; iBall < ballCount; iBall++) { + const NMR::MESHBALL * meshBall = m_mesh.getBall(iBall); + + ball->m_Index = meshBall->m_nodeindex; + + ball->m_Radius = meshBall->m_radius; + ball++; + } + } + else if (ballMode == eBeamLatticeBallMode::All) { + Lib3MF_uint32 meshBallCount = m_mesh.getBallCount(); + + // Sort balls that are in the mesh into a map by node index + std::map meshBallMap; + for (Lib3MF_uint32 iBall = 0; iBall < meshBallCount; iBall++) { + const NMR::MESHBALL * meshBall = m_mesh.getBall(iBall); + + meshBallMap[meshBall->m_nodeindex] = meshBall->m_radius; + } + + // Fill balls from default or mesh balls + sLib3MFBall * ball = pBallInfoBuffer; + for (Lib3MF_uint32 i = 0; i < ballCount; i++) { + Lib3MF_uint32 currNodeIndex = m_mesh.getOccupiedNode(i)->m_index; + + ball->m_Index = currNodeIndex; + ball->m_Radius = meshBallMap[currNodeIndex] > 0.0 ? meshBallMap[currNodeIndex] : defaultBallRadius; + + ball++; + } + } + else { + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + } + } +} + +Lib3MF_uint32 CBeamLattice::GetBeamSetCount () +{ + return m_mesh.getBeamSetCount(); +} + +IBeamSet * CBeamLattice::AddBeamSet () +{ + return new CBeamSet(m_mesh.addBeamSet(), m_pMeshObject); +} + +IBeamSet * CBeamLattice::GetBeamSet (const Lib3MF_uint32 nIndex) +{ + return new CBeamSet(m_mesh.getBeamSet(nIndex), m_pMeshObject); +} + diff --git a/Source/API/lib3mf_beamset.cpp b/Source/API/lib3mf_beamset.cpp new file mode 100644 index 0000000..42e447d --- /dev/null +++ b/Source/API/lib3mf_beamset.cpp @@ -0,0 +1,146 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CBeamSet + +*/ + +#include "lib3mf_beamset.hpp" +#include "lib3mf_interfaceexception.hpp" + +// Include custom headers here. + + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CBeamSet +**************************************************************************************************************************/ + +CBeamSet::CBeamSet(NMR::PBEAMSET pBeamSet, NMR::PModelMeshObject pMeshObject): + m_pBeamSet(pBeamSet), m_mesh(*pMeshObject->getMesh()) +{ + +} + +void CBeamSet::SetName(const std::string & sName) +{ + m_pBeamSet->m_sName = sName; +} + +std::string CBeamSet::GetName() +{ + return m_pBeamSet->m_sName; +} + +void CBeamSet::SetIdentifier(const std::string & sIdentifier) +{ + // Ensure identifier is unique + if (sIdentifier.compare("") != 0) { + Lib3MF_uint32 nBeamSets = m_mesh.getBeamSetCount(); + for (Lib3MF_uint32 iBeamSet = 0; iBeamSet < nBeamSets; iBeamSet++) + if (sIdentifier.compare(m_mesh.getBeamSet(iBeamSet)->m_sIdentifier) == 0) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + } + + m_pBeamSet->m_sIdentifier = sIdentifier; +} + +std::string CBeamSet::GetIdentifier() +{ + return m_pBeamSet->m_sIdentifier; +} + +Lib3MF_uint32 CBeamSet::GetReferenceCount() +{ + return (Lib3MF_uint32)m_pBeamSet->m_Refs.size(); +} + +void CBeamSet::SetReferences(const Lib3MF_uint64 nReferencesBufferSize, const Lib3MF_uint32 * pReferencesBuffer) +{ + if (nReferencesBufferSize > LIB3MF_MAXBEAMCOUNT) + throw ELib3MFInterfaceException(LIB3MF_ERROR_ELEMENTCOUNTEXCEEDSLIMIT); + + m_pBeamSet->m_Refs.resize((size_t) nReferencesBufferSize); + const Lib3MF_uint32 beamCount = m_mesh.getBeamCount(); + for (size_t i = 0; i < (size_t)nReferencesBufferSize; i++) { + if (beamCount <= pReferencesBuffer[i]) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + m_pBeamSet->m_Refs[i] = Lib3MF_uint32(pReferencesBuffer[i]); + } + +} + +void CBeamSet::GetReferences(Lib3MF_uint64 nReferencesBufferSize, Lib3MF_uint64* pReferencesNeededCount, Lib3MF_uint32 * pReferencesBuffer) +{ + Lib3MF_uint32 referenceCount = (Lib3MF_uint32)m_pBeamSet->m_Refs.size(); + if (pReferencesNeededCount) + *pReferencesNeededCount = referenceCount; + + if (nReferencesBufferSize >= referenceCount && pReferencesBuffer) + { + Lib3MF_uint32* pRef = pReferencesBuffer; + for (Lib3MF_uint32 i = 0; i < referenceCount; i++) + { + *pRef = m_pBeamSet->m_Refs[i]; + pRef++; + } + } +} + +Lib3MF_uint32 CBeamSet::GetBallReferenceCount() +{ + return (Lib3MF_uint32)m_pBeamSet->m_BallRefs.size(); +} + +void CBeamSet::SetBallReferences(const Lib3MF_uint64 nBallReferencesBufferSize, const Lib3MF_uint32* pBallReferencesBuffer) +{ + if (nBallReferencesBufferSize > LIB3MF_MAXBEAMCOUNT) + throw ELib3MFInterfaceException(LIB3MF_ERROR_ELEMENTCOUNTEXCEEDSLIMIT); + + m_pBeamSet->m_BallRefs.resize((size_t)nBallReferencesBufferSize); + const Lib3MF_uint32 ballCount = m_mesh.getBallCount(); + for (size_t i = 0; i < (size_t)nBallReferencesBufferSize; i++) { + if (ballCount <= pBallReferencesBuffer[i]) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + m_pBeamSet->m_BallRefs[i] = Lib3MF_uint32(pBallReferencesBuffer[i]); + } +} + +void CBeamSet::GetBallReferences(Lib3MF_uint64 nBallReferencesBufferSize, Lib3MF_uint64* pBallReferencesNeededCount, Lib3MF_uint32* pBallReferencesBuffer) +{ + Lib3MF_uint32 ballReferenceCount = GetBallReferenceCount(); + if (pBallReferencesNeededCount) + *pBallReferencesNeededCount = ballReferenceCount; + + if (nBallReferencesBufferSize >= ballReferenceCount && pBallReferencesBuffer) { + Lib3MF_uint32* pBallRef = pBallReferencesBuffer; + for (Lib3MF_uint32 i = 0; i < ballReferenceCount; i++) { + *pBallRef = m_pBeamSet->m_BallRefs[i]; + pBallRef++; + } + } +} diff --git a/Source/API/lib3mf_builditem.cpp b/Source/API/lib3mf_builditem.cpp new file mode 100644 index 0000000..a7d4149 --- /dev/null +++ b/Source/API/lib3mf_builditem.cpp @@ -0,0 +1,139 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CBuildItem + +*/ + +#include "lib3mf_builditem.hpp" +#include "lib3mf_interfaceexception.hpp" + +#include "lib3mf_utils.hpp" +#include "lib3mf_object.hpp" +#include "lib3mf_metadatagroup.hpp" +// Include custom headers here. + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CBuildItem +**************************************************************************************************************************/ + +NMR::CModelBuildItem& CBuildItem::buildItem() +{ + return *m_pBuildItem.get(); +} + +CBuildItem::CBuildItem(NMR::PModelBuildItem pBuildItem) +{ + m_pBuildItem = pBuildItem; +} + +Lib3MF_uint32 CBuildItem::GetHandle() +{ + return buildItem().getHandle(); +} + +IObject * CBuildItem::GetObjectResource () +{ + NMR::PModelResource pResource = buildItem().getModel()->findResource(buildItem().getObject()->getPackageResourceID()); + if (!pResource.get()) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDMODELRESOURCE); + + std::unique_ptr pResourceInterface(CObject::fnCreateObjectFromModelResource(pResource, true)); + if (pResourceInterface == nullptr) + throw ELib3MFInterfaceException(LIB3MF_ERROR_RESOURCENOTFOUND); + + return pResourceInterface.release(); +} + +std::string CBuildItem::GetUUID (bool & bHasUUID) +{ + bHasUUID = buildItem().uuid() != nullptr; + if (bHasUUID) + return buildItem().uuid()->toString(); + return ""; +} + +void CBuildItem::SetUUID (const std::string & sUUID) +{ + NMR::PUUID pUUID = std::make_shared(sUUID); + buildItem().setUUID(pUUID); +} + +Lib3MF_uint32 CBuildItem::GetObjectResourceID() +{ + return buildItem().getObject()->getPackageResourceID()->getUniqueID(); +} + +bool CBuildItem::HasObjectTransform () +{ + return buildItem().hasTransform(); +} + +sLib3MFTransform CBuildItem::GetObjectTransform () +{ + const NMR::NMATRIX3 matrix = buildItem().getTransform(); + return MatrixToTransform(matrix); +} + +void CBuildItem::SetObjectTransform (const sLib3MFTransform Transform) +{ + buildItem().setTransform(TransformToMatrix(Transform)); +} + +std::string CBuildItem::GetPartNumber () +{ + return buildItem().getPartNumber(); +} + +void CBuildItem::SetPartNumber (const std::string & sSetPartnumber) +{ + buildItem().setPartNumber(sSetPartnumber); +} + +IMetaDataGroup * CBuildItem::GetMetaDataGroup () +{ + return new CMetaDataGroup(buildItem().metaDataGroup()); +} + +Lib3MF::sBox CBuildItem::GetOutbox() +{ + NMR::NOUTBOX3 sOutbox; + NMR::fnOutboxInitialize(sOutbox); + + buildItem().getObject()->extendOutbox(sOutbox, buildItem().getTransform()); + + sBox s; + s.m_MinCoordinate[0] = sOutbox.m_min.m_fields[0]; + s.m_MinCoordinate[1] = sOutbox.m_min.m_fields[1]; + s.m_MinCoordinate[2] = sOutbox.m_min.m_fields[2]; + + s.m_MaxCoordinate[0] = sOutbox.m_max.m_fields[0]; + s.m_MaxCoordinate[1] = sOutbox.m_max.m_fields[1]; + s.m_MaxCoordinate[2] = sOutbox.m_max.m_fields[2]; + return s; +} diff --git a/Source/API/lib3mf_builditemiterator.cpp b/Source/API/lib3mf_builditemiterator.cpp new file mode 100644 index 0000000..1fafa75 --- /dev/null +++ b/Source/API/lib3mf_builditemiterator.cpp @@ -0,0 +1,113 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CBuildItemIterator + +*/ + +#include "lib3mf_builditemiterator.hpp" +#include "lib3mf_interfaceexception.hpp" + +#include "lib3mf_builditem.hpp" +// Include custom headers here. + + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CBuildItemIterator +**************************************************************************************************************************/ + +CBuildItemIterator::CBuildItemIterator() +{ + m_nCurrentIndex = -1; +} + + +void CBuildItemIterator::addBuildItem(NMR::PModelBuildItem pBuildItem) +{ + m_pBuildItems.push_back(pBuildItem); +} + +bool CBuildItemIterator::MoveNext () +{ + // Get Resource Count + Lib3MF_int32 nBuildItemCount = (Lib3MF_int32)m_pBuildItems.size(); + m_nCurrentIndex++; + + // Check new Index + if (m_nCurrentIndex >= nBuildItemCount) { + m_nCurrentIndex = nBuildItemCount; + return false; + } + else { + return true; + } +} + +bool CBuildItemIterator::MovePrevious () +{ + // Get Resource Count + m_nCurrentIndex--; + + // Check new Index + if (m_nCurrentIndex <= -1) { + m_nCurrentIndex = -1; + return false; + } + else { + return true; + } +} + +IBuildItem * CBuildItemIterator::GetCurrent () +{ + // Get Resource Count + Lib3MF_int32 nBuildItemCount = (Lib3MF_int32)m_pBuildItems.size(); + if ((m_nCurrentIndex < 0) || (m_nCurrentIndex >= nBuildItemCount)) + throw ELib3MFInterfaceException(LIB3MF_ERROR_ITERATORINVALIDINDEX); + + // Create specific API class + NMR::PModelBuildItem pBuildItem = m_pBuildItems[m_nCurrentIndex]; + + return new CBuildItem(pBuildItem); +} + +IBuildItemIterator * CBuildItemIterator::Clone () +{ + auto pBuildItems = std::unique_ptr(new CBuildItemIterator()); + + for (auto iIterator = m_pBuildItems.begin(); iIterator != m_pBuildItems.end(); iIterator++) + pBuildItems->addBuildItem(*iIterator); + + return pBuildItems.release(); +} + +Lib3MF_uint64 CBuildItemIterator::Count() +{ + return m_pBuildItems.size(); +} + diff --git a/Source/API/lib3mf_colorgroup.cpp b/Source/API/lib3mf_colorgroup.cpp new file mode 100644 index 0000000..0bff9d2 --- /dev/null +++ b/Source/API/lib3mf_colorgroup.cpp @@ -0,0 +1,115 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CColorGroup + +*/ + +#include "lib3mf_colorgroup.hpp" +#include "lib3mf_interfaceexception.hpp" + +// Include custom headers here. + + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CColorGroup +**************************************************************************************************************************/ + +CColorGroup::CColorGroup(NMR::PModelColorGroupResource pResource) + : CResource(std::static_pointer_cast(pResource)) +{ + +} + + +NMR::CModelColorGroupResource& CColorGroup::colorGroup() +{ + NMR::CModelColorGroupResource* pColorGroup = dynamic_cast(resource().get()); + if (pColorGroup == nullptr) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCOLORGROUP); + return *pColorGroup; +} + + +Lib3MF_uint32 CColorGroup::GetCount () +{ + return colorGroup().getCount(); +} + +void CColorGroup::GetAllPropertyIDs (Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer) +{ + Lib3MF_uint32 nCount = colorGroup().getCount(); + + if (pPropertyIDsNeededCount) + *pPropertyIDsNeededCount = nCount; + + if (nPropertyIDsBufferSize >= nCount && pPropertyIDsBuffer) { + if (!colorGroup().hasResourceIndexMap()) { + colorGroup().buildResourceIndexMap(); + } + for (Lib3MF_uint32 i = 0; i < nCount; i++) { + DWORD nPropertyID; + if (colorGroup().mapResourceIndexToPropertyID(i, nPropertyID)) { + *pPropertyIDsBuffer = nPropertyID; + } + else { + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDRESOURCEINDEX); + } + pPropertyIDsBuffer++; + } + } +} + +Lib3MF_uint32 CColorGroup::AddColor (const sLib3MFColor TheColor) +{ + NMR::nfColor cColor = TheColor.m_Red | (TheColor.m_Green << 8) | (TheColor.m_Blue << 16) | (TheColor.m_Alpha << 24); + + return colorGroup().addColor(cColor); +} + +void CColorGroup::SetColor (const Lib3MF_uint32 nPropertyID, const sLib3MFColor TheColor) +{ + NMR::nfColor cColor = TheColor.m_Red | (TheColor.m_Green << 8) | (TheColor.m_Blue << 16) | (TheColor.m_Alpha << 24); + colorGroup().setColor(nPropertyID, cColor); +} + +sLib3MFColor CColorGroup::GetColor (const Lib3MF_uint32 nPropertyID) +{ + NMR::nfColor cColor = colorGroup().getColor(nPropertyID); + sLib3MFColor c; + c.m_Red = (cColor) & 0xff; + c.m_Green = (cColor >> 8) & 0xff; + c.m_Blue = (cColor >> 16) & 0xff; + c.m_Alpha = (cColor >> 24) & 0xff; + return c; +} + +void CColorGroup::RemoveColor(const Lib3MF_uint32 nPropertyID) +{ + colorGroup().removeColor(nPropertyID); +} diff --git a/Source/API/lib3mf_colorgroupiterator.cpp b/Source/API/lib3mf_colorgroupiterator.cpp new file mode 100644 index 0000000..d35b93d --- /dev/null +++ b/Source/API/lib3mf_colorgroupiterator.cpp @@ -0,0 +1,48 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CColorGroupIterator + +*/ + +#include "lib3mf_colorgroupiterator.hpp" +#include "lib3mf_interfaceexception.hpp" + +// Include custom headers here. +#include "lib3mf_colorgroup.hpp" + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CColorGroupIterator +**************************************************************************************************************************/ + +IColorGroup * CColorGroupIterator::GetCurrentColorGroup () +{ + // Create specific API class + return new CColorGroup(std::dynamic_pointer_cast(GetCurrentResource())); +} + diff --git a/Source/API/lib3mf_component.cpp b/Source/API/lib3mf_component.cpp new file mode 100644 index 0000000..2230dcd --- /dev/null +++ b/Source/API/lib3mf_component.cpp @@ -0,0 +1,101 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CComponent + +*/ + +#include "lib3mf_component.hpp" +#include "lib3mf_interfaceexception.hpp" + +// Include custom headers here. +#include "lib3mf_utils.hpp" +#include "lib3mf_object.hpp" + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CComponent +**************************************************************************************************************************/ + +CComponent::CComponent(NMR::PModelComponent pComponent) +{ + if (pComponent.get() == nullptr) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCOMPONENT); + m_pComponent = pComponent; +} + + +IObject * CComponent::GetObjectResource() +{ + NMR::PModelResource pModelObject = m_pComponent->getModel()->findResource(m_pComponent->getObject()->getPackageResourceID()); + if (!pModelObject.get()) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDMODELRESOURCE); + + std::unique_ptr pObject(CObject::fnCreateObjectFromModelResource(pModelObject, true)); + if (pObject == nullptr) + throw ELib3MFInterfaceException(LIB3MF_ERROR_RESOURCENOTFOUND); + + return pObject.release(); +} + +Lib3MF_uint32 CComponent::GetObjectResourceID() +{ + return m_pComponent->getObject()->getPackageResourceID()->getUniqueID(); +} + +std::string CComponent::GetUUID(bool & bHasUUID) +{ + NMR::PUUID pUUID = m_pComponent->uuid(); + bHasUUID = (pUUID.get() != nullptr); + if (bHasUUID) + return pUUID->toString(); + else + return ""; +} + +void CComponent::SetUUID(const std::string & sUUID) +{ + NMR::PUUID pUUID = std::make_shared(sUUID); + m_pComponent->setUUID(pUUID); +} + +bool CComponent::HasTransform() +{ + return m_pComponent->hasTransform(); +} + +void CComponent::SetTransform (const sLib3MFTransform Transform) +{ + m_pComponent->setTransform(TransformToMatrix(Transform)); +} + +sLib3MFTransform CComponent::GetTransform() +{ + const NMR::NMATRIX3 matrix = m_pComponent->getTransform(); + return MatrixToTransform(matrix); +} + diff --git a/Source/API/lib3mf_componentsobject.cpp b/Source/API/lib3mf_componentsobject.cpp new file mode 100644 index 0000000..6c0658b --- /dev/null +++ b/Source/API/lib3mf_componentsobject.cpp @@ -0,0 +1,128 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CComponentsObject + +*/ + +#include "lib3mf_componentsobject.hpp" +#include "lib3mf_interfaceexception.hpp" + +#include "lib3mf_component.hpp" +#include "lib3mf_utils.hpp" + +// Include custom headers here. + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CComponentsObject +**************************************************************************************************************************/ + + +IComponentsObject* CComponentsObject::fnCreateComponentsObjectFromModelResource(NMR::PModelResource pResource, bool bFailIfUnkownClass) +{ + + if (!pResource.get()) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + + NMR::CModelComponentsObject * pMeshObject = dynamic_cast (pResource.get()); + if (pMeshObject) { + return new CComponentsObject(pResource); + } + + if (bFailIfUnkownClass) + throw ELib3MFInterfaceException(NMR_ERROR_UNKNOWNMODELRESOURCE); + + return nullptr; +} + +CComponentsObject::CComponentsObject(NMR::PModelResource pResource) + : CResource(pResource), CObject(pResource) +{ +} + +NMR::CModelComponentsObject * CComponentsObject::getComponentsObject() +{ + NMR::CModelComponentsObject * pComponentsObject = dynamic_cast (resource().get()); + if (pComponentsObject == nullptr) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCOMPONENTSOBJECT); + + return pComponentsObject; +} + +IComponent * CComponentsObject::AddComponent(IObject* pObjectResource, const sLib3MFTransform Transform) +{ + NMR::CModelComponentsObject * pComponentsObject = getComponentsObject(); + NMR::CModel * pModel = pComponentsObject->getModel(); + if (pModel == nullptr) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDMODEL); + + // Get Resource ID + NMR::UniqueResourceID nObjectID = pObjectResource->GetResourceID(); + + if (GetResourceID() == nObjectID) + throw ELib3MFInterfaceException(LIB3MF_ERROR_FORBIDDENCYCLICREFERENCE); + + // TODO: check all ancestors to avoid circular references + + // Find class instance + NMR::CModelObject * pObject = pModel->findObject(nObjectID); + if (pObject == nullptr) + throw ELib3MFInterfaceException(LIB3MF_ERROR_RESOURCENOTFOUND); + + // Convert Transform, if given + NMR::NMATRIX3 mMatrix = TransformToMatrix(Transform); + + // Create Model component + NMR::PModelComponent pNewComponent = std::make_shared(pObject, mMatrix); + pComponentsObject->addComponent(pNewComponent); + + return new CComponent(pNewComponent); +} + +IComponent * CComponentsObject::GetComponent (const Lib3MF_uint32 nIndex) +{ + NMR::CModelComponentsObject * pComponentsObject = getComponentsObject(); + NMR::PModelComponent pNewComponent = pComponentsObject->getComponent(nIndex); + return new CComponent(pNewComponent); +} + +Lib3MF_uint32 CComponentsObject::GetComponentCount () +{ + return getComponentsObject()->getComponentCount(); +} + +bool CComponentsObject::IsMeshObject() +{ + return false; +} + +bool CComponentsObject::IsComponentsObject() +{ + return true; +} + diff --git a/Source/API/lib3mf_componentsobjectiterator.cpp b/Source/API/lib3mf_componentsobjectiterator.cpp new file mode 100644 index 0000000..b677792 --- /dev/null +++ b/Source/API/lib3mf_componentsobjectiterator.cpp @@ -0,0 +1,47 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CComponentsObjectIterator + +*/ + +#include "lib3mf_componentsobjectiterator.hpp" +#include "lib3mf_interfaceexception.hpp" + +// Include custom headers here. +#include "lib3mf_componentsobject.hpp" + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CComponentsObjectIterator +**************************************************************************************************************************/ + +IComponentsObject * CComponentsObjectIterator::GetCurrentComponentsObject () +{ + return CComponentsObject::fnCreateComponentsObjectFromModelResource(GetCurrentResource(), true); +} + diff --git a/Source/API/lib3mf_compositematerials.cpp b/Source/API/lib3mf_compositematerials.cpp new file mode 100644 index 0000000..dd9fb1b --- /dev/null +++ b/Source/API/lib3mf_compositematerials.cpp @@ -0,0 +1,133 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CCompositeMaterials + +*/ + +#include "lib3mf_compositematerials.hpp" +#include "lib3mf_interfaceexception.hpp" + +// Include custom headers here. +#include "lib3mf_basematerialgroup.hpp" + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CCompositeMaterials +**************************************************************************************************************************/ + + +CCompositeMaterials::CCompositeMaterials(NMR::PModelCompositeMaterialsResource pResource) + : CResource(std::static_pointer_cast(pResource)) +{ + +} + + +NMR::CModelCompositeMaterialsResource& CCompositeMaterials::compositeMaterials() +{ + NMR::CModelCompositeMaterialsResource* pCompositeMaterials = dynamic_cast(resource().get()); + if (pCompositeMaterials == nullptr) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCOMPOSITEMATERIALS); + return *pCompositeMaterials; +} + +Lib3MF_uint32 CCompositeMaterials::GetCount () +{ + return compositeMaterials().getCount(); +} + +void CCompositeMaterials::GetAllPropertyIDs (Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer) +{ + Lib3MF_uint32 nCompositesCount = compositeMaterials().getCount(); + + if (pPropertyIDsNeededCount) + *pPropertyIDsNeededCount = nCompositesCount; + + if (nPropertyIDsBufferSize >= nCompositesCount && pPropertyIDsBuffer) { + if (!compositeMaterials().hasResourceIndexMap()) { + compositeMaterials().buildResourceIndexMap(); + } + for (Lib3MF_uint32 i = 0; i < nCompositesCount; i++) { + DWORD nPropertyID; + if (compositeMaterials().mapResourceIndexToPropertyID(i, nPropertyID)) { + *pPropertyIDsBuffer = nPropertyID; + } + else { + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDRESOURCEINDEX); + } + pPropertyIDsBuffer++; + } + } +} + +IBaseMaterialGroup * CCompositeMaterials::GetBaseMaterialGroup () +{ + return new CBaseMaterialGroup(compositeMaterials().getBaseMaterialResource()); +} + +Lib3MF_uint32 CCompositeMaterials::AddComposite(const Lib3MF_uint64 nCompositeBufferSize, const sLib3MFCompositeConstituent * pCompositeBuffer) +{ + if (nCompositeBufferSize > LIB3MF_MAXCOMPOSITEMATERIALS) + throw ELib3MFInterfaceException(LIB3MF_ERROR_ELEMENTCOUNTEXCEEDSLIMIT); + + NMR::PModelComposite constituents = std::make_shared(); + constituents->resize((size_t)nCompositeBufferSize); + for (size_t i = 0; i < (size_t)nCompositeBufferSize; i++) { + (*constituents)[i].m_dMixingRatio = pCompositeBuffer[i].m_MixingRatio; + (*constituents)[i].m_nPropertyID = pCompositeBuffer[i].m_PropertyID; + } + return compositeMaterials().addComposite(constituents); +} + +void CCompositeMaterials::RemoveComposite (const Lib3MF_uint32 nPropertyID) +{ + compositeMaterials().removeComposite(nPropertyID); +} + +void CCompositeMaterials::GetComposite(const Lib3MF_uint32 nPropertyID, Lib3MF_uint64 nCompositeBufferSize, Lib3MF_uint64* pCompositeNeededCount, sLib3MFCompositeConstituent * pCompositeBuffer) +{ + + if (nCompositeBufferSize > LIB3MF_MAXCOMPOSITEMATERIALS) + throw ELib3MFInterfaceException(LIB3MF_ERROR_ELEMENTCOUNTEXCEEDSLIMIT); + + NMR::PModelComposite constituents = compositeMaterials().getComposite(nPropertyID); + + if (pCompositeNeededCount) { + *pCompositeNeededCount = constituents->size(); + } + + if (pCompositeBuffer && nCompositeBufferSize >= constituents->size()) { + for (size_t i = 0; i < (size_t) nCompositeBufferSize; i++) { + pCompositeBuffer[i].m_MixingRatio = (*constituents)[i].m_dMixingRatio; + pCompositeBuffer[i].m_PropertyID = (*constituents)[i].m_nPropertyID; + } + } + +} + + diff --git a/Source/API/lib3mf_compositematerialsiterator.cpp b/Source/API/lib3mf_compositematerialsiterator.cpp new file mode 100644 index 0000000..a3cebbd --- /dev/null +++ b/Source/API/lib3mf_compositematerialsiterator.cpp @@ -0,0 +1,48 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CCompositeMaterialsIterator + +*/ + +#include "lib3mf_compositematerialsiterator.hpp" +#include "lib3mf_interfaceexception.hpp" + +// Include custom headers here. +#include "lib3mf_compositematerials.hpp" + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CCompositeMaterialsIterator +**************************************************************************************************************************/ + +ICompositeMaterials * CCompositeMaterialsIterator::GetCurrentCompositeMaterials () +{ + // Create specific API class + return new CCompositeMaterials(std::dynamic_pointer_cast(GetCurrentResource())); +} + diff --git a/Source/API/lib3mf_consumer.cpp b/Source/API/lib3mf_consumer.cpp new file mode 100644 index 0000000..beb85f3 --- /dev/null +++ b/Source/API/lib3mf_consumer.cpp @@ -0,0 +1,22 @@ +#include "lib3mf_consumer.hpp" +#include "lib3mf_interfaceexception.hpp" +#include "Model/Classes/NMR_KeyStoreConsumer.h" + + +using namespace Lib3MF::Impl; + +Lib3MF::Impl::CConsumer::CConsumer(NMR::PKeyStoreConsumer const & consumer) { + m_Consumer = consumer; +} + +std::string Lib3MF::Impl::CConsumer::GetConsumerID() { + return m_Consumer->getConsumerID(); +} + +std::string Lib3MF::Impl::CConsumer::GetKeyID() { + return m_Consumer->getKeyID(); +} + +std::string Lib3MF::Impl::CConsumer::GetKeyValue() { + return m_Consumer->getKeyValue(); +} diff --git a/Source/API/lib3mf_contentencryptionparams.cpp b/Source/API/lib3mf_contentencryptionparams.cpp new file mode 100644 index 0000000..f431940 --- /dev/null +++ b/Source/API/lib3mf_contentencryptionparams.cpp @@ -0,0 +1,73 @@ +#include "lib3mf_contentencryptionparams.hpp" +#include "lib3mf_interfaceexception.hpp" + +using namespace Lib3MF::Impl; + + +namespace Lib3MF { + namespace Impl { + CContentEncryptionParams::CContentEncryptionParams(NMR::PCKeyStoreContentEncryptionParams const & p): m_pParams(p) { + if (!p) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + } + + Lib3MF_uint64 CContentEncryptionParams::GetDescriptor() { + return m_pParams->getDescriptor(); + } + + eEncryptionAlgorithm CContentEncryptionParams::GetEncryptionAlgorithm() { + return(eEncryptionAlgorithm)m_pParams->getEncryptionAlgorithm(); + } + + void CContentEncryptionParams::GetKey(Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64 *pByteDataNeededCount, Lib3MF_uint8 *pByteDataBuffer) { + const std::vector & buf = m_pParams->getKey(); + if (nByteDataBufferSize < buf.size() || nullptr == pByteDataBuffer) + *pByteDataNeededCount = buf.size(); + else { + std::copy(buf.begin(), buf.end(), pByteDataBuffer); + } + } + + void CContentEncryptionParams::GetInitializationVector(Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64 *pByteDataNeededCount, Lib3MF_uint8 *pByteDataBuffer) { + const std::vector & buf = m_pParams->getInitVector(); + if (nByteDataBufferSize < buf.size() || nullptr == pByteDataBuffer) + *pByteDataNeededCount = buf.size(); + else { + std::copy(buf.begin(), buf.end(), pByteDataBuffer); + } + } + + void CContentEncryptionParams::GetAuthenticationTag(Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64 *pByteDataNeededCount, Lib3MF_uint8 *pByteDataBuffer) { + const std::vector & buf = m_pParams->getAuthTag(); + if (nByteDataBufferSize < buf.size() || nullptr == pByteDataBuffer) + *pByteDataNeededCount = buf.size(); + else { + std::copy(buf.begin(), buf.end(), pByteDataBuffer); + } + } + + void CContentEncryptionParams::SetAuthenticationTag(Lib3MF_uint64 const nByteDataBufferSize, const Lib3MF_uint8 *pByteDataBuffer) { + std::vector tag(pByteDataBuffer, pByteDataBuffer + nByteDataBufferSize); + m_pParams->setAuthTag(tag); + } + + void CContentEncryptionParams::GetAdditionalAuthenticationData(Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64 *pByteDataNeededCount, Lib3MF_uint8 *pByteDataBuffer) { + const std::vector & buf = m_pParams->getAddAuthData(); + if (nByteDataBufferSize < buf.size() || nullptr == pByteDataBuffer) + *pByteDataNeededCount = buf.size(); + else { + std::copy(buf.begin(), buf.end(), pByteDataBuffer); + } + } + + void CContentEncryptionParams::SetAdditionalAuthenticationData(Lib3MF_uint64 const nByteDataBufferSize, const Lib3MF_uint8 *pByteDataBuffer) { + std::vector aad(pByteDataBuffer, pByteDataBuffer + nByteDataBufferSize); + m_pParams->setAddAuthData(aad); + } + + std::string CContentEncryptionParams::GetKeyUUID() { + return std::string(); + } + } +} + diff --git a/Source/API/lib3mf_keystore.cpp b/Source/API/lib3mf_keystore.cpp new file mode 100644 index 0000000..d4b7684 --- /dev/null +++ b/Source/API/lib3mf_keystore.cpp @@ -0,0 +1,161 @@ +#include "lib3mf_types.hpp" +#include "lib3mf_keystore.hpp" +#include "lib3mf_interfaceexception.hpp" +#include "lib3mf_consumer.hpp" +#include "lib3mf_resourcedatagroup.hpp" +#include "lib3mf_resourcedata.hpp" +#include "lib3mf_packagepart.hpp" +#include "lib3mf_utils.hpp" + +#include "Model/Classes/NMR_KeyStoreFactory.h" +#include "Model/Classes/NMR_PackageResourceID.h" +#include "Model/Classes/NMR_Model.h" +#include "Common/NMR_SecureContentTypes.h" +#include "Common/NMR_Types.h" + +#include + +using namespace Lib3MF::Impl; + +Lib3MF::Impl::CKeyStore::CKeyStore(NMR::PModel const & pModel) + :m_pModel(pModel) +{ + if (nullptr == pModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDKEYSTORE); + m_pKeyStore = pModel->getKeyStore(); +} + +IConsumer * Lib3MF::Impl::CKeyStore::AddConsumer(const std::string & sConsumerID, const std::string & sKeyID, const std::string & sKeyValue) +{ + NMR::PKeyStoreConsumer consumer = NMR::CKeyStoreFactory::makeConsumer(sConsumerID); + consumer->setKeyID(sKeyID); + consumer->setKeyValue(sKeyValue); + m_pKeyStore->addConsumer(consumer); + return new CConsumer(consumer); +} + +Lib3MF_uint64 Lib3MF::Impl::CKeyStore::GetConsumerCount() +{ + return m_pKeyStore->getConsumerCount(); +} + +IConsumer * Lib3MF::Impl::CKeyStore::GetConsumer(const Lib3MF_uint64 nConsumerIndex) +{ + NMR::PKeyStoreConsumer consumer = m_pKeyStore->getConsumer(nConsumerIndex); + return new CConsumer(consumer); +} + +IConsumer * Lib3MF::Impl::CKeyStore::FindConsumer(const std::string & sConsumerID) +{ + NMR::PKeyStoreConsumer consumer = m_pKeyStore->findConsumerById(sConsumerID); + if (!consumer) + return nullptr; + return new CConsumer(consumer); +} + +void Lib3MF::Impl::CKeyStore::RemoveConsumer(IConsumer * pConsumerInstance) +{ + CConsumer * pConsumer = dynamic_cast(pConsumerInstance); + if (!pConsumer) { + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDKEYSTORECONSUMER); + } + m_pKeyStore->removeConsumer(pConsumer->consumer()); +} + +std::string Lib3MF::Impl::CKeyStore::GetUUID(bool & bHasUUID) { + bHasUUID = m_pKeyStore->getUUID() != nullptr; + if (bHasUUID) + return m_pKeyStore->getUUID()->toString(); + return ""; +} + +void Lib3MF::Impl::CKeyStore::SetUUID(const std::string & sUUID) +{ + NMR::PUUID pUUID = std::make_shared(sUUID); + m_pKeyStore->setUUID(pUUID); +} + +Lib3MF_uint64 Lib3MF::Impl::CKeyStore::GetResourceDataGroupCount() +{ + return (Lib3MF_uint32)m_pKeyStore->getResourceDataGroupCount(); +} + +IResourceDataGroup * Lib3MF::Impl::CKeyStore::GetResourceDataGroup(const Lib3MF_uint64 nResourceDataIndex) +{ + NMR::PKeyStoreResourceDataGroup dg = m_pKeyStore->getResourceDataGroup(nResourceDataIndex); + return new CResourceDataGroup(dg); +} + +IResourceDataGroup * Lib3MF::Impl::CKeyStore::AddResourceDataGroup() { + //this is not ideal, as key size is determined by the encryptionalgorithm inside resourcedata. + //in any case, the spec does not state what happens if different resource datas have different algorithms, + //but resourcedatagroups are supposed to group the same key for a group of resources... + //so far, this should work as aes256 is the only thing we support. + std::vector key(NMR::fnGetAlgorithmKeySize(NMR::eKeyStoreEncryptAlgorithm::AES256_GCM), 0); + m_pModel->generateRandomBytes(key.data(), key.size()); + NMR::PKeyStoreResourceDataGroup dg = NMR::CKeyStoreFactory::makeResourceDataGroup(std::make_shared(), key); + m_pKeyStore->addResourceDataGroup(dg); + return new CResourceDataGroup(dg); +} + +void Lib3MF::Impl::CKeyStore::RemoveResourceDataGroup(IResourceDataGroup * pTheResourceDataGroup) { + CResourceDataGroup * dg = dynamic_cast(pTheResourceDataGroup); + if (!dg) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + m_pKeyStore->removeResourceDataGroup(dg->resourceDataGroup()); +} + +Lib3MF::Impl::IResourceDataGroup * Lib3MF::Impl::CKeyStore::FindResourceDataGroup(Lib3MF::Impl::IPackagePart *pPartPath) { + NMR::PPackageModelPath pPath = m_pModel->findOrCreateModelPath(pPartPath->GetPath()); + if (!pPath) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + + NMR::PKeyStoreResourceDataGroup dg = m_pKeyStore->findResourceDataGroupByResourceDataPath(pPath); + if (!dg) + return nullptr; + return new CResourceDataGroup(dg); +} + +Lib3MF::Impl::IResourceData * Lib3MF::Impl::CKeyStore::AddResourceData(Lib3MF::Impl::IResourceDataGroup *pResourceDataGroup, Lib3MF::Impl::IPackagePart *pPartPath, Lib3MF::eEncryptionAlgorithm eAlgorithm, Lib3MF::eCompression eCompression, Lib3MF_uint64 nAdditionalAuthenticationDataBufferSize, const Lib3MF_uint8 *pAdditionalAuthenticationDataBuffer) { + bool compression = translateCompression(eCompression); + NMR::eKeyStoreEncryptAlgorithm algorithm = translateEncryptionAlgorithm(eAlgorithm); + CResourceDataGroup * dg = dynamic_cast(pResourceDataGroup); + if (!dg) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + //pPartPath might have different implementations, so asking model get us right to what we need. + NMR::PPackageModelPath pPath = m_pModel->findOrCreateModelPath(pPartPath->GetPath()); + if (!pPath) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + + std::vector aad(pAdditionalAuthenticationDataBuffer, pAdditionalAuthenticationDataBuffer + nAdditionalAuthenticationDataBufferSize); + NMR::PKeyStoreCEKParams params = NMR::CKeyStoreFactory::makeCEKParams(compression, algorithm, aad); + NMR::PKeyStoreResourceData rd = NMR::CKeyStoreFactory::makeResourceData(dg->resourceDataGroup(), pPath, params); + m_pKeyStore->addResourceData(rd); + return new CResourceData(rd); +} + +void Lib3MF::Impl::CKeyStore::RemoveResourceData(Lib3MF::Impl::IResourceData *pResourceData) { + CResourceData * rd = dynamic_cast(pResourceData); + if (!rd) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + m_pKeyStore->removeResourceData(rd->resourceData()); +} + +Lib3MF_uint64 Lib3MF::Impl::CKeyStore::GetResourceDataCount() { + return m_pKeyStore->getResourceDataCount(); +} + +Lib3MF::Impl::IResourceData * Lib3MF::Impl::CKeyStore::GetResourceData(Lib3MF_uint64 nResourceDataIndex) { + NMR::PKeyStoreResourceData rd = m_pKeyStore->getResourceData(nResourceDataIndex); + return new CResourceData(rd); +} + +IResourceData * Lib3MF::Impl::CKeyStore::FindResourceData(IPackagePart * pResourcePath) { + NMR::PPackageModelPath pPath = m_pModel->findOrCreateModelPath(pResourcePath->GetPath()); + if (!pPath) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + NMR::PKeyStoreResourceData rd = m_pKeyStore->findResourceData(pPath); + if (!rd) + return nullptr; + return new CResourceData(rd); +} diff --git a/Source/API/lib3mf_meshobject.cpp b/Source/API/lib3mf_meshobject.cpp new file mode 100644 index 0000000..7c7e4f5 --- /dev/null +++ b/Source/API/lib3mf_meshobject.cpp @@ -0,0 +1,390 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CMeshObject + +*/ +#include "lib3mf_meshobject.hpp" +#include "lib3mf_interfaceexception.hpp" + +#include "lib3mf_beamlattice.hpp" +// Include custom headers here. + +#include "Common/MeshInformation/NMR_MeshInformation_Properties.h" +#include + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CMeshObject + **************************************************************************************************************************/ + +IMeshObject* CMeshObject::fnCreateMeshObjectFromModelResource(NMR::PModelResource pResource, bool bFailIfUnkownClass) { + + if (!pResource.get()) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + + NMR::CModelMeshObject * pMeshObject = dynamic_cast (pResource.get()); + if (pMeshObject) { + return new CMeshObject(pResource); + } + + if (bFailIfUnkownClass) + throw ELib3MFInterfaceException(NMR_ERROR_UNKNOWNMODELRESOURCE); + + return nullptr; +} + +NMR::CMeshInformation_Properties* CMeshObject::getMeshInformationProperties() +{ + auto pMesh = mesh(); + auto pInformationHandler = pMesh->createMeshInformationHandler(); + NMR::CMeshInformation_Properties * pInformation = dynamic_cast (pInformationHandler->getInformationByType(0, NMR::emiProperties)); + + if (pInformation == nullptr) { + NMR::PMeshInformation_Properties pNewInformation = std::make_shared(pMesh->getFaceCount()); + pInformationHandler->addInformation(pNewInformation); + + pInformation = pNewInformation.get(); + } + return pInformation; +} + +CMeshObject::CMeshObject(NMR::PModelResource pResource) + : CResource(pResource), CObject(pResource) +{ + +} + +NMR::PModelMeshObject CMeshObject::meshObject() +{ + NMR::PModelMeshObject pMesh = std::dynamic_pointer_cast(resource()); + if (pMesh == nullptr) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDOBJECT); + return pMesh; +} + +NMR::CMesh* CMeshObject::mesh() +{ + return meshObject()->getMesh(); +} + +Lib3MF_uint32 CMeshObject::GetVertexCount () +{ + return mesh()->getNodeCount(); +} + +Lib3MF_uint32 CMeshObject::GetTriangleCount () +{ + return mesh()->getFaceCount(); +} + +void CMeshObject::SetVertex (const Lib3MF_uint32 nIndex, const sLib3MFPosition Coordinates) +{ + NMR::MESHNODE* node = mesh()->getNode(nIndex); + node->m_position.m_fields[0] = Coordinates.m_Coordinates[0]; + node->m_position.m_fields[1] = Coordinates.m_Coordinates[1]; + node->m_position.m_fields[2] = Coordinates.m_Coordinates[2]; +} + +sLib3MFPosition CMeshObject::GetVertex(const Lib3MF_uint32 nIndex) +{ + NMR::MESHNODE* node = mesh()->getNode(nIndex); + sLib3MFPosition pos; + pos.m_Coordinates[0] = node->m_position.m_fields[0]; + pos.m_Coordinates[1] = node->m_position.m_fields[1]; + pos.m_Coordinates[2] = node->m_position.m_fields[2]; + return pos; +} + +Lib3MF_uint32 CMeshObject::AddVertex (const sLib3MFPosition Coordinates) +{ + return mesh()->addNode(Coordinates.m_Coordinates[0], Coordinates.m_Coordinates[1], Coordinates.m_Coordinates[2])->m_index; +} + +void CMeshObject::GetVertices(Lib3MF_uint64 nVerticesBufferSize, Lib3MF_uint64* pVerticesNeededCount, sLib3MFPosition * pVerticesBuffer) +{ + Lib3MF_uint32 nodeCount = mesh()->getNodeCount(); + if (pVerticesNeededCount) + *pVerticesNeededCount = nodeCount; + + if (nVerticesBufferSize >= nodeCount && pVerticesBuffer) + { + for (Lib3MF_uint32 i = 0; i < nodeCount; i++) + { + const NMR::MESHNODE* node = mesh()->getNode(i); + pVerticesBuffer[i].m_Coordinates[0] = node->m_position.m_fields[0]; + pVerticesBuffer[i].m_Coordinates[1] = node->m_position.m_fields[1]; + pVerticesBuffer[i].m_Coordinates[2] = node->m_position.m_fields[2]; + } + } +} + +sLib3MFTriangle CMeshObject::GetTriangle (const Lib3MF_uint32 nIndex) +{ + sLib3MFTriangle t; + NMR::MESHFACE* mf = mesh()->getFace(nIndex); + + t.m_Indices[0] = mf->m_nodeindices[0]; + t.m_Indices[1] = mf->m_nodeindices[1]; + t.m_Indices[2] = mf->m_nodeindices[2]; + + return t; +} + +void CMeshObject::SetTriangle (const Lib3MF_uint32 nIndex, const sLib3MFTriangle Indices) +{ + NMR::MESHFACE* mf = mesh()->getFace(nIndex); + + mf->m_nodeindices[0] = Indices.m_Indices[0]; + mf->m_nodeindices[1] = Indices.m_Indices[1]; + mf->m_nodeindices[2] = Indices.m_Indices[2]; +} + +Lib3MF_uint32 CMeshObject::AddTriangle(const sLib3MFTriangle Indices) +{ + return mesh()->addFace(Indices.m_Indices[0], Indices.m_Indices[1], Indices.m_Indices[2])->m_index; +} + +void CMeshObject::GetTriangleIndices (Lib3MF_uint64 nIndicesBufferSize, Lib3MF_uint64* pIndicesNeededCount, sLib3MFTriangle * pIndicesBuffer) +{ + Lib3MF_uint32 faceCount = mesh()->getFaceCount(); + if (pIndicesNeededCount) + *pIndicesNeededCount = faceCount; + + if (nIndicesBufferSize >= faceCount && pIndicesBuffer) + { + for (Lib3MF_uint32 i = 0; i < faceCount; i++) + { + const NMR::MESHFACE* face = mesh()->getFace(i); + pIndicesBuffer[i].m_Indices[0] = face->m_nodeindices[0]; + pIndicesBuffer[i].m_Indices[1] = face->m_nodeindices[1]; + pIndicesBuffer[i].m_Indices[2] = face->m_nodeindices[2]; + } + } +} + +void CMeshObject::SetObjectLevelProperty(const Lib3MF_uint32 nUniqueResourceID, const Lib3MF_uint32 nPropertyID) +{ + NMR::CMeshInformation_Properties * pInformation = getMeshInformationProperties(); + + NMR::MESHINFORMATION_PROPERTIES * pDefaultData = new NMR::MESHINFORMATION_PROPERTIES; + pDefaultData->m_nUniqueResourceID = nUniqueResourceID; + pDefaultData->m_nPropertyIDs[0] = nPropertyID; + pDefaultData->m_nPropertyIDs[1] = nPropertyID; + pDefaultData->m_nPropertyIDs[2] = nPropertyID; + + pInformation->setDefaultData((NMR::MESHINFORMATIONFACEDATA*)pDefaultData); +} + +bool CMeshObject::GetObjectLevelProperty(Lib3MF_uint32 & nUniqueResourceID, Lib3MF_uint32 & nPropertyID) +{ + NMR::CMeshInformation_Properties * pInformation = getMeshInformationProperties(); + + NMR::MESHINFORMATION_PROPERTIES * pDefaultData = (NMR::MESHINFORMATION_PROPERTIES*)pInformation->getDefaultData(); + if (pDefaultData) { + nUniqueResourceID = pDefaultData->m_nUniqueResourceID; + nPropertyID = pDefaultData->m_nPropertyIDs[0]; + return true; + } + return false; +} + +void CMeshObject::SetTriangleProperties(const Lib3MF_uint32 nIndex, const sLib3MFTriangleProperties Properties) +{ + NMR::CMeshInformation_Properties * pInformation = getMeshInformationProperties(); + + NMR::MESHINFORMATION_PROPERTIES * pFaceData = (NMR::MESHINFORMATION_PROPERTIES*)pInformation->getFaceData(nIndex); + if (pFaceData != nullptr) { + pFaceData->m_nUniqueResourceID = Properties.m_ResourceID; + for (unsigned j = 0; j < 3; j++) { + pFaceData->m_nPropertyIDs[j] = Properties.m_PropertyIDs[j]; + } + } + +} + +void CMeshObject::GetTriangleProperties(const Lib3MF_uint32 nIndex, sLib3MFTriangleProperties & sProperty) +{ + NMR::CMeshInformation_Properties * pInformation = getMeshInformationProperties(); + + NMR::MESHINFORMATION_PROPERTIES * pFaceData = (NMR::MESHINFORMATION_PROPERTIES*)pInformation->getFaceData(nIndex); + if (pFaceData != nullptr) { + sProperty.m_ResourceID = pFaceData->m_nUniqueResourceID; + for (unsigned j = 0; j < 3; j++) { + sProperty.m_PropertyIDs[j] = pFaceData->m_nPropertyIDs[j]; + } + + } + else { + sProperty.m_ResourceID = 0; + for (unsigned j = 0; j < 3; j++) { + sProperty.m_PropertyIDs[j] = 0; + } + + } +} + +void CMeshObject::SetAllTriangleProperties(const Lib3MF_uint64 nPropertiesArrayBufferSize, const sLib3MFTriangleProperties * pPropertiesArrayBuffer) +{ + auto pMesh = mesh(); + uint32_t nFaceCount = pMesh->getFaceCount(); + + if (nPropertiesArrayBufferSize != nFaceCount) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPROPERTYCOUNT); + if (pPropertiesArrayBuffer == nullptr) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + + NMR::CMeshInformation_Properties * pInformation = getMeshInformationProperties(); + + const sLib3MFTriangleProperties * pProperty = pPropertiesArrayBuffer; + + for (uint32_t nIndex = 0; nIndex < nFaceCount; nIndex++) { + NMR::MESHINFORMATION_PROPERTIES * pFaceData = (NMR::MESHINFORMATION_PROPERTIES*)pInformation->getFaceData(nIndex); + if (pFaceData != nullptr) { + pFaceData->m_nUniqueResourceID = pProperty->m_ResourceID; + for (unsigned j = 0; j < 3; j++) { + pFaceData->m_nPropertyIDs[j] = pProperty->m_PropertyIDs[j]; + } + } + pProperty++; + } + + // Prepare an object-level property, if it makes sense to do so + if ((nFaceCount > 0) && (pInformation->getDefaultData() == nullptr)) { + NMR::MESHINFORMATION_PROPERTIES * pFaceData = (NMR::MESHINFORMATION_PROPERTIES*)pInformation->getFaceData(0); + std::unique_ptr pDefaultFaceData(new NMR::MESHINFORMATION_PROPERTIES); + pDefaultFaceData->m_nUniqueResourceID = pFaceData->m_nUniqueResourceID; + for (unsigned j = 0; j < 3; j++) { + pDefaultFaceData->m_nPropertyIDs[j] = pFaceData->m_nPropertyIDs[j]; + } + pInformation->setDefaultData((NMR::MESHINFORMATIONFACEDATA*)pDefaultFaceData.release()); + } + +} + +void CMeshObject::GetAllTriangleProperties(Lib3MF_uint64 nPropertiesArrayBufferSize, Lib3MF_uint64* pPropertiesArrayNeededCount, sLib3MFTriangleProperties * pPropertiesArrayBuffer) +{ + auto pMesh = mesh(); + uint32_t nFaceCount = pMesh->getFaceCount(); + + if (pPropertiesArrayNeededCount) + *pPropertiesArrayNeededCount = nFaceCount; + + if (nPropertiesArrayBufferSize >= nFaceCount && pPropertiesArrayBuffer) + { + NMR::CMeshInformation_Properties * pInformation = getMeshInformationProperties(); + + sLib3MFTriangleProperties * pProperty = pPropertiesArrayBuffer; + + uint32_t nIndex; + for (nIndex = 0; nIndex < nFaceCount; nIndex++) { + + NMR::MESHINFORMATION_PROPERTIES * pFaceData = (NMR::MESHINFORMATION_PROPERTIES*)pInformation->getFaceData(nIndex); + if (pFaceData != nullptr) { + pProperty->m_ResourceID = pFaceData->m_nUniqueResourceID; + for (unsigned j = 0; j < 3; j++) { + pProperty->m_PropertyIDs[j] = pFaceData->m_nPropertyIDs[j]; + } + } + pProperty++; + } + } +} + +void CMeshObject::ClearAllProperties() +{ + mesh()->clearMeshInformationHandler(); +} + +void CMeshObject::SetGeometry(const Lib3MF_uint64 nVerticesBufferSize, const sLib3MFPosition * pVerticesBuffer, const Lib3MF_uint64 nIndicesBufferSize, const sLib3MFTriangle * pIndicesBuffer) +{ + if ( ((!pVerticesBuffer) && (nVerticesBufferSize>0)) || ((!pIndicesBuffer) && (nIndicesBufferSize>0))) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + + NMR::CMesh * pMesh = mesh(); + + // Clear old mesh + pMesh->clear(); + + // Rebuild Mesh Coordinates + const sLib3MFPosition * pVertex = pVerticesBuffer; + for (Lib3MF_uint64 nIndex = 0; nIndex < nVerticesBufferSize; nIndex++) { + for (int j = 0; j < 3; j++) { + if (std::fabs(pVertex->m_Coordinates[j]) > NMR_MESH_MAXCOORDINATE) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + } + pMesh->addNode(pVertex->m_Coordinates[0], pVertex->m_Coordinates[1], pVertex->m_Coordinates[2]); + + pVertex++; + } + + // Rebuild Mesh Faces + const sLib3MFTriangle * pTriangle = pIndicesBuffer; + for (Lib3MF_uint64 nIndex = 0; nIndex < nIndicesBufferSize; nIndex++) { + NMR::MESHNODE * pNodes[3]; + + for (int j = 0; j < 3; j++) { + if (pTriangle->m_Indices[j] >= nVerticesBufferSize) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + pNodes[j] = pMesh->getNode(pTriangle->m_Indices[j]); + } + + if ((pTriangle->m_Indices[0] == pTriangle->m_Indices[1]) || + (pTriangle->m_Indices[0] == pTriangle->m_Indices[2]) || + (pTriangle->m_Indices[1] == pTriangle->m_Indices[2])) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + + pMesh->addFace(pNodes[0], pNodes[1], pNodes[2]); + + pTriangle++; + } +} + +bool CMeshObject::IsManifoldAndOriented () +{ + return meshObject()->isManifoldAndOriented(); +} + +bool CMeshObject::IsMeshObject() +{ + return true; +} + +bool CMeshObject::IsComponentsObject() +{ + return false; +} + +bool CMeshObject::IsValid() +{ + return meshObject()->isValid(); +} + +IBeamLattice* CMeshObject::BeamLattice() +{ + return new CBeamLattice(meshObject(), meshObject()->getBeamLatticeAttributes()); +} diff --git a/Source/API/lib3mf_meshobjectiterator.cpp b/Source/API/lib3mf_meshobjectiterator.cpp new file mode 100644 index 0000000..3dffbdc --- /dev/null +++ b/Source/API/lib3mf_meshobjectiterator.cpp @@ -0,0 +1,47 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CMeshObjectIterator + +*/ + +#include "lib3mf_meshobjectiterator.hpp" +#include "lib3mf_interfaceexception.hpp" + +// Include custom headers here. +#include "lib3mf_meshobject.hpp" + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CObjectIterator +**************************************************************************************************************************/ + +IMeshObject * CMeshObjectIterator::GetCurrentMeshObject () +{ + return CMeshObject::fnCreateMeshObjectFromModelResource(GetCurrentResource(), true); +} + diff --git a/Source/API/lib3mf_metadata.cpp b/Source/API/lib3mf_metadata.cpp new file mode 100644 index 0000000..664ead9 --- /dev/null +++ b/Source/API/lib3mf_metadata.cpp @@ -0,0 +1,103 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CMetaData + +*/ + +#include "lib3mf_metadata.hpp" +#include "lib3mf_interfaceexception.hpp" + +// Include custom headers here. + + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CMetaData +**************************************************************************************************************************/ + +CMetaData::CMetaData(NMR::PModelMetaData pMetaData) + :m_pMetaData(pMetaData) +{ +} + + +std::string CMetaData::GetNameSpace () +{ + return m_pMetaData->getNameSpace(); +} + +void CMetaData::SetNameSpace (const std::string & sNameSpace) +{ + m_pMetaData->setNameSpace(sNameSpace); +} + +std::string CMetaData::GetName() +{ + return m_pMetaData->getName(); +} + +std::string CMetaData::GetKey() +{ + return m_pMetaData->getKey(); +} + +void CMetaData::SetName (const std::string & sName) +{ + m_pMetaData->setName(sName); +} + +bool CMetaData::GetMustPreserve () +{ + return m_pMetaData->getPreserve(); +} + +void CMetaData::SetMustPreserve (const bool bMustPreserve) +{ + m_pMetaData->setPreserve(bMustPreserve); +} + +std::string CMetaData::GetType () +{ + return m_pMetaData->getType(); +} + +void CMetaData::SetType (const std::string & sType) +{ + m_pMetaData->setType(sType); +} + +std::string CMetaData::GetValue () +{ + return m_pMetaData->getValue(); +} + +void CMetaData::SetValue (const std::string & sValue) +{ + m_pMetaData->setValue(sValue); +} + diff --git a/Source/API/lib3mf_metadatagroup.cpp b/Source/API/lib3mf_metadatagroup.cpp new file mode 100644 index 0000000..cbf1913 --- /dev/null +++ b/Source/API/lib3mf_metadatagroup.cpp @@ -0,0 +1,100 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CMetaDataGroup + +*/ + +#include "lib3mf_metadatagroup.hpp" +#include "lib3mf_interfaceexception.hpp" + +#include "lib3mf_metadata.hpp" +// Include custom headers here. + + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CMetaDataGroup +**************************************************************************************************************************/ + +CMetaDataGroup::CMetaDataGroup(NMR::PModelMetaDataGroup pMetaDataGroup) + : m_pModelMetaDataGroup(pMetaDataGroup) +{ + +} + +Lib3MF_uint32 CMetaDataGroup::GetMetaDataCount () +{ + return m_pModelMetaDataGroup->getMetaDataCount(); +} + +IMetaData * CMetaDataGroup::GetMetaData (const Lib3MF_uint32 nIndex) +{ + return new CMetaData(m_pModelMetaDataGroup->getMetaData(nIndex)); +} + +IMetaData * CMetaDataGroup::GetMetaDataByKey (const std::string & sNameSpace, const std::string & sName) +{ + for (NMR::nfUint32 i = 0; i < m_pModelMetaDataGroup->getMetaDataCount(); i++) { + NMR::PModelMetaData pMetaData = m_pModelMetaDataGroup->getMetaData(i); + if (sNameSpace.empty()) { + if (pMetaData->getName() == sName) { + return new CMetaData(pMetaData); + } + } + else { + if (pMetaData->getKey() == sNameSpace + ":" + sName) { + return new CMetaData(pMetaData); + } + } + } + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); +} + +void CMetaDataGroup::RemoveMetaDataByIndex (const Lib3MF_uint32 nIndex) +{ + m_pModelMetaDataGroup->removeMetaData(nIndex); +} + +void CMetaDataGroup::RemoveMetaData(IMetaData* pTheMetaData) +{ + for (NMR::nfUint32 i = 0; i < m_pModelMetaDataGroup->getMetaDataCount(); i++) { + NMR::PModelMetaData pMetaData = m_pModelMetaDataGroup->getMetaData(i); + if (pTheMetaData->GetName() == pMetaData->getName()) { + m_pModelMetaDataGroup->removeMetaData(i); + return; + } + } + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); +} + +IMetaData * CMetaDataGroup::AddMetaData(const std::string & sNameSpace, const std::string & sName, const std::string & sValue, const std::string & sType, const bool bMustPreserve) +{ + NMR::PModelMetaData pModelMetaData = m_pModelMetaDataGroup->addMetaData(sNameSpace, sName, sValue, sType, bMustPreserve); + return new CMetaData(pModelMetaData); +} + diff --git a/Source/API/lib3mf_model.cpp b/Source/API/lib3mf_model.cpp new file mode 100644 index 0000000..514309b --- /dev/null +++ b/Source/API/lib3mf_model.cpp @@ -0,0 +1,708 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CModel + +*/ + +#include "lib3mf_model.hpp" +#include "lib3mf_interfaceexception.hpp" + +#include "lib3mf_reader.hpp" +#include "lib3mf_writer.hpp" + +#include "lib3mf_builditem.hpp" +#include "lib3mf_builditemiterator.hpp" +#include "lib3mf_meshobject.hpp" +#include "lib3mf_objectiterator.hpp" +#include "lib3mf_meshobjectiterator.hpp" +#include "lib3mf_resourceiterator.hpp" +#include "lib3mf_componentsobject.hpp" +#include "lib3mf_componentsobjectiterator.hpp" +#include "lib3mf_basematerialgroup.hpp" +#include "lib3mf_metadatagroup.hpp" +#include "lib3mf_attachment.hpp" +#include "lib3mf_slicestack.hpp" +#include "lib3mf_slicestackiterator.hpp" +#include "lib3mf_texture2d.hpp" +#include "lib3mf_texture2diterator.hpp" +#include "lib3mf_basematerialgroupiterator.hpp" +#include "lib3mf_colorgroup.hpp" +#include "lib3mf_colorgroupiterator.hpp" +#include "lib3mf_texture2dgroup.hpp" +#include "lib3mf_texture2dgroupiterator.hpp" +#include "lib3mf_compositematerials.hpp" +#include "lib3mf_compositematerialsiterator.hpp" +#include "lib3mf_multipropertygroup.hpp" +#include "lib3mf_multipropertygroupiterator.hpp" +#include "lib3mf_packagepart.hpp" +#include "lib3mf_keystore.hpp" + + +// Include custom headers here. +#include "Model/Classes/NMR_ModelMeshObject.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Common/Platform/NMR_ImportStream_Unique_Memory.h" +#include "Model/Classes/NMR_ModelColorGroup.h" +#include "Model/Classes/NMR_ModelTexture2DGroup.h" +#include "Model/Classes/NMR_ModelMultiPropertyGroup.h" +#include "Common/NMR_SecureContentTypes.h" +#include "lib3mf_utils.hpp" + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CModel +**************************************************************************************************************************/ + + +CModel::CModel() +{ + m_model = std::make_shared(); +} + +NMR::CModel& CModel::model() +{ + return *m_model; +} + +IPackagePart* CModel::RootModelPart() +{ + return new CPackagePart(model().rootModelPath()); +} + +IPackagePart * CModel::FindOrCreatePackagePart(const std::string & sAbsolutePath) +{ + return new CPackagePart(model().findOrCreateModelPath(sAbsolutePath)); +} + +void CModel::SetUnit (const eLib3MFModelUnit eUnit) +{ + model().setUnit(NMR::eModelUnit(eUnit)); +} + +eLib3MFModelUnit CModel::GetUnit () +{ + return eLib3MFModelUnit(model().getUnit()); +} + +std::string CModel::GetLanguage () +{ + return model().getLanguage(); +} + +void CModel::SetLanguage (const std::string & sLanguage) +{ + model().setLanguage(sLanguage); +} + +IWriter * CModel::QueryWriter (const std::string & sWriterClass) +{ + return new CWriter(sWriterClass, m_model); +} + +IReader * CModel::QueryReader (const std::string & sReaderClass) +{ + return new CReader(sReaderClass, m_model); +} + +ITexture2D * CModel::GetTexture2DByID(const Lib3MF_uint32 nUniqueResourceID) +{ + NMR::PModelTexture2DResource pTexture2DResource = model().findTexture2D(nUniqueResourceID); + if (pTexture2DResource) { + return new CTexture2D(pTexture2DResource); + } + else + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDTEXTURERESOURCE); +} + +eLib3MFPropertyType CModel::GetPropertyTypeByID(const Lib3MF_uint32 nUniqueResourceID) +{ + NMR::PModelResource pResource = model().findResource(nUniqueResourceID); + if (!pResource) { + throw ELib3MFInterfaceException(LIB3MF_ERROR_RESOURCENOTFOUND); + } + + if (dynamic_cast(pResource.get())) { + return ePropertyType::BaseMaterial; + } + else if ((dynamic_cast(pResource.get()))) { + return ePropertyType::Colors; + } + else if ((dynamic_cast(pResource.get()))) { + return ePropertyType::TexCoord; + } + else if ((dynamic_cast(pResource.get()))) { + return ePropertyType::Composite; + } + else if ((dynamic_cast(pResource.get()))) { + return ePropertyType::Multi; + } + else + return ePropertyType::NoPropertyType; +} + +IBaseMaterialGroup * CModel::GetBaseMaterialGroupByID(const Lib3MF_uint32 nUniqueResourceID) +{ + NMR::PPackageResourceID pID = model().findPackageResourceID(nUniqueResourceID); + if (pID) { + NMR::PModelBaseMaterialResource pBaseMaterialResource = model().findBaseMaterial(pID); + if (pBaseMaterialResource) { + return new CBaseMaterialGroup(pBaseMaterialResource); + } + else + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDBASEMATERIALGROUP); + } + else { + throw ELib3MFInterfaceException(LIB3MF_ERROR_RESOURCENOTFOUND); + } + +} + +IMeshObject * CModel::GetMeshObjectByID(const Lib3MF_uint32 nUniqueResourceID) +{ + NMR::PModelResource pObjectResource = model().findResource(nUniqueResourceID); + if (dynamic_cast(pObjectResource.get())) { + return new CMeshObject(pObjectResource); + } + else + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDMESHOBJECT); +} + +IComponentsObject * CModel::GetComponentsObjectByID(const Lib3MF_uint32 nUniqueResourceID) +{ + NMR::PModelResource pObjectResource = model().findResource(nUniqueResourceID); + if (dynamic_cast(pObjectResource.get())) { + return new CComponentsObject(pObjectResource); + } + else + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCOMPONENTSOBJECT); +} + +IColorGroup * CModel::GetColorGroupByID(const Lib3MF_uint32 nUniqueResourceID) +{ + NMR::PModelResource pResource = model().findResource(nUniqueResourceID); + if (dynamic_cast(pResource.get())) { + return new CColorGroup(std::dynamic_pointer_cast(pResource)); + } + else + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCOLORGROUP); +} + +ISliceStack * CModel::GetSliceStackByID(const Lib3MF_uint32 nUniqueResourceID) +{ + NMR::PModelResource pResource = model().findResource(nUniqueResourceID); + if (dynamic_cast(pResource.get())) { + return new CSliceStack(std::dynamic_pointer_cast(pResource)); + } + else + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDSLICESTACKRESOURCE); +} + +ITexture2DGroup * CModel::GetTexture2DGroupByID(const Lib3MF_uint32 nUniqueResourceID) +{ + NMR::PModelResource pResource = model().findResource(nUniqueResourceID); + if (dynamic_cast(pResource.get())) { + return new CTexture2DGroup(std::dynamic_pointer_cast(pResource)); + } + else + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDTEXTURE2DGROUP); +} + +ICompositeMaterials * CModel::GetCompositeMaterialsByID(const Lib3MF_uint32 nUniqueResourceID) +{ + NMR::PModelResource pResource = model().findResource(nUniqueResourceID); + if (dynamic_cast(pResource.get())) { + return new CCompositeMaterials(std::dynamic_pointer_cast(pResource)); + } + else + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCOMPOSITEMATERIALS); +} + +IMultiPropertyGroup * CModel::GetMultiPropertyGroupByID(const Lib3MF_uint32 nUniqueResourceID) +{ + NMR::PModelResource pResource = model().findResource(nUniqueResourceID); + if (dynamic_cast(pResource.get())) { + return new CMultiPropertyGroup(std::dynamic_pointer_cast(pResource)); + } + else + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDMULTIPROPERTYGROUP); +} + +std::string CModel::GetBuildUUID (bool & bHasUUID) +{ + NMR::PUUID buildUUID = model().buildUUID(); + bHasUUID = buildUUID.get() != nullptr; + if (bHasUUID) + return buildUUID->toString(); + return ""; +} + +void CModel::SetBuildUUID (const std::string & sUUID) +{ + NMR::PUUID pUUID = std::make_shared(sUUID); + model().setBuildUUID(pUUID); +} + +IBuildItemIterator * CModel::GetBuildItems () +{ + auto pResult = std::unique_ptr(new CBuildItemIterator()); + Lib3MF_uint32 nBuildItemCount = m_model->getBuildItemCount(); + Lib3MF_uint32 nIdx; + + for (nIdx = 0; nIdx < nBuildItemCount; nIdx++) + pResult->addBuildItem(m_model->getBuildItem(nIdx)); + + return pResult.release(); +} + +IResourceIterator * CModel::GetResources () +{ + auto pResult = std::unique_ptr(new CResourceIterator()); + Lib3MF_uint32 nResourcesCount = model().getResourceCount(); + + for (Lib3MF_uint32 nIdx = 0; nIdx < nResourcesCount; nIdx++) { + auto resource = model().getResource(nIdx); + pResult->addResource(resource); + } + return pResult.release(); +} + +IObjectIterator * CModel::GetObjects () +{ + auto pResult = std::unique_ptr(new CObjectIterator()); + Lib3MF_uint32 nObjectsCount = model().getObjectCount(); + + for (Lib3MF_uint32 nIdx = 0; nIdx < nObjectsCount; nIdx++) { + auto resource = model().getObjectResource(nIdx); + pResult->addResource(resource); + } + return pResult.release(); +} + +IMeshObjectIterator * CModel::GetMeshObjects () +{ + auto pResult = std::unique_ptr(new CMeshObjectIterator()); + Lib3MF_uint32 nObjectsCount = model().getObjectCount(); + + for (Lib3MF_uint32 nIdx = 0; nIdx < nObjectsCount; nIdx++) { + auto resource = model().getObjectResource(nIdx); + if (dynamic_cast(resource.get())) + pResult->addResource(resource); + } + return pResult.release(); +} + +IComponentsObjectIterator * CModel::GetComponentsObjects() +{ + auto pResult = std::unique_ptr(new CComponentsObjectIterator()); + Lib3MF_uint32 nObjectsCount = model().getObjectCount(); + + for (Lib3MF_uint32 nIdx = 0; nIdx < nObjectsCount; nIdx++) { + auto resource = model().getObjectResource(nIdx); + if (dynamic_cast(resource.get())) + pResult->addResource(resource); + } + return pResult.release(); +} + +ITexture2DIterator * CModel::GetTexture2Ds() +{ + auto pResult = std::unique_ptr(new CTexture2DIterator()); + Lib3MF_uint32 nCount = model().getTexture2DCount(); + + for (Lib3MF_uint32 nIdx = 0; nIdx < nCount; nIdx++) { + auto resource = model().getTexture2DResource(nIdx); + if (dynamic_cast(resource.get())) + pResult->addResource(resource); + } + return pResult.release(); +} + +IBaseMaterialGroupIterator * CModel::GetBaseMaterialGroups() +{ + auto pResult = std::unique_ptr(new CBaseMaterialGroupIterator()); + Lib3MF_uint32 nCount = model().getBaseMaterialCount(); + + for (Lib3MF_uint32 nIdx = 0; nIdx < nCount; nIdx++) { + auto resource = model().getBaseMaterialResource(nIdx); + if (dynamic_cast(resource.get())) + pResult->addResource(resource); + } + return pResult.release(); +} + +IColorGroupIterator * CModel::GetColorGroups() +{ + auto pResult = std::unique_ptr(new CColorGroupIterator()); + Lib3MF_uint32 nCount = model().getColorGroupCount(); + + for (Lib3MF_uint32 nIdx = 0; nIdx < nCount; nIdx++) { + auto resource = model().getColorGroupResource(nIdx); + if (dynamic_cast(resource.get())) + pResult->addResource(resource); + } + return pResult.release(); +} + +ITexture2DGroupIterator * CModel::GetTexture2DGroups() +{ + auto pResult = std::unique_ptr(new CTexture2DGroupIterator()); + Lib3MF_uint32 nCount = model().getTexture2DGroupCount(); + + for (Lib3MF_uint32 nIdx = 0; nIdx < nCount; nIdx++) { + auto resource = model().getTexture2DGroupResource(nIdx); + if (dynamic_cast(resource.get())) + pResult->addResource(resource); + } + return pResult.release(); +} + +ICompositeMaterialsIterator * CModel::GetCompositeMaterials() +{ + auto pResult = std::unique_ptr(new CCompositeMaterialsIterator()); + Lib3MF_uint32 nCount = model().getCompositeMaterialsCount(); + + for (Lib3MF_uint32 nIdx = 0; nIdx < nCount; nIdx++) { + auto resource = model().getCompositeMaterialsResource(nIdx); + if (dynamic_cast(resource.get())) + pResult->addResource(resource); + } + return pResult.release(); +} + +IMultiPropertyGroupIterator * CModel::GetMultiPropertyGroups() +{ + auto pResult = std::unique_ptr(new CMultiPropertyGroupIterator()); + Lib3MF_uint32 nCount = model().getMultiPropertyGroupCount(); + + for (Lib3MF_uint32 nIdx = 0; nIdx < nCount; nIdx++) { + auto resource = model().getMultiPropertyGroupResource(nIdx); + if (dynamic_cast(resource.get())) + pResult->addResource(resource); + } + return pResult.release(); +} + + +ISliceStackIterator * CModel::GetSliceStacks() +{ + auto pResult = std::unique_ptr(new CSliceStackIterator()); + Lib3MF_uint32 nCount = model().getSliceStackCount(); + + for (Lib3MF_uint32 nIdx = 0; nIdx < nCount; nIdx++) { + auto resource = model().getSliceStackResource(nIdx); + if (dynamic_cast(resource.get())) + pResult->addResource(resource); + } + return pResult.release(); +} + +IModel * CModel::MergeToModel () +{ + // Create merged mesh + NMR::PMesh pMesh = std::make_shared(); + model().mergeToMesh(pMesh.get()); + + auto pOutModel = std::unique_ptr(new CModel()); + + // Copy relevant resources to new model + NMR::CModel& newModel = pOutModel->model(); + + NMR::UniqueResourceIDMapping oldToNewUniqueResourceIDs; + + newModel.mergeModelAttachments(&model()); + newModel.mergeTextures2D(&model(), oldToNewUniqueResourceIDs); + newModel.mergeBaseMaterials(&model(), oldToNewUniqueResourceIDs); + newModel.mergeColorGroups(&model(), oldToNewUniqueResourceIDs); + newModel.mergeTexture2DGroups(&model(), oldToNewUniqueResourceIDs); + newModel.mergeCompositeMaterials(&model(), oldToNewUniqueResourceIDs); + newModel.mergeMultiPropertyGroups(&model(), oldToNewUniqueResourceIDs); + newModel.mergeMetaData(&model()); + + pMesh->patchMeshInformationResources(oldToNewUniqueResourceIDs); + + newModel.setUnit(model().getUnit()); + newModel.setLanguage(model().getLanguage()); + + NMR::PModelMeshObject pMeshObject = std::make_shared(newModel.generateResourceID(), &newModel, pMesh); + newModel.addResource(pMeshObject); + + NMR::PModelBuildItem pBuildItem = std::make_shared(pMeshObject.get(), model().createHandle()); + newModel.addBuildItem(pBuildItem); + + return pOutModel.release(); +} + +IMeshObject * CModel::AddMeshObject () +{ + NMR::ModelResourceID NewResourceID = model().generateResourceID(); + NMR::PMesh pNewMesh = std::make_shared(); + NMR::PModelMeshObject pNewResource = std::make_shared(NewResourceID, &model(), pNewMesh); + + model().addResource(pNewResource); + return new CMeshObject(pNewResource); +} + +IComponentsObject * CModel::AddComponentsObject () +{ + NMR::ModelResourceID NewResourceID = model().generateResourceID(); + NMR::PModelComponentsObject pNewResource = std::make_shared(NewResourceID, &model()); + + model().addResource(pNewResource); + return new CComponentsObject(pNewResource); +} + +ISliceStack * CModel::AddSliceStack(const Lib3MF_double dZBottom) +{ + NMR::ModelResourceID NewResourceID = model().generateResourceID(); + NMR::PModelSliceStack pNewResource = std::make_shared(NewResourceID, &model(), dZBottom); + + model().addResource(pNewResource); + + return new CSliceStack(pNewResource); +} + + +ITexture2D * CModel::AddTexture2DFromAttachment (IAttachment* pTextureAttachment) +{ + NMR::PModelAttachment attachment = model().findModelAttachment(pTextureAttachment->GetPath()); + + NMR::PModelTexture2DResource pResource = NMR::CModelTexture2DResource::make(model().generateResourceID(), &model(), attachment); + model().addResource(pResource); + + return new CTexture2D(pResource); +} + +IBaseMaterialGroup * CModel::AddBaseMaterialGroup () +{ + NMR::PModelBaseMaterialResource pResource = std::make_shared(model().generateResourceID(), &model()); + model().addResource(pResource); + + return new CBaseMaterialGroup(pResource); +} + +IColorGroup * CModel::AddColorGroup() +{ + NMR::PModelColorGroupResource pResource = std::make_shared(model().generateResourceID(), &model()); + model().addResource(pResource); + + return new CColorGroup(pResource); +} + +ITexture2DGroup * CModel::AddTexture2DGroup(ITexture2D* pTexture2DInstance) +{ + NMR::UniqueResourceID nTexture2DID = pTexture2DInstance->GetResourceID(); + + // Find class instance + NMR::PModelTexture2DResource pModelTexture2DObject = model().findTexture2D(nTexture2DID); + if (pModelTexture2DObject == nullptr) + throw ELib3MFInterfaceException(LIB3MF_ERROR_RESOURCENOTFOUND); + + NMR::PModelTexture2DGroupResource pResource = std::make_shared(model().generateResourceID(), &model(), pModelTexture2DObject); + model().addResource(pResource); + + return new CTexture2DGroup(pResource); +} + +ICompositeMaterials * CModel::AddCompositeMaterials(IBaseMaterialGroup* pBaseMaterialGroupInstance) +{ + NMR::UniqueResourceID nBaseMaterialGroupID = pBaseMaterialGroupInstance->GetUniqueResourceID(); + NMR::PPackageResourceID pID = model().findPackageResourceID(nBaseMaterialGroupID); + // Find class instance + NMR::PModelBaseMaterialResource pModelBaseMaterialGroup = model().findBaseMaterial(pID); + if (pModelBaseMaterialGroup == nullptr) + throw ELib3MFInterfaceException(LIB3MF_ERROR_RESOURCENOTFOUND); + + NMR::PModelCompositeMaterialsResource pResource = std::make_shared(model().generateResourceID(), &model(), pModelBaseMaterialGroup); + model().addResource(pResource); + + return new CCompositeMaterials(pResource); +} + +IMultiPropertyGroup * CModel::AddMultiPropertyGroup() +{ + NMR::PModelMultiPropertyGroupResource pResource = std::make_shared(model().generateResourceID(), &model()); + model().addResource(pResource); + + return new CMultiPropertyGroup(pResource); +} + +IBuildItem * CModel::AddBuildItem (IObject* pObject, const sLib3MFTransform Transform) +{ + // Get Resource ID + NMR::UniqueResourceID nObjectID = pObject->GetResourceID(); + + // Find class instance + NMR::CModelObject * pModelObject = model().findObject(nObjectID); + if (pModelObject == nullptr) + throw ELib3MFInterfaceException(LIB3MF_ERROR_RESOURCENOTFOUND); + + // Create Build item instance + NMR::PModelBuildItem pModelBuildItem = std::make_shared(pModelObject, TransformToMatrix(Transform), model().createHandle()); + model().addBuildItem(pModelBuildItem); + + return new CBuildItem(pModelBuildItem); +} + +void CModel::RemoveBuildItem (IBuildItem* pBuildItemInstance) +{ + CBuildItem* pLib3MFBuildItem = dynamic_cast (pBuildItemInstance); + if (!pLib3MFBuildItem) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDBUILDITEM); + model().removeBuildItem(pLib3MFBuildItem->GetHandle(), true); +} + +IMetaDataGroup * CModel::GetMetaDataGroup () +{ + return new CMetaDataGroup(model().getMetaDataGroup()); +} + +IAttachment * CModel::AddAttachment (const std::string & sURI, const std::string & sRelationShipType) +{ + NMR::PImportStream pStream = std::make_shared(); + + NMR::PModelAttachment pModelAttachment(model().addAttachment(sURI, sRelationShipType, pStream)); + + return new CAttachment(pModelAttachment); +} + +IAttachment * CModel::GetAttachment (const Lib3MF_uint32 nIndex) +{ + NMR::PModelAttachment pAttachment = m_model->getModelAttachment(nIndex); + return new CAttachment(pAttachment); +} + +IAttachment * CModel::FindAttachment (const std::string & sURI) +{ + NMR::PModelAttachment pAttachment = m_model->findModelAttachment(sURI); + + if (pAttachment.get() == nullptr) + throw ELib3MFInterfaceException(LIB3MF_ERROR_ATTACHMENTNOTFOUND); + + return new CAttachment(pAttachment); +} + +void CModel::RemoveAttachment(IAttachment* pAttachmentInstance) +{ + m_model->removeAttachment(pAttachmentInstance->GetPath()); +} + +Lib3MF_uint32 CModel::GetAttachmentCount () +{ + return m_model->getAttachmentCount(); +} + +bool CModel::HasPackageThumbnailAttachment() +{ + return m_model->getPackageThumbnail() != nullptr; +} + +IAttachment * CModel::CreatePackageThumbnailAttachment() +{ + NMR::PModelAttachment pModelAttachment; + if (HasPackageThumbnailAttachment()) + { + pModelAttachment = m_model->getPackageThumbnail(); + } + else { + pModelAttachment = m_model->addPackageThumbnail(); + } + if (pModelAttachment) { + return new CAttachment(pModelAttachment); + } + else { + throw ELib3MFInterfaceException(LIB3MF_ERROR_ATTACHMENTNOTFOUND); + } +} + +IAttachment * CModel::GetPackageThumbnailAttachment() +{ + if (HasPackageThumbnailAttachment()) + { + return new CAttachment(m_model->getPackageThumbnail()); + } + else { + return nullptr; + } +} + +void CModel::RemovePackageThumbnailAttachment() +{ + m_model->removePackageThumbnail(); +} + +void CModel::AddCustomContentType (const std::string & sExtension, const std::string & sContentType) +{ + m_model->addCustomContentType(sExtension, sContentType); +} + +void CModel::RemoveCustomContentType (const std::string & sExtension) +{ + m_model->removeCustomContentType(sExtension); +} + +Lib3MF::sBox CModel::GetOutbox() +{ + NMR::NOUTBOX3 sOutbox; + NMR::fnOutboxInitialize(sOutbox); + + for (NMR::nfUint32 iBuildItem = 0; iBuildItem < model().getBuildItemCount(); iBuildItem++) { + auto pBuildItem = model().getBuildItem(iBuildItem); + pBuildItem->getObject()->extendOutbox(sOutbox, pBuildItem->getTransform()); + } + + sBox s; + s.m_MinCoordinate[0] = sOutbox.m_min.m_fields[0]; + s.m_MinCoordinate[1] = sOutbox.m_min.m_fields[1]; + s.m_MinCoordinate[2] = sOutbox.m_min.m_fields[2]; + + s.m_MaxCoordinate[0] = sOutbox.m_max.m_fields[0]; + s.m_MaxCoordinate[1] = sOutbox.m_max.m_fields[1]; + s.m_MaxCoordinate[2] = sOutbox.m_max.m_fields[2]; + return s; +} + +IKeyStore * Lib3MF::Impl::CModel::GetKeyStore() { + return new CKeyStore(m_model); +} + +void Lib3MF::Impl::CModel::SetRandomNumberCallback(Lib3MF::RandomNumberCallback pTheCallback, Lib3MF_pvoid pUserData) { + if (nullptr == pTheCallback) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + NMR::CryptoRandGenDescriptor descriptor; + descriptor.m_pUserData = pUserData; + descriptor.m_fnRNG = [pTheCallback](NMR::nfByte * buffer, NMR::nfUint64 size, void * userData) { + Lib3MF_uint64 generated = 0; + (*pTheCallback)((Lib3MF_uint64)buffer, size, userData, &generated); + if (generated > 0) + return generated; + throw NMR::CNMRException(NMR_ERROR_CALCULATIONTERMINATED); + }; + + m_model->setCryptoRandCallback(descriptor); +} + diff --git a/Source/API/lib3mf_multipropertygroup.cpp b/Source/API/lib3mf_multipropertygroup.cpp new file mode 100644 index 0000000..eb88cfa --- /dev/null +++ b/Source/API/lib3mf_multipropertygroup.cpp @@ -0,0 +1,160 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CMultiPropertyGroup + +*/ + +#include "lib3mf_multipropertygroup.hpp" +#include "lib3mf_interfaceexception.hpp" + +// Include custom headers here. + + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CMultiPropertyGroup +**************************************************************************************************************************/ + +CMultiPropertyGroup::CMultiPropertyGroup(NMR::PModelMultiPropertyGroupResource pResource) + : CResource(std::static_pointer_cast(pResource)) +{ + +} + + +NMR::CModelMultiPropertyGroupResource& CMultiPropertyGroup::multiPropertyGroup() +{ + NMR::CModelMultiPropertyGroupResource* pMultiPropertyGroup = dynamic_cast(resource().get()); + if (pMultiPropertyGroup == nullptr) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDMULTIPROPERTYGROUP); + return *pMultiPropertyGroup; +} + +Lib3MF_uint32 CMultiPropertyGroup::GetCount () +{ + return multiPropertyGroup().getCount(); +} + +void CMultiPropertyGroup::GetAllPropertyIDs (Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer) +{ + Lib3MF_uint32 nMultiMaterialCount = multiPropertyGroup().getCount(); + + if (pPropertyIDsNeededCount) + *pPropertyIDsNeededCount = nMultiMaterialCount; + + if (nPropertyIDsBufferSize >= nMultiMaterialCount && pPropertyIDsBuffer) { + if (!multiPropertyGroup().hasResourceIndexMap()) { + multiPropertyGroup().buildResourceIndexMap(); + } + for (Lib3MF_uint32 i = 0; i < nMultiMaterialCount; i++) { + DWORD nPropertyID; + if (multiPropertyGroup().mapResourceIndexToPropertyID(i, nPropertyID)) { + *pPropertyIDsBuffer = nPropertyID; + } + else { + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDRESOURCEINDEX); + } + pPropertyIDsBuffer++; + } + } +} + +Lib3MF_uint32 CMultiPropertyGroup::AddMultiProperty (const Lib3MF_uint64 nPropertyIDsBufferSize, const Lib3MF_uint32 * pPropertyIDsBuffer) +{ + if (nPropertyIDsBufferSize > LIB3MF_MAXMULTIPROPERTIES) + throw ELib3MFInterfaceException(LIB3MF_ERROR_ELEMENTCOUNTEXCEEDSLIMIT); + + NMR::PModelMultiProperty multiProperty = std::make_shared(); + multiProperty->resize((size_t)nPropertyIDsBufferSize); + for (size_t i = 0; i < (size_t) nPropertyIDsBufferSize; i++) { + (*multiProperty)[i] = pPropertyIDsBuffer[i]; + } + return multiPropertyGroup().addMultiProperty(multiProperty); +} + +void CMultiPropertyGroup::SetMultiProperty (const Lib3MF_uint32 nPropertyID, const Lib3MF_uint64 nPropertyIDsBufferSize, const Lib3MF_uint32 * pPropertyIDsBuffer) +{ + if (nPropertyIDsBufferSize > LIB3MF_MAXMULTIPROPERTIES) + throw ELib3MFInterfaceException(LIB3MF_ERROR_ELEMENTCOUNTEXCEEDSLIMIT); + + NMR::PModelMultiProperty multiProperty = std::make_shared(); + multiProperty->resize((size_t)nPropertyIDsBufferSize); + for (size_t i = 0; i < (size_t)nPropertyIDsBufferSize; i++) { + (*multiProperty)[i] = pPropertyIDsBuffer[i]; + } + multiPropertyGroup().setMultiProperty(nPropertyID, multiProperty); +} + +void CMultiPropertyGroup::GetMultiProperty (const Lib3MF_uint32 nPropertyID, Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer) +{ + NMR::PModelMultiProperty multiProperty = multiPropertyGroup().getMultiProperty(nPropertyID); + + if (pPropertyIDsNeededCount) { + *pPropertyIDsNeededCount = multiProperty->size(); + } + + if (pPropertyIDsBuffer && nPropertyIDsBufferSize >= multiProperty->size()) { + + if (nPropertyIDsBufferSize > LIB3MF_MAXMULTIPROPERTIES) + throw ELib3MFInterfaceException(LIB3MF_ERROR_ELEMENTCOUNTEXCEEDSLIMIT); + + for (size_t i = 0; i < (size_t)nPropertyIDsBufferSize; i++) { + pPropertyIDsBuffer[i] = (*multiProperty)[i]; + } + } +} + +void CMultiPropertyGroup::RemoveMultiProperty (const Lib3MF_uint32 nPropertyID) +{ + multiPropertyGroup().removeMultiProperty(nPropertyID); +} + +Lib3MF_uint32 CMultiPropertyGroup::GetLayerCount () +{ + return multiPropertyGroup().getLayerCount(); +} + +Lib3MF_uint32 CMultiPropertyGroup::AddLayer (const sLib3MFMultiPropertyLayer TheLayer) +{ + return multiPropertyGroup().addLayer(NMR::MODELMULTIPROPERTYLAYER{ TheLayer.m_ResourceID, NMR::eModelBlendMethod(TheLayer.m_TheBlendMethod)}); +} + +sLib3MFMultiPropertyLayer CMultiPropertyGroup::GetLayer (const Lib3MF_uint32 nLayerIndex) +{ + NMR::MODELMULTIPROPERTYLAYER sLayer = multiPropertyGroup().getLayer(nLayerIndex); + sLib3MFMultiPropertyLayer outLayer; + outLayer.m_ResourceID = sLayer.m_nUniqueResourceID; + outLayer.m_TheBlendMethod = (eLib3MFBlendMethod)sLayer.m_nMethod; + return outLayer; +} + +void CMultiPropertyGroup::RemoveLayer (const Lib3MF_uint32 nLayerIndex) +{ + multiPropertyGroup().removeLayer(nLayerIndex); +} + diff --git a/Source/API/lib3mf_multipropertygroupiterator.cpp b/Source/API/lib3mf_multipropertygroupiterator.cpp new file mode 100644 index 0000000..a66ce81 --- /dev/null +++ b/Source/API/lib3mf_multipropertygroupiterator.cpp @@ -0,0 +1,47 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CMultiPropertyGroupIterator + +*/ + +#include "lib3mf_multipropertygroupiterator.hpp" +#include "lib3mf_interfaceexception.hpp" + +// Include custom headers here. +#include "lib3mf_multipropertygroup.hpp" + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CMultiPropertyGroupIterator +**************************************************************************************************************************/ + +IMultiPropertyGroup * CMultiPropertyGroupIterator::GetCurrentMultiPropertyGroup () +{ + return new CMultiPropertyGroup(std::dynamic_pointer_cast(GetCurrentResource())); +} + diff --git a/Source/API/lib3mf_object.cpp b/Source/API/lib3mf_object.cpp new file mode 100644 index 0000000..aa87cec --- /dev/null +++ b/Source/API/lib3mf_object.cpp @@ -0,0 +1,256 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CObject + +*/ + +#include "lib3mf_object.hpp" +#include "lib3mf_interfaceexception.hpp" + +#include "lib3mf_meshobject.hpp" +#include "lib3mf_componentsobject.hpp" +#include "lib3mf_metadatagroup.hpp" +#include "lib3mf_slicestack.hpp" +#include "lib3mf_attachment.hpp" + +// Include custom headers here. +#include "Model/Classes/NMR_ModelMeshObject.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CObject +**************************************************************************************************************************/ + +NMR::CModelObject* CObject::object() +{ + NMR::CModelObject* pObject = dynamic_cast(resource().get()); + if (pObject == nullptr) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDOBJECT); + return pObject; +} + +IObject* CObject::fnCreateObjectFromModelResource(NMR::PModelResource pResource, bool bFailIfUnkownClass) { + + if (!pResource.get()) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + + NMR::CModelMeshObject * pMeshObject = dynamic_cast (pResource.get()); + if (pMeshObject) { + return new CMeshObject(pResource); + } + + NMR::CModelComponentsObject * pComponentsResource = dynamic_cast (pResource.get()); + if (pComponentsResource) { + return new CComponentsObject(pResource); + } + + if (bFailIfUnkownClass) + throw ELib3MFInterfaceException(NMR_ERROR_UNKNOWNMODELRESOURCE); + + return nullptr; +} + +CObject::CObject(NMR::PModelResource pResource) + :CResource(pResource) +{ +} + + +eLib3MFObjectType CObject::GetType () +{ + return eLib3MFObjectType(object()->getObjectType()); +} + +void CObject::SetType (const eLib3MFObjectType eObjectType) +{ + object()->setObjectType(NMR::eModelObjectType(eObjectType)); +} + +std::string CObject::GetName () +{ + return object()->getName(); +} + +void CObject::SetName (const std::string & sName) +{ + object()->setName(sName); +} + +std::string CObject::GetPartNumber () +{ + return object()->getPartNumber(); +} + +void CObject::SetPartNumber (const std::string & sPartNumber) +{ + object()->setPartNumber(sPartNumber); +} + +bool CObject::IsMeshObject () +{ + // overwritten by child class + throw ELib3MFInterfaceException(LIB3MF_ERROR_SHOULDNOTBECALLED); +} + +bool CObject::IsComponentsObject () +{ + // overwritten by child class + throw ELib3MFInterfaceException(LIB3MF_ERROR_SHOULDNOTBECALLED); +} + +IMeshObject * CObject::AsMeshObject() +{ + if (dynamic_cast(resource().get())) + { + return new CMeshObject(resource()); + } + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); +} + +IComponentsObject * CObject::AsComponentsObject() +{ + if (dynamic_cast(resource().get())) + { + return new CComponentsObject(resource()); + } + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); +} + +bool CObject::IsValid () +{ + // Implemented by base class + throw ELib3MFInterfaceException (LIB3MF_ERROR_SHOULDNOTBECALLED); +} + +void CObject::SetAttachmentAsThumbnail(IAttachment* pAttachment) +{ + auto pModelAttachment = object()->getModel()->findModelAttachment(pAttachment->GetPath()); + if (!pModelAttachment) { + throw ELib3MFInterfaceException(LIB3MF_ERROR_ATTACHMENTNOTFOUND); + } + object()->setThumbnailAttachment(pModelAttachment, true); +} + +IAttachment * CObject::GetThumbnailAttachment() +{ + if (object()->getThumbnailAttachment()) { + return new CAttachment(object()->getThumbnailAttachment()); + } + return nullptr; +} + +void CObject::ClearThumbnailAttachment() +{ + object()->clearThumbnailAttachment(); +} + + +IMetaDataGroup * CObject::GetMetaDataGroup () +{ + return new CMetaDataGroup(object()->metaDataGroup()); +} + +std::string CObject::GetUUID(bool & bHasUUID) +{ + NMR::PUUID pUUID = object()->uuid(); + bHasUUID = (pUUID.get() != nullptr); + if (bHasUUID) + return pUUID->toString(); + else + return ""; +} + +void CObject::SetUUID(const std::string & sUUID) +{ + NMR::PUUID pUUID = std::make_shared(sUUID); + object()->setUUID(pUUID); +} + +void CObject::SetSlicesMeshResolution(const eLib3MFSlicesMeshResolution eMeshResolution) +{ + object()->setSlicesMeshResolution(NMR::eModelSlicesMeshResolution(eMeshResolution)); +} + +eLib3MFSlicesMeshResolution CObject::GetSlicesMeshResolution() +{ + return eLib3MFSlicesMeshResolution(object()->slicesMeshResolution()); +} + +bool CObject::HasSlices(const bool bRecursive) +{ + return object()->hasSlices(bRecursive); +} + +void CObject::ClearSliceStack() +{ + object()->assignSliceStack(nullptr); +} + +ISliceStack * CObject::GetSliceStack() +{ + NMR::PModelSliceStack pSliceStackResource = object()->getSliceStack(); + if (pSliceStackResource) + return new CSliceStack(pSliceStackResource); + else + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDSLICESTACKRESOURCE); +} + +void CObject::AssignSliceStack(ISliceStack* pSliceStackInstance) +{ + NMR::ModelResourceID nID = pSliceStackInstance->GetResourceID(); + std::shared_ptr pPackagePart(pSliceStackInstance->PackagePart()); + std::string sPath = pPackagePart->GetPath(); + + NMR::PModelSliceStack pSliceStackResource = std::dynamic_pointer_cast + ( object()->getModel()->findResource(sPath, nID) ); + if (!pSliceStackResource) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDSLICESTACKRESOURCE); + + object()->assignSliceStack(pSliceStackResource); +} + +Lib3MF::sBox CObject::GetOutbox() +{ + NMR::NOUTBOX3 oOutbox; + NMR::fnOutboxInitialize(oOutbox); + + object()->extendOutbox(oOutbox, NMR::fnMATRIX3_identity()); + + sBox s; + s.m_MinCoordinate[0] = oOutbox.m_min.m_fields[0]; + s.m_MinCoordinate[1] = oOutbox.m_min.m_fields[1]; + s.m_MinCoordinate[2] = oOutbox.m_min.m_fields[2]; + + s.m_MaxCoordinate[0] = oOutbox.m_max.m_fields[0]; + s.m_MaxCoordinate[1] = oOutbox.m_max.m_fields[1]; + s.m_MaxCoordinate[2] = oOutbox.m_max.m_fields[2]; + + return s; +} + diff --git a/Source/API/lib3mf_objectiterator.cpp b/Source/API/lib3mf_objectiterator.cpp new file mode 100644 index 0000000..1274a41 --- /dev/null +++ b/Source/API/lib3mf_objectiterator.cpp @@ -0,0 +1,47 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CObjectIterator + +*/ + +#include "lib3mf_objectiterator.hpp" +#include "lib3mf_interfaceexception.hpp" + +// Include custom headers here. +#include "lib3mf_object.hpp" + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CObjectIterator +**************************************************************************************************************************/ + +IObject * CObjectIterator::GetCurrentObject () +{ + return CObject::fnCreateObjectFromModelResource(GetCurrentResource(), true); +} + diff --git a/Source/API/lib3mf_packagepart.cpp b/Source/API/lib3mf_packagepart.cpp new file mode 100644 index 0000000..e07cef8 --- /dev/null +++ b/Source/API/lib3mf_packagepart.cpp @@ -0,0 +1,61 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CPackagePart + +*/ + +#include "lib3mf_packagepart.hpp" +#include "lib3mf_interfaceexception.hpp" + +// Include custom headers here. + +#include "Model/Classes/NMR_PackageResourceID.h" + + + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CPackagePart +**************************************************************************************************************************/ + +CPackagePart::CPackagePart(NMR::PPackageModelPath pPath) + : m_pPath(pPath) +{ + if (!pPath.get()) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); +} + +std::string CPackagePart::GetPath() +{ + return m_pPath->getPath(); +} + +void CPackagePart::SetPath(const std::string & sPath) +{ + m_pPath->setPath(sPath); +} diff --git a/Source/API/lib3mf_reader.cpp b/Source/API/lib3mf_reader.cpp new file mode 100644 index 0000000..9754233 --- /dev/null +++ b/Source/API/lib3mf_reader.cpp @@ -0,0 +1,230 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CReader + +*/ + +#include "lib3mf_reader.hpp" + +// Include custom headers here. +#include "lib3mf_interfaceexception.hpp" +#include "lib3mf_accessright.hpp" +#include "lib3mf_contentencryptionparams.hpp" +#include "Common/Platform/NMR_Platform.h" +#include "Common/Platform/NMR_ImportStream_Shared_Memory.h" +#include "Common/Platform/NMR_ImportStream_Callback.h" +#include "Common/NMR_SecureContentTypes.h" +#include "Common/NMR_SecureContext.h" +#include "Model/Classes/NMR_KeyStore.h" + + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CReader +**************************************************************************************************************************/ + +CReader::CReader(std::string sReaderClass, NMR::PModel model) +{ + m_pReader = nullptr; + + // Create specified writer instance + if (sReaderClass.compare("3mf") == 0) { + m_pReader = std::make_shared(model); + + } + else if (sReaderClass.compare("stl") == 0) { + m_pReader = std::make_shared(model); + } + + if (!m_pReader) + throw ELib3MFInterfaceException(LIB3MF_ERROR_READERCLASSUNKNOWN); +} + +NMR::CModelReader& CReader::reader() +{ + return *m_pReader; +} + +void CReader::ReadFromFile (const std::string & sFilename) +{ + NMR::PImportStream pImportStream = NMR::fnCreateImportStreamInstance(sFilename.c_str()); + + try { + reader().readStream(pImportStream); + } + catch (NMR::CNMRException&e) { + if (e.getErrorCode() == NMR_USERABORTED) { + throw ELib3MFInterfaceException(LIB3MF_ERROR_CALCULATIONABORTED); + } + else throw e; + } +} + +void CReader::ReadFromBuffer (const Lib3MF_uint64 nBufferBufferSize, const Lib3MF_uint8 * pBufferBuffer) +{ + NMR::PImportStream pImportStream = std::make_shared(pBufferBuffer, nBufferBufferSize); + + try { + reader().readStream(pImportStream); + } + catch (NMR::CNMRException&e) { + if (e.getErrorCode() == NMR_USERABORTED) { + throw ELib3MFInterfaceException(LIB3MF_ERROR_CALCULATIONABORTED); + } + else throw e; + } +} + +void CReader::ReadFromCallback(const Lib3MFReadCallback pTheReadCallback, const Lib3MF_uint64 nStreamSize, const Lib3MFSeekCallback pTheSeekCallback, const Lib3MF_pvoid pUserData) +{ + + NMR::ImportStream_ReadCallbackType lambdaReadCallback = + [pTheReadCallback](NMR::nfByte* pData, NMR::nfUint64 cbBytes, void* pUserData) + { + (*pTheReadCallback)(reinterpret_cast(pData), cbBytes, pUserData); + return 0; + }; + + NMR::ImportStream_SeekCallbackType lambdaSeekCallback = + [pTheSeekCallback](NMR::nfUint64 nPosition, void* pUserData) + { + (*pTheSeekCallback)(nPosition, pUserData); + return 0; + }; + + NMR::PImportStream pImportStream = std::make_shared( + lambdaReadCallback, lambdaSeekCallback, + pUserData, nStreamSize); + try { + reader().readStream(pImportStream); + } + catch (NMR::CNMRException&e) { + if (e.getErrorCode() == NMR_USERABORTED) { + throw ELib3MFInterfaceException(LIB3MF_ERROR_CALCULATIONABORTED); + } + else throw e; + } +} + +void CReader::SetProgressCallback(const Lib3MFProgressCallback pProgressCallback, const Lib3MF_pvoid pUserData) +{ + NMR::Lib3MFProgressCallback lambdaCallback = + [pProgressCallback](int progressStep, NMR::ProgressIdentifier identifier, void* pUserData) + { + bool ret; + (*pProgressCallback)(&ret, progressStep / 100.0f, eLib3MFProgressIdentifier(identifier), pUserData); + return ret; + }; + m_pReader->SetProgressCallback(lambdaCallback, pUserData); +} + +void CReader::AddRelationToRead (const std::string & sRelationShipType) +{ + reader().addRelationToRead(sRelationShipType); +} + +void CReader::RemoveRelationToRead (const std::string & sRelationShipType) +{ + reader().removeRelationToRead(sRelationShipType); +} + +void CReader::SetStrictModeActive (const bool bStrictModeActive) +{ + if (bStrictModeActive) + reader().warnings()->setCriticalWarningLevel(NMR::mrwInvalidOptionalValue); + else + reader().warnings()->setCriticalWarningLevel(NMR::mrwFatal); +} + +bool CReader::GetStrictModeActive () +{ + return reader().warnings()->getCriticalWarningLevel() == NMR::mrwInvalidOptionalValue; +} + +std::string CReader::GetWarning (const Lib3MF_uint32 nIndex, Lib3MF_uint32 & nErrorCode) +{ + auto warning = reader().warnings()->getWarning(nIndex); + nErrorCode = warning->getErrorCode(); + return warning->getMessage(); +} + +Lib3MF_uint32 CReader::GetWarningCount () +{ + return reader().warnings()->getWarningCount(); +} + +void Lib3MF::Impl::CReader::AddKeyWrappingCallback(const std::string &sConsumerID, const Lib3MF::KeyWrappingCallback pTheCallback, const Lib3MF_pvoid pUserData) { + NMR::KeyWrappingDescriptor descriptor; + descriptor.m_sKekDecryptData.m_pUserData = pUserData; + descriptor.m_fnWrap = + [this, pTheCallback]( + std::vector const & cipher, + std::vector & plain, + NMR::KeyWrappingContext & ctx) { + + std::shared_ptr pAccessRight = std::make_shared(ctx.m_pAccessRight); + IBase * pBaseEntity(nullptr); + pBaseEntity = pAccessRight.get(); + Lib3MF_AccessRight entityHandle = pBaseEntity; + + //figure out the size of the key. + Lib3MF_uint64 needed = 0; + Lib3MF_uint64 result = 0; + (*pTheCallback)(entityHandle, cipher.size(), cipher.data(), + 0, &needed, nullptr, ctx.m_pUserData, &result); + if (result == 0) + throw ELib3MFInterfaceException(LIB3MF_ERROR_CALCULATIONABORTED); + + plain.resize(needed, 0); + + result = 0; + (*pTheCallback)(entityHandle, cipher.size(), cipher.data(), + plain.size(), nullptr, plain.data(), ctx.m_pUserData, &result); + if (result == 0) + throw ELib3MFInterfaceException(LIB3MF_ERROR_CALCULATIONABORTED); + return (NMR::nfUint64)result; + }; + reader().secureContext()->addKekCtx(sConsumerID, descriptor); +} +void Lib3MF::Impl::CReader::SetContentEncryptionCallback(const Lib3MF::ContentEncryptionCallback pTheCallback, const Lib3MF_pvoid pUserData) { + NMR::ContentEncryptionDescriptor descriptor; + descriptor.m_sDekDecryptData.m_pUserData = pUserData; + descriptor.m_fnCrypt = [this, pTheCallback](NMR::nfUint64 size, NMR::nfByte const * cipher, NMR::nfByte * plain, NMR::ContentEncryptionContext & ctx) { + std::shared_ptr pCekParams = std::make_shared(ctx.m_sParams); + IBase * pBaseEntity(nullptr); + pBaseEntity = pCekParams.get(); + Lib3MF_ContentEncryptionParams entityHandle = pBaseEntity; + Lib3MF_uint64 result = 0; + (*pTheCallback)(entityHandle, (Lib3MF_uint64)size, cipher, (Lib3MF_uint64)size, nullptr, plain, ctx.m_pUserData, &result); + if (result == 0) + throw ELib3MFInterfaceException(LIB3MF_ERROR_CALCULATIONABORTED); + return (NMR::nfUint64)result; + }; + reader().secureContext()->setDekCtx(descriptor); +} + diff --git a/Source/API/lib3mf_resource.cpp b/Source/API/lib3mf_resource.cpp new file mode 100644 index 0000000..d06de18 --- /dev/null +++ b/Source/API/lib3mf_resource.cpp @@ -0,0 +1,105 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CResource + +*/ + +#include "lib3mf_resource.hpp" +#include "lib3mf_interfaceexception.hpp" + +// Include custom headers here. +#include "lib3mf_packagepart.hpp" +#include "Model/Classes/NMR_ModelObject.h" +#include "lib3mf_object.hpp" +#include + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CResource +**************************************************************************************************************************/ + + +NMR::PModelResource CResource::resource() +{ + if (m_pResource.get()==nullptr) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDOBJECT); + + return m_pResource; +} + +CResource::CResource(NMR::PModelResource pResource) +{ + if (pResource.get() == nullptr) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDMODELRESOURCE); + m_pResource = pResource; +} + +Lib3MF_uint32 CResource::GetResourceID() +{ + return m_pResource->getPackageResourceID()->getUniqueID(); +} + +Lib3MF_uint32 CResource::GetUniqueResourceID() +{ + return m_pResource->getPackageResourceID()->getUniqueID(); +} + +Lib3MF_uint32 CResource::GetModelResourceID() +{ + return m_pResource->getPackageResourceID()->getModelResourceID(); +} + +IObject * CResource::AsObject() +{ + if (dynamic_cast(m_pResource.get())) + { + return new CObject(m_pResource); + } + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); +} + +IPackagePart * CResource::PackagePart() +{ + return new CPackagePart(m_pResource->getPackageResourceID()->getPackageModelPath()); +} + +void CResource::SetPackagePart(IPackagePart* pPackagePart) +{ + std::string sPath = pPackagePart->GetPath(); + NMR::ModelResourceID nID = m_pResource->getPackageResourceID()->getModelResourceID(); + NMR::PPackageResourceID pTargetPackageResourceID = m_pResource->getModel()->findPackageResourceID(sPath, nID); + if (pTargetPackageResourceID) { + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDMODELRESOURCE); + } + NMR::PPackageResourceID pIDOld = m_pResource->getPackageResourceID(); + NMR::PPackageResourceID pID = m_pResource->getModel()->generatePackageResourceID(sPath, nID); + m_pResource->setPackageResourceID(pID); + + m_pResource->getModel()->removePackageResourceID(pIDOld); +} + diff --git a/Source/API/lib3mf_resourcedata.cpp b/Source/API/lib3mf_resourcedata.cpp new file mode 100644 index 0000000..00ffd54 --- /dev/null +++ b/Source/API/lib3mf_resourcedata.cpp @@ -0,0 +1,38 @@ +#include "lib3mf_resourcedata.hpp" +#include "lib3mf_interfaceexception.hpp" +#include "lib3mf_consumer.hpp" +#include "lib3mf_packagepart.hpp" +#include "lib3mf_utils.hpp" + +namespace Lib3MF { + namespace Impl { + Lib3MF::Impl::CResourceData::CResourceData(NMR::PKeyStoreResourceData resourceData) + :m_pResourceData(resourceData) + { + if (!resourceData) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + } + + Lib3MF::eEncryptionAlgorithm Lib3MF::Impl::CResourceData::GetEncryptionAlgorithm() { + NMR::eKeyStoreEncryptAlgorithm ea = m_pResourceData->getEncryptionAlgorithm(); + return static_cast(ea); + } + + Lib3MF::eCompression Lib3MF::Impl::CResourceData::GetCompression() { + return translateCompression(m_pResourceData->isCompressed()); + } + + IPackagePart * CResourceData::GetPath() { + return new CPackagePart(m_pResourceData->packagePath()); + } + + void CResourceData::GetAdditionalAuthenticationData(Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64 * pByteDataNeededCount, Lib3MF_uint8 * pByteDataBuffer) { + std::vector const & aad = m_pResourceData->getAddAuthData(); + if (nByteDataBufferSize < aad.size()) { + *pByteDataNeededCount = aad.size(); + } else { + std::copy(aad.begin(), aad.end(), pByteDataBuffer); + } + } + } +} \ No newline at end of file diff --git a/Source/API/lib3mf_resourcedatagroup.cpp b/Source/API/lib3mf_resourcedatagroup.cpp new file mode 100644 index 0000000..e26f4ee --- /dev/null +++ b/Source/API/lib3mf_resourcedatagroup.cpp @@ -0,0 +1,47 @@ + + +#include "lib3mf_resourcedatagroup.hpp" +#include "lib3mf_interfaceexception.hpp" + +#include "lib3mf_consumer.hpp" +#include "lib3mf_accessright.hpp" + +#include "Model/Classes/NMR_KeyStoreFactory.h" +namespace Lib3MF { + namespace Impl { + CResourceDataGroup::CResourceDataGroup(NMR::PKeyStoreResourceDataGroup const & dg) + : m_pDataGroup(dg) + { + if (!dg) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + } + + IAccessRight * CResourceDataGroup::AddAccessRight(IConsumer * pConsumer, const Lib3MF::eWrappingAlgorithm eWrappingAlgorithm, const Lib3MF::eMgfAlgorithm eMgfAlgorithm, const Lib3MF::eDigestMethod eDigestMethod) { + CConsumer * c = dynamic_cast(pConsumer); + if (nullptr == c) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + NMR::PKeyStoreAccessRight ar = NMR::CKeyStoreFactory::makeAccessRight( + c->consumer(), + (NMR::eKeyStoreWrapAlgorithm)eWrappingAlgorithm, + (NMR::eKeyStoreMaskGenerationFunction)eMgfAlgorithm, + (NMR::eKeyStoreMessageDigest)eDigestMethod); + m_pDataGroup->addAccessRight(ar); + return new CAccessRight(ar); + } + + IAccessRight * CResourceDataGroup::FindAccessRightByConsumer(IConsumer * pConsumerInstance) { + NMR::PKeyStoreAccessRight ar = m_pDataGroup->findAccessRightByConsumerID(pConsumerInstance->GetConsumerID()); + if (!ar) + return nullptr; + return new CAccessRight(ar); + } + + void CResourceDataGroup::RemoveAccessRight(IConsumer * pConsumerInstance) { + m_pDataGroup->removeAccessRight(pConsumerInstance->GetConsumerID()); + } + + std::string CResourceDataGroup::GetKeyUUID() { + return m_pDataGroup->getKeyUUID()->toString(); + } + } +} \ No newline at end of file diff --git a/Source/API/lib3mf_resourceiterator.cpp b/Source/API/lib3mf_resourceiterator.cpp new file mode 100644 index 0000000..4a913e6 --- /dev/null +++ b/Source/API/lib3mf_resourceiterator.cpp @@ -0,0 +1,118 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CResourceIterator + +*/ + +#include "lib3mf_resource.hpp" +#include "lib3mf_resourceiterator.hpp" +#include "lib3mf_interfaceexception.hpp" + +// Include custom headers here. + + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CResourceIterator +**************************************************************************************************************************/ + +CResourceIterator::CResourceIterator() +{ + m_nCurrentIndex = -1; +} + +void CResourceIterator::addResource(NMR::PModelResource pResource) +{ + if (pResource.get() == nullptr) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + + m_pResources.push_back(pResource); +} + +bool CResourceIterator::MoveNext () +{ + // Get Resource Count + Lib3MF_int32 nBuildItemCount = (Lib3MF_int32)m_pResources.size(); + m_nCurrentIndex++; + + // Check new Index + if (m_nCurrentIndex >= nBuildItemCount) { + m_nCurrentIndex = nBuildItemCount; + return false; + } + else { + return true; + } +} + +bool CResourceIterator::MovePrevious () +{ + // Get Resource Count + m_nCurrentIndex--; + + // Check new Index + if (m_nCurrentIndex <= -1) { + m_nCurrentIndex = -1; + return false; + } + else { + return true; + } +} + +NMR::PModelResource CResourceIterator::GetCurrentResource() +{ + // Get Resource Count + Lib3MF_int32 nBuildItemCount = (Lib3MF_int32)m_pResources.size(); + if ((m_nCurrentIndex < 0) || (m_nCurrentIndex >= nBuildItemCount)) + throw ELib3MFInterfaceException(LIB3MF_ERROR_ITERATORINVALIDINDEX); + + return m_pResources[m_nCurrentIndex]; +} + +IResource * CResourceIterator::GetCurrent () +{ + // Create specific API class + return new CResource(GetCurrentResource()); +} + +IResourceIterator * CResourceIterator::Clone () +{ + auto pResources = std::unique_ptr(new CResourceIterator()); + + for (auto iIterator = m_pResources.begin(); iIterator != m_pResources.end(); iIterator++) + pResources->addResource(*iIterator); + + return pResources.release(); +} + +Lib3MF_uint64 CResourceIterator::Count() +{ + return m_pResources.size(); +} + diff --git a/Source/API/lib3mf_slice.cpp b/Source/API/lib3mf_slice.cpp new file mode 100644 index 0000000..194b67b --- /dev/null +++ b/Source/API/lib3mf_slice.cpp @@ -0,0 +1,124 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CSlice + +*/ + +#include "lib3mf_slice.hpp" +#include "lib3mf_interfaceexception.hpp" + +// Include custom headers here. + + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CSlice +**************************************************************************************************************************/ + +CSlice::CSlice(NMR::PSlice pSlice) + :m_pSlice(pSlice) +{ + +} + +void CSlice::SetVertices (const Lib3MF_uint64 nVerticesBufferSize, const sLib3MFPosition2D * pVerticesBuffer) +{ + m_pSlice->Clear(); + for (Lib3MF_uint64 index = 0; index < nVerticesBufferSize; index++) { + m_pSlice->addVertex(pVerticesBuffer->m_Coordinates[0], pVerticesBuffer->m_Coordinates[1]); + pVerticesBuffer++; + } +} + +void CSlice::GetVertices (Lib3MF_uint64 nVerticesBufferSize, Lib3MF_uint64* pVerticesNeededCount, sLib3MFPosition2D * pVerticesBuffer) +{ + Lib3MF_uint64 vertexCount = m_pSlice->getVertexCount(); + if (pVerticesNeededCount) + *pVerticesNeededCount = vertexCount; + + if (nVerticesBufferSize >= vertexCount && pVerticesBuffer) + { + for (Lib3MF_uint32 i = 0; i < vertexCount; i++) + { + const NMR::SLICENODE* node = m_pSlice->getNode(i); + pVerticesBuffer[i].m_Coordinates[0] = node->m_position.m_fields[0]; + pVerticesBuffer[i].m_Coordinates[1] = node->m_position.m_fields[1]; + } + } +} + +Lib3MF_uint64 CSlice::GetVertexCount () +{ + return m_pSlice->getVertexCount(); +} + +Lib3MF_uint64 CSlice::AddPolygon(const Lib3MF_uint64 nIndicesBufferSize, const Lib3MF_uint32 * pIndicesBuffer) +{ + Lib3MF_uint32 index = m_pSlice->beginPolygon(); + SetPolygonIndices(index, nIndicesBufferSize, pIndicesBuffer); + return index; +} + +Lib3MF_uint64 CSlice::GetPolygonCount () +{ + return m_pSlice->getPolygonCount(); +} + +void CSlice::SetPolygonIndices (const Lib3MF_uint64 nIndex, const Lib3MF_uint64 nIndicesBufferSize, const Lib3MF_uint32 * pIndicesBuffer) +{ + m_pSlice->clearPolygon(NMR::nfUint32(nIndex)); + + for (Lib3MF_uint64 i=0; i< nIndicesBufferSize; i++) + m_pSlice->addPolygonIndex(NMR::nfUint32(nIndex), pIndicesBuffer[i]); +} + +void CSlice::GetPolygonIndices (const Lib3MF_uint64 nIndex, Lib3MF_uint64 nIndicesBufferSize, Lib3MF_uint64* pIndicesNeededCount, Lib3MF_uint32 * pIndicesBuffer) +{ + Lib3MF_uint64 indexCount = m_pSlice->getPolygonIndexCount(NMR::nfUint32(nIndex)); + if (pIndicesNeededCount) + *pIndicesNeededCount = indexCount; + + if (nIndicesBufferSize >= indexCount && pIndicesBuffer) + { + for (Lib3MF_uint32 i = 0; i < indexCount; i++) + { + pIndicesBuffer[i] = m_pSlice->getPolygonIndex(NMR::nfUint32(nIndex), i); + } + } + +} + +Lib3MF_uint64 CSlice::GetPolygonIndexCount (const Lib3MF_uint64 nIndex) +{ + return m_pSlice->getPolygonIndexCount(NMR::nfUint32(nIndex)); +} + +double CSlice::GetZTop() +{ + return m_pSlice->getTopZ(); +} diff --git a/Source/API/lib3mf_slicestack.cpp b/Source/API/lib3mf_slicestack.cpp new file mode 100644 index 0000000..2e2cec2 --- /dev/null +++ b/Source/API/lib3mf_slicestack.cpp @@ -0,0 +1,116 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CSliceStack + +*/ + +#include "lib3mf_slicestack.hpp" +#include "lib3mf_interfaceexception.hpp" + +#include "lib3mf_slice.hpp" +// Include custom headers here. + + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CSliceStack +**************************************************************************************************************************/ + +CSliceStack::CSliceStack(NMR::PModelSliceStack pSliceStack): + CResource(pSliceStack) +{ +} + +NMR::PModelSliceStack CSliceStack::sliceStack() +{ + return std::dynamic_pointer_cast(resource()); +} + +double CSliceStack::GetBottomZ() +{ + return sliceStack()->getZBottom(); +} + +Lib3MF_uint64 CSliceStack::GetSliceCount () +{ + return sliceStack()->getSliceCount(); +} + +ISlice * CSliceStack::GetSlice (const Lib3MF_uint64 nSliceIndex) +{ + NMR::PSlice pSlice = sliceStack()->getSlice(Lib3MF_uint32(nSliceIndex)); + return new CSlice(pSlice); +} + +ISlice * CSliceStack::AddSlice (const double fZTop) +{ + NMR::PSlice pSlice = sliceStack()->AddSlice(fZTop); + return new CSlice(pSlice); +} + +Lib3MF_uint64 CSliceStack::GetSliceRefCount() +{ + return sliceStack()->getSliceRefCount(); +} + +void CSliceStack::AddSliceStackReference(ISliceStack* pTheSliceStack) +{ + NMR::ModelResourceID nID = pTheSliceStack->GetResourceID(); + + std::shared_ptr pPackagePart(pTheSliceStack->PackagePart()); + std::string sPath = pPackagePart->GetPath(); + + NMR::PModelResource pResource = sliceStack()->getModel()->findResource(sPath, nID); + NMR::PModelSliceStack pModelSliceStack = std::dynamic_pointer_cast(pResource); + if (!pModelSliceStack) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDSLICESTACKRESOURCE); + + sliceStack()->AddSliceRef(pModelSliceStack); +} + +ISliceStack * CSliceStack::GetSliceStackReference(const Lib3MF_uint64 nSliceRefIndex) +{ + NMR::PModelSliceStack pModelSliceStack = sliceStack()->getSliceRef(Lib3MF_uint32(nSliceRefIndex)); + return new CSliceStack(pModelSliceStack); +} + +void CSliceStack::CollapseSliceReferences() +{ + sliceStack()->CollapseSliceReferences(); +} + +void CSliceStack::SetOwnPath(const std::string & sPath) +{ + sliceStack()->SetOwnPath(sPath); +} + +std::string CSliceStack::GetOwnPath() +{ + return sliceStack()->OwnPath(); +} + diff --git a/Source/API/lib3mf_slicestackiterator.cpp b/Source/API/lib3mf_slicestackiterator.cpp new file mode 100644 index 0000000..77ac6c3 --- /dev/null +++ b/Source/API/lib3mf_slicestackiterator.cpp @@ -0,0 +1,46 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CSliceStackIterator + +*/ + +#include "lib3mf_slicestackiterator.hpp" +#include "lib3mf_interfaceexception.hpp" + +// Include custom headers here. +#include "lib3mf_slicestack.hpp" + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CSliceStackIterator +**************************************************************************************************************************/ + +ISliceStack * CSliceStackIterator::GetCurrentSliceStack () +{ + return new CSliceStack(std::dynamic_pointer_cast(GetCurrentResource())); +} diff --git a/Source/API/lib3mf_texture2d.cpp b/Source/API/lib3mf_texture2d.cpp new file mode 100644 index 0000000..8f7741e --- /dev/null +++ b/Source/API/lib3mf_texture2d.cpp @@ -0,0 +1,101 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CTexture2D + +*/ + +#include "lib3mf_texture2d.hpp" +#include "lib3mf_interfaceexception.hpp" +#include "lib3mf_attachment.hpp" + +// Include custom headers here. + + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CTexture2D +**************************************************************************************************************************/ + + +CTexture2D::CTexture2D(NMR::PModelTexture2DResource pResource) + :CResource(pResource) +{ +} + +NMR::PModelTexture2DResource CTexture2D::texture() +{ + NMR::PModelTexture2DResource pTexture = std::dynamic_pointer_cast(resource()); + if (!pTexture) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDTEXTURERESOURCE); + return pTexture; +} + + +IAttachment * CTexture2D::GetAttachment () +{ + return new CAttachment(texture()->getAttachment()); +} + +void CTexture2D::SetAttachment (IAttachment* pAttachment) +{ + NMR::PModelAttachment attachment = texture()->getModel()->findModelAttachment(pAttachment->GetPath()); + texture()->setAttachment(attachment); +} + +eLib3MFTextureType CTexture2D::GetContentType () +{ + return (eLib3MFTextureType)(texture()->getContentType()); +} + +void CTexture2D::SetContentType (const eLib3MFTextureType eContentType) +{ + texture()->setContentType(NMR::eModelTexture2DType(eContentType)); +} + +void CTexture2D::GetTileStyleUV (eLib3MFTextureTileStyle & eTileStyleU, eLib3MFTextureTileStyle & eTileStyleV) +{ + eTileStyleU = eLib3MFTextureTileStyle(texture()->getTileStyleU()); + eTileStyleV = eLib3MFTextureTileStyle(texture()->getTileStyleV()); +} + +void CTexture2D::SetTileStyleUV (const eLib3MFTextureTileStyle eTileStyleU, const eLib3MFTextureTileStyle eTileStyleV) +{ + texture()->setTileStyleU(NMR::eModelTextureTileStyle(eTileStyleU)); + texture()->setTileStyleV(NMR::eModelTextureTileStyle(eTileStyleV)); +} + +eLib3MFTextureFilter CTexture2D::GetFilter () +{ + return eLib3MFTextureFilter(texture()->getFilter()); +} + +void CTexture2D::SetFilter (const eLib3MFTextureFilter eFilter) +{ + texture()->setFilter(NMR::eModelTextureFilter(eFilter)); +} + diff --git a/Source/API/lib3mf_texture2dgroup.cpp b/Source/API/lib3mf_texture2dgroup.cpp new file mode 100644 index 0000000..4e626f2 --- /dev/null +++ b/Source/API/lib3mf_texture2dgroup.cpp @@ -0,0 +1,106 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CTexture2DGroup + +*/ + +#include "lib3mf_texture2dgroup.hpp" +#include "lib3mf_interfaceexception.hpp" + +// Include custom headers here. +#include "lib3mf_texture2d.hpp" + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CTexture2DGroup +**************************************************************************************************************************/ + +NMR::CModelTexture2DGroupResource& CTexture2DGroup::texture2DGroup() +{ + NMR::CModelTexture2DGroupResource* pTexture2dGroup = dynamic_cast(resource().get()); + if (pTexture2dGroup == nullptr) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDTEXTURE2DGROUP); + return *pTexture2dGroup; +} + +CTexture2DGroup::CTexture2DGroup(NMR::PModelTexture2DGroupResource pResource) + : CResource(std::static_pointer_cast(pResource)) +{ + +} + +ITexture2D * CTexture2DGroup::GetTexture2D() +{ + return new CTexture2D(texture2DGroup().getTexture2D()); +} + +Lib3MF_uint32 CTexture2DGroup::GetCount () +{ + return texture2DGroup().getCount(); +} + +void CTexture2DGroup::GetAllPropertyIDs (Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer) +{ + Lib3MF_uint32 nCount = texture2DGroup().getCount(); + + if (pPropertyIDsNeededCount) + *pPropertyIDsNeededCount = nCount; + + if (nPropertyIDsBufferSize >= nCount && pPropertyIDsBuffer) { + if (!texture2DGroup().hasResourceIndexMap()) { + texture2DGroup().buildResourceIndexMap(); + } + for (Lib3MF_uint32 i = 0; i < nCount; i++) { + DWORD nPropertyID; + if (texture2DGroup().mapResourceIndexToPropertyID(i, nPropertyID)) { + *pPropertyIDsBuffer = nPropertyID; + } + else { + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDRESOURCEINDEX); + } + pPropertyIDsBuffer++; + } + } +} + +Lib3MF_uint32 CTexture2DGroup::AddTex2Coord (const sLib3MFTex2Coord UVCoordinate) +{ + return texture2DGroup().addUVCoordinate(NMR::MODELTEXTURE2DCOORDINATE({ UVCoordinate.m_U, UVCoordinate.m_V })); +} + +sLib3MFTex2Coord CTexture2DGroup::GetTex2Coord (const Lib3MF_uint32 nPropertyID) +{ + NMR::MODELTEXTURE2DCOORDINATE coord = texture2DGroup().getUVCoordinate(nPropertyID); + return sLib3MFTex2Coord({ coord.m_dU, coord.m_dV}); +} + +void CTexture2DGroup::RemoveTex2Coord(const Lib3MF_uint32 nPropertyID) +{ + texture2DGroup().removePropertyID(nPropertyID); +} + diff --git a/Source/API/lib3mf_texture2dgroupiterator.cpp b/Source/API/lib3mf_texture2dgroupiterator.cpp new file mode 100644 index 0000000..aaa3ec5 --- /dev/null +++ b/Source/API/lib3mf_texture2dgroupiterator.cpp @@ -0,0 +1,47 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CTexture2DIterator + +*/ + +#include "lib3mf_texture2dgroupiterator.hpp" +#include "lib3mf_interfaceexception.hpp" +#include "lib3mf_texture2dgroup.hpp" +// Include custom headers here. + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CTexture2DIterator +**************************************************************************************************************************/ + +ITexture2DGroup * CTexture2DGroupIterator::GetCurrentTexture2DGroup() +{ + // Create specific API class + return new CTexture2DGroup(std::dynamic_pointer_cast(GetCurrentResource())); +} + diff --git a/Source/API/lib3mf_texture2diterator.cpp b/Source/API/lib3mf_texture2diterator.cpp new file mode 100644 index 0000000..3af9bec --- /dev/null +++ b/Source/API/lib3mf_texture2diterator.cpp @@ -0,0 +1,49 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CTexture2DIterator + +*/ + +#include "lib3mf_texture2diterator.hpp" +#include "lib3mf_interfaceexception.hpp" +#include "lib3mf_texture2d.hpp" + +// Include custom headers here. + + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CTexture2DIterator +**************************************************************************************************************************/ + +ITexture2D * CTexture2DIterator::GetCurrentTexture2D () +{ + // Create specific API class + return new CTexture2D(std::dynamic_pointer_cast(GetCurrentResource())); +} + diff --git a/Source/API/lib3mf_utils.cpp b/Source/API/lib3mf_utils.cpp new file mode 100644 index 0000000..c58611b --- /dev/null +++ b/Source/API/lib3mf_utils.cpp @@ -0,0 +1,93 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This file implements utilities for the lib3mf API + +*/ + +#include "lib3mf_utils.hpp" +#include "lib3mf_interfaceexception.hpp" + +// Include custom headers here. + + +// using namespace Lib3MF::Impl; + +NMR::NMATRIX3 Lib3MF::TransformToMatrix(const sLib3MFTransform Transform) +{ + NMR::NMATRIX3 matrix; + for (int i = 0; i < 4; i++) { + for (int j = 0; j < 3; j++) + matrix.m_fields[j][i] = Transform.m_Fields[i][j]; + matrix.m_fields[3][i] = 0.f + 1.0f*(i == 3); + } + return matrix; +} + +sLib3MFTransform Lib3MF::MatrixToTransform(const NMR::NMATRIX3 matrix) +{ + sLib3MFTransform transform; + for (int i = 0; i < 4; i++) { + for (int j = 0; j < 3; j++) + transform.m_Fields[i][j] = matrix.m_fields[j][i]; + } + return transform; +} + + +eLib3MFEncryptionAlgorithm Lib3MF::translateEncryptionAlgorithm(const NMR::eKeyStoreEncryptAlgorithm algorithm) { + if (NMR::eKeyStoreEncryptAlgorithm::AES256_GCM == algorithm) + return eLib3MFEncryptionAlgorithm::AES256_GCM; + throw ELib3MFInterfaceException(LIB3MF_ERROR_NOTIMPLEMENTED); +} +NMR::eKeyStoreEncryptAlgorithm Lib3MF::translateEncryptionAlgorithm(const eLib3MFEncryptionAlgorithm algorithm) { + if (eLib3MFEncryptionAlgorithm::AES256_GCM == algorithm) + return NMR::eKeyStoreEncryptAlgorithm::AES256_GCM; + throw ELib3MFInterfaceException(LIB3MF_ERROR_NOTIMPLEMENTED); +} + +eLib3MFWrappingAlgorithm Lib3MF::translateWrappingAlgorithm(const NMR::eKeyStoreWrapAlgorithm algorithm) { + if (NMR::eKeyStoreWrapAlgorithm::RSA_OAEP == algorithm) + return eLib3MFWrappingAlgorithm::RSA_OAEP; + throw ELib3MFInterfaceException(LIB3MF_ERROR_NOTIMPLEMENTED); +} +NMR::eKeyStoreWrapAlgorithm Lib3MF::translateWrappingAlgorithm(const eLib3MFWrappingAlgorithm algorithm) { + if (eLib3MFWrappingAlgorithm::RSA_OAEP == algorithm) + return NMR::eKeyStoreWrapAlgorithm::RSA_OAEP; + throw ELib3MFInterfaceException(LIB3MF_ERROR_NOTIMPLEMENTED); +} + + + +eLib3MFCompression Lib3MF::translateCompression(bool compression) { + if (compression) + return eLib3MFCompression::Deflate; + return eLib3MFCompression::NoCompression; +} + +bool Lib3MF::translateCompression(const eLib3MFCompression compression) { + return eLib3MFCompression::Deflate == compression; +} \ No newline at end of file diff --git a/Source/API/lib3mf_writer.cpp b/Source/API/lib3mf_writer.cpp new file mode 100644 index 0000000..33b26c4 --- /dev/null +++ b/Source/API/lib3mf_writer.cpp @@ -0,0 +1,269 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class definition of CWriter + +*/ + +#include "lib3mf_writer.hpp" + +// Include custom headers here. +#include "lib3mf_interfaceexception.hpp" +#include "lib3mf_accessright.hpp" +#include "lib3mf_contentencryptionparams.hpp" +#include "Common/Platform/NMR_Platform.h" +#include "Common/Platform/NMR_ExportStream_Callback.h" +#include "Common/Platform/NMR_ExportStream_Memory.h" +#include "Common/Platform/NMR_ExportStream_Dummy.h" +#include "Common/NMR_SecureContentTypes.h" +#include "Common/NMR_SecureContext.h" +#include "Model/Classes/NMR_KeyStore.h" +#include "Common/NMR_ModelWarnings.h" + + + +using namespace Lib3MF::Impl; + +/************************************************************************************************************************* + Class definition of CWriter +**************************************************************************************************************************/ + +CWriter::CWriter(std::string sWriterClass, NMR::PModel model) +{ + m_pWriter = nullptr; + + // Create specified writer instance + if (sWriterClass.compare("3mf") == 0) { + m_pWriter = std::make_shared(model); + } + else if (sWriterClass.compare("stl") == 0) { + m_pWriter = std::make_shared(model); + } + + if (!m_pWriter) + throw ELib3MFInterfaceException(LIB3MF_ERROR_WRITERCLASSUNKNOWN); +} + +NMR::CModelWriter& CWriter::writer() +{ + return *m_pWriter; +} + +void CWriter::WriteToFile (const std::string & sFilename) +{ + setlocale(LC_ALL, "C"); + NMR::PExportStream pStream = NMR::fnCreateExportStreamInstance(sFilename.c_str()); + try { + writer().exportToStream(pStream); + } + catch (NMR::CNMRException&e) { + if (e.getErrorCode() == NMR_USERABORTED) { + throw ELib3MFInterfaceException(LIB3MF_ERROR_CALCULATIONABORTED); + } else if (e.getErrorCode() == NMR_ERROR_DEKDESCRIPTORNOTFOUND + || e.getErrorCode() == NMR_ERROR_KEKDESCRIPTORNOTFOUND) { + throw ELib3MFInterfaceException(LIB3MF_ERROR_SECURECONTEXTNOTREGISTERED); + } else throw e; + } +} + +Lib3MF_uint64 CWriter::GetStreamSize () +{ + // Write to a special dummy stream just to calculate the size + NMR::PExportStreamDummy pStream = std::make_shared(); + try { + writer().exportToStream(pStream); + } + catch (NMR::CNMRException&e) { + if (e.getErrorCode() == NMR_USERABORTED) { + throw ELib3MFInterfaceException(LIB3MF_ERROR_CALCULATIONABORTED); + } else if (e.getErrorCode() == NMR_ERROR_DEKDESCRIPTORNOTFOUND + || e.getErrorCode() == NMR_ERROR_KEKDESCRIPTORNOTFOUND) { + throw ELib3MFInterfaceException(LIB3MF_ERROR_SECURECONTEXTNOTREGISTERED); + } else throw e; + } + + return pStream->getDataSize(); +} + +#include + +void CWriter::WriteToBuffer(Lib3MF_uint64 nBufferBufferSize, Lib3MF_uint64* pBufferNeededCount, Lib3MF_uint8 * pBufferBuffer) +{ + NMR::PExportStreamMemory pStream; + if (!momentBuffer || momentBuffer->getDataSize() > nBufferBufferSize) { + pStream = std::make_shared(); + try { + writer().exportToStream(pStream); + } catch (NMR::CNMRException&e) { + if (e.getErrorCode() == NMR_USERABORTED) { + throw ELib3MFInterfaceException(LIB3MF_ERROR_CALCULATIONABORTED); + } else if (e.getErrorCode() == NMR_ERROR_DEKDESCRIPTORNOTFOUND + || e.getErrorCode() == NMR_ERROR_KEKDESCRIPTORNOTFOUND) { + throw ELib3MFInterfaceException(LIB3MF_ERROR_SECURECONTEXTNOTREGISTERED); + } else throw e; + } + } else { + pStream = momentBuffer; + } + + Lib3MF_uint64 cbStreamSize = pStream->getDataSize(); + if (pBufferNeededCount) + *pBufferNeededCount = cbStreamSize; + + if (nBufferBufferSize >= cbStreamSize) { + // TODO eliminate this copy, perhaps by allowing CExportStreamMemory to use existing buffers + memcpy(pBufferBuffer, pStream->getData(), static_cast(cbStreamSize)); + momentBuffer.reset(); + } else { + momentBuffer = pStream; + } +} + +void CWriter::WriteToCallback(const Lib3MFWriteCallback pTheWriteCallback, const Lib3MFSeekCallback pTheSeekCallback, const Lib3MF_pvoid pUserData) +{ + NMR::ExportStream_WriteCallbackType lambdaWriteCallback = + [pTheWriteCallback](NMR::nfByte* pData, NMR::nfUint64 cbBytes, void* pUserData) + { + (*pTheWriteCallback)(reinterpret_cast(pData), cbBytes, pUserData ); + return 0; + }; + + NMR::ExportStream_SeekCallbackType lambdaSeekCallback = + [pTheSeekCallback](NMR::nfUint64 nPosition, void* pUserData) + { + (*pTheSeekCallback)(nPosition, pUserData); + return 0; + }; + + NMR::PExportStream pStream = std::make_shared(lambdaWriteCallback, lambdaSeekCallback, pUserData); + try { + writer().exportToStream(pStream); + } + catch (NMR::CNMRException&e) { + if (e.getErrorCode() == NMR_USERABORTED) { + throw ELib3MFInterfaceException(LIB3MF_ERROR_CALCULATIONABORTED); + } + else throw e; + } +} + +void CWriter::SetProgressCallback(const Lib3MFProgressCallback callback, const Lib3MF_pvoid pUserData) +{ + NMR::Lib3MFProgressCallback lambdaCallback = + [callback](int progressStep, NMR::ProgressIdentifier identifier, void* pUserData) + { + bool ret; + (*callback)(&ret, progressStep /100.0f, eLib3MFProgressIdentifier(identifier), pUserData); + return ret; + }; + m_pWriter->SetProgressCallback(lambdaCallback, reinterpret_cast(pUserData)); +} + +Lib3MF_uint32 CWriter::GetDecimalPrecision() +{ + return m_pWriter->GetDecimalPrecision(); +} + +void CWriter::SetDecimalPrecision(const Lib3MF_uint32 nDecimalPrecision) +{ + m_pWriter->SetDecimalPrecision(nDecimalPrecision); +} + +void Lib3MF::Impl::CWriter::AddKeyWrappingCallback(const std::string & sConsumerID, const Lib3MF::KeyWrappingCallback pTheCallback, const Lib3MF_pvoid pUserData){ + NMR::KeyWrappingDescriptor descriptor; + descriptor.m_sKekDecryptData.m_pUserData = pUserData; + descriptor.m_fnWrap = + [this, pTheCallback]( + std::vector const & plain, + std::vector & cipher, + NMR::KeyWrappingContext & ctx) { + + std::shared_ptr pAccessRight = std::make_shared(ctx.m_pAccessRight); + IBase * pBaseEntity(nullptr); + pBaseEntity = pAccessRight.get(); + Lib3MF_AccessRight entityHandle = pBaseEntity; + + Lib3MF_uint64 needed = 0; + Lib3MF_uint64 result = 0; + (*pTheCallback)(entityHandle, plain.size(), plain.data(), 0, + &needed, nullptr, ctx.m_pUserData, &result); + if (result == 0) + throw ELib3MFInterfaceException(LIB3MF_ERROR_CALCULATIONABORTED); + + cipher.resize(needed, 0); + + result = 0; + (*pTheCallback)(entityHandle, plain.size(), plain.data(), plain.size(), + nullptr, cipher.data(), ctx.m_pUserData, &result); + if (result == 0) + throw ELib3MFInterfaceException(LIB3MF_ERROR_CALCULATIONABORTED); + return (NMR::nfUint64)result; + }; + writer().secureContext()->addKekCtx(sConsumerID, descriptor); +} + +void Lib3MF::Impl::CWriter::SetContentEncryptionCallback(const Lib3MF::ContentEncryptionCallback pTheCallback, const Lib3MF_pvoid pUserData) +{ + NMR::ContentEncryptionDescriptor descriptor; + descriptor.m_sDekDecryptData.m_pUserData = pUserData; + descriptor.m_fnCrypt = [this, pTheCallback]( + NMR::nfUint64 size, + NMR::nfByte const * plain, + NMR::nfByte * cipher, + NMR::ContentEncryptionContext & ctx) { + std::shared_ptr pCekParams = std::make_shared(ctx.m_sParams); + IBase * pBaseEntity(nullptr); + pBaseEntity = pCekParams.get(); + Lib3MF_ContentEncryptionParams entityHandle = pBaseEntity; + Lib3MF_uint64 result = 0; + (*pTheCallback)(entityHandle, (Lib3MF_uint64)size, plain, (Lib3MF_uint64)size, nullptr, cipher, ctx.m_pUserData, &result); + if (result == 0) + throw ELib3MFInterfaceException(LIB3MF_ERROR_CALCULATIONABORTED); + return (NMR::nfUint64)result; + }; + m_pWriter->secureContext()->setDekCtx(descriptor); +} + +void CWriter::SetStrictModeActive(const bool bStrictModeActive) { + if (bStrictModeActive) + writer().warnings()->setCriticalWarningLevel(NMR::mrwInvalidOptionalValue); + else + writer().warnings()->setCriticalWarningLevel(NMR::mrwFatal); +} + +bool CWriter::GetStrictModeActive() { + return writer().warnings()->getCriticalWarningLevel() == NMR::mrwInvalidOptionalValue; +} + +std::string CWriter::GetWarning(const Lib3MF_uint32 nIndex, Lib3MF_uint32 & nErrorCode) { + auto warning = writer().warnings()->getWarning(nIndex); + nErrorCode = warning->getErrorCode(); + return warning->getMessage(); +} + +Lib3MF_uint32 CWriter::GetWarningCount() { + return writer().warnings()->getWarningCount(); +} \ No newline at end of file diff --git a/Source/Common/3MF_ProgressMonitor.cpp b/Source/Common/3MF_ProgressMonitor.cpp new file mode 100644 index 0000000..5519318 --- /dev/null +++ b/Source/Common/3MF_ProgressMonitor.cpp @@ -0,0 +1,157 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: Progress Monitor + +--*/ + +#include "Common/3MF_ProgressMonitor.h" +#include "Common/NMR_Exception.h" + +#include +#include +#include + +NMR::CProgressMonitor::CProgressMonitor() +{ + m_progressCallback = nullptr; + m_userData = nullptr; + m_lastCallbackResult = true; + m_dProgress = 0; + m_dProgressMax = 1; + m_eProgressIdentifier = ProgressIdentifier::PROGRESS_QUERYCANCELED; +} + +bool NMR::CProgressMonitor::QueryCancelled(bool throwIfCancelled) +{ + if (m_progressCallback) + { + std::unique_lock lock(m_callbackMutex, std::try_to_lock); + if (lock) // If another progress callback is happening right _now_, just drop this one + { + int nProgress = (int)(100 * m_dProgress / m_dProgressMax); + m_lastCallbackResult = m_progressCallback(nProgress, ProgressIdentifier::PROGRESS_QUERYCANCELED, m_userData); + + if (throwIfCancelled && m_lastCallbackResult) + throw CNMRException(NMR_USERABORTED); + + return m_lastCallbackResult; + } + } + return false; +} + +bool NMR::CProgressMonitor::ReportProgressAndQueryCancelled(bool throwIfCancelled) +{ + if (m_progressCallback) + { + std::unique_lock lock(m_callbackMutex, std::try_to_lock); + if (lock) // If another progress callback is happening right _now_, just drop this one + { + int nProgress = (int)(100 * m_dProgress / m_dProgressMax); + m_lastCallbackResult = m_progressCallback(nProgress, m_eProgressIdentifier, m_userData); + + if (throwIfCancelled && m_lastCallbackResult) + throw CNMRException(NMR_USERABORTED); + + return m_lastCallbackResult; + } + } + return false; +} + +bool NMR::CProgressMonitor::WasAborted() +{ + return (m_lastCallbackResult == false); +} + +void NMR::CProgressMonitor::SetProgressIdentifier(ProgressIdentifier identifier) +{ + m_eProgressIdentifier = identifier; +} + +void NMR::CProgressMonitor::SetMaxProgress(double dProgressMax) +{ + m_dProgressMax = dProgressMax; +} + +void NMR::CProgressMonitor::DecreaseMaxProgress(double dMaxProgressDecrement) +{ + m_dProgressMax = std::max(m_dProgressMax - dMaxProgressDecrement, 1.0); + m_dProgress = std::min(m_dProgressMax, m_dProgress); +} + +void NMR::CProgressMonitor::IncrementProgress(double dProgressIncrement) +{ + if (m_progressCallback) + { + { + std::unique_lock lock(m_callbackMutex, std::try_to_lock); + m_dProgress = std::min(m_dProgressMax, m_dProgress + dProgressIncrement); + } + } +} + +void NMR::CProgressMonitor::SetProgressCallback(Lib3MFProgressCallback callback, void * userData) +{ + m_progressCallback = callback; + m_userData = userData; + m_lastCallbackResult = true; +} + +void NMR::CProgressMonitor::ClearProgressCallback() +{ + SetProgressCallback(nullptr, nullptr); +} + +void NMR::CProgressMonitor::GetProgressMessage(NMR::ProgressIdentifier progressIdentifier, std::string& progressString) { + switch (progressIdentifier) { + case PROGRESS_QUERYCANCELED: progressString = ""; break; + case PROGRESS_DONE: progressString = "Done"; break; + case PROGRESS_CLEANUP: progressString = "Cleaning up"; break; + case PROGRESS_READSTREAM: progressString = "Reading stream"; break; + case PROGRESS_EXTRACTOPCPACKAGE: progressString = "Extracting OPC package"; break; + case PROGRESS_READNONROOTMODELS: progressString = "Reading non-root models"; break; + case PROGRESS_READROOTMODEL: progressString = "Reading root model"; break; + case PROGRESS_READRESOURCES: progressString = "Reading resources"; break; + case PROGRESS_READMESH: progressString = "Reading mesh data"; break; + case PROGRESS_READSLICES: progressString = "Reading slice data"; break; + case PROGRESS_READBUILD: progressString = "Reading build definition"; break; + case PROGRESS_READCUSTOMATTACHMENTS: progressString = "Reading custom attachments"; break; + case PROGRESS_READTEXTURETACHMENTS: progressString = "Reading texture attachments"; break; + case PROGRESS_CREATEOPCPACKAGE: progressString = "Creating OPC package"; break; + case PROGRESS_WRITEMODELSTOSTREAM: progressString = "Writing models to stream"; break; + case PROGRESS_WRITEROOTMODEL: progressString = "Writing root model"; break; + case PROGRESS_WRITENONROOTMODELS: progressString = "Writing non-root models"; break; + case PROGRESS_WRITEATTACHMENTS: progressString = "Writing attachments"; break; + case PROGRESS_WRITECONTENTTYPES: progressString = "Writing content types"; break; + case PROGRESS_WRITEOBJECTS: progressString = "Writing objects"; break; + case PROGRESS_WRITENODES: progressString = "Writing Nodes"; break; + case PROGRESS_WRITETRIANGLES: progressString = "Writing triangles"; break; + case PROGRESS_WRITESLICES: progressString = "Writing slices"; break; + default: progressString = "Unknown Progress Identifier"; + } +} diff --git a/Source/Common/Math/NMR_Matrix.cpp b/Source/Common/Math/NMR_Matrix.cpp new file mode 100644 index 0000000..da0fadb --- /dev/null +++ b/Source/Common/Math/NMR_Matrix.cpp @@ -0,0 +1,493 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_Matrix.cpp implements all needed matrix calculations and transforms for +2D and 3D vectors. + +--*/ + +#include "Common/Math/NMR_Geometry.h" +#include "Common/Math/NMR_Matrix.h" +#include "Common/Math/NMR_Vector.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_StringUtils.h" +#include +#include +#include + +namespace NMR { + + NMATRIX2 fnMATRIX2_identity() + { + NMATRIX2 mResult; + nfInt32 i, j; + for (i = 0; i < 3; i++) + for (j = 0; j < 3; j++) + mResult.m_fields[i][j] = (i == j) ? 1.0f : 0.0f; + + return mResult; + } + + NMATRIX2 fnMATRIX2_rotation(_In_ const nfFloat fAngle) + { + NMATRIX2 mResult; + nfFloat s = sinf(fAngle); + nfFloat c = cosf(fAngle); + + mResult.m_fields[0][0] = c; + mResult.m_fields[0][1] = -s; + mResult.m_fields[0][2] = 0.0f; + mResult.m_fields[1][0] = s; + mResult.m_fields[1][1] = c; + mResult.m_fields[1][2] = 0.0f; + mResult.m_fields[2][0] = 0.0f; + mResult.m_fields[2][1] = 0.0f; + mResult.m_fields[2][2] = 1.0f; + + return mResult; + } + + NMATRIX2 fnMATRIX2_translation(_In_ const NVEC2 vTranslation) + { + NMATRIX2 mResult; + + mResult.m_fields[0][0] = 1.0f; + mResult.m_fields[0][1] = 0.0f; + mResult.m_fields[0][2] = vTranslation.m_fields[0]; + mResult.m_fields[1][0] = 0.0f; + mResult.m_fields[1][1] = 1.0f; + mResult.m_fields[1][2] = vTranslation.m_fields[1]; + mResult.m_fields[2][0] = 0.0f; + mResult.m_fields[2][1] = 0.0f; + mResult.m_fields[2][2] = 1.0f; + + return mResult; + } + + NMATRIX2 fnMATRIX2_transformation(_In_ const nfFloat fAngle, _In_ const NVEC2 vTranslation) + { + NMATRIX2 mResult; + nfFloat s = sinf(fAngle); + nfFloat c = cosf(fAngle); + + mResult.m_fields[0][0] = c; + mResult.m_fields[0][1] = -s; + mResult.m_fields[0][2] = vTranslation.m_fields[0]; + mResult.m_fields[1][0] = s; + mResult.m_fields[1][1] = c; + mResult.m_fields[1][2] = vTranslation.m_fields[1]; + mResult.m_fields[2][0] = 0.0f; + mResult.m_fields[2][1] = 0.0f; + mResult.m_fields[2][2] = 1.0f; + + return mResult; + } + + NMATRIX2 fnMATRIX2_uniformscale(_In_ nfFloat fScale) + { + NMATRIX2 mResult; + + mResult.m_fields[0][0] = fScale; + mResult.m_fields[0][1] = 0.0f; + mResult.m_fields[0][2] = 0.0f; + mResult.m_fields[1][0] = 0.0f; + mResult.m_fields[1][1] = fScale; + mResult.m_fields[1][2] = 0.0f; + mResult.m_fields[2][0] = 0.0f; + mResult.m_fields[2][1] = 0.0f; + mResult.m_fields[2][2] = 1.0f; + + return mResult; + } + + NMATRIX2 fnMATRIX2_scale(_In_ nfFloat fScaleX, _In_ nfFloat fScaleY) + { + NMATRIX2 mResult; + + mResult.m_fields[0][0] = fScaleX; + mResult.m_fields[0][1] = 0.0f; + mResult.m_fields[0][2] = 0.0f; + mResult.m_fields[1][0] = 0.0f; + mResult.m_fields[1][1] = fScaleY; + mResult.m_fields[1][2] = 0.0f; + mResult.m_fields[2][0] = 0.0f; + mResult.m_fields[2][1] = 0.0f; + mResult.m_fields[2][2] = 1.0f; + + return mResult; + } + + NMATRIX2 fnMATRIX2_multiply(_In_ const NMATRIX2 mMatrix1, _In_ const NMATRIX2 mMatrix2) + { + NMATRIX2 mResult; + nfInt32 i, j; + for (i = 0; i < 3; i++) + for (j = 0; j < 3; j++) + mResult.m_fields[i][j] = mMatrix1.m_fields[i][0] * mMatrix2.m_fields[0][j] + + mMatrix1.m_fields[i][1] * mMatrix2.m_fields[1][j] + + mMatrix1.m_fields[i][2] * mMatrix2.m_fields[2][j]; + + return mResult; + } + + NVEC2 fnMATRIX2_apply(_In_ const NMATRIX2 mMatrix, _In_ const NVEC2 vVector) + { + NVEC2 vResult; + nfInt32 i; + for (i = 0; i < 2; i++) + vResult.m_fields[i] = mMatrix.m_fields[i][0] * vVector.m_fields[0] + mMatrix.m_fields[i][1] * vVector.m_fields[1] + mMatrix.m_fields[i][2]; + + return vResult; + } + + NLINMATRIX2 fnLINMATRIX2_identity() + { + NLINMATRIX2 mResult; + nfInt32 i, j; + for (i = 0; i < 2; i++) + for (j = 0; j < 2; j++) + mResult.m_fields[i][j] = (i == j) ? 1.0f : 0.0f; + + return mResult; + } + + NLINMATRIX2 fnLINMATRIX2_rotation(_In_ const nfFloat fAngle) + { + NLINMATRIX2 mResult; + nfFloat s = sinf(fAngle); + nfFloat c = cosf(fAngle); + + mResult.m_fields[0][0] = c; + mResult.m_fields[0][1] = -s; + mResult.m_fields[1][0] = s; + mResult.m_fields[1][1] = c; + + return mResult; + } + + NLINMATRIX2 fnLINMATRIX2_uniformscale(_In_ nfFloat fScale) + { + NLINMATRIX2 mResult; + + mResult.m_fields[0][0] = fScale; + mResult.m_fields[0][1] = 0.0f; + mResult.m_fields[1][0] = 0.0f; + mResult.m_fields[1][1] = fScale; + + return mResult; + } + + NLINMATRIX2 fnLINMATRIX2_scale(_In_ nfFloat fScaleX, _In_ nfFloat fScaleY) + { + NLINMATRIX2 mResult; + + mResult.m_fields[0][0] = fScaleX; + mResult.m_fields[0][1] = 0.0f; + mResult.m_fields[1][0] = 0.0f; + mResult.m_fields[1][1] = fScaleY; + + return mResult; + } + + NLINMATRIX2 fnLINMATRIX2_multiply(_In_ const NLINMATRIX2 mMatrix1, _In_ const NLINMATRIX2 mMatrix2) + { + NLINMATRIX2 mResult; + nfInt32 i, j; + for (i = 0; i < 2; i++) + for (j = 0; j < 2; j++) + mResult.m_fields[i][j] = mMatrix1.m_fields[i][0] * mMatrix2.m_fields[0][j] + + mMatrix1.m_fields[i][1] * mMatrix2.m_fields[1][j]; + + return mResult; + } + + NVEC2 fnLINMATRIX2_apply(_In_ const NLINMATRIX2 mMatrix, _In_ const NVEC2 vVector) + { + NVEC2 vResult; + nfInt32 i; + for (i = 0; i < 2; i++) + vResult.m_fields[i] = mMatrix.m_fields[i][0] * vVector.m_fields[0] + mMatrix.m_fields[i][1] * vVector.m_fields[1]; + + return vResult; + } + + NLINMATRIX2 fnLINMATRIX2_invert(_In_ const NLINMATRIX2 mMatrix, _In_ nfBool bFailIfSingular) + { + nfFloat fDet = mMatrix.m_fields[0][0] * mMatrix.m_fields[1][1] - mMatrix.m_fields[0][1] * mMatrix.m_fields[1][0]; + if (fabs(fDet) < NMR_MATRIX_MINDETERMINANT) { + if (bFailIfSingular) + throw CNMRException(NMR_ERROR_SINGULARMATRIX); + return fnLINMATRIX2_identity(); + } + + NLINMATRIX2 mResult; + + mResult.m_fields[0][0] = mMatrix.m_fields[1][1] / fDet; + mResult.m_fields[0][1] = -mMatrix.m_fields[0][1] / fDet; + mResult.m_fields[1][0] = -mMatrix.m_fields[1][0] / fDet; + mResult.m_fields[1][1] = mMatrix.m_fields[0][0] / fDet; + + return mResult; + } + + NMATRIX3 fnMATRIX3_identity() + { + NMATRIX3 mResult; + nfInt32 i, j; + for (i = 0; i < 4; i++) + for (j = 0; j < 4; j++) + mResult.m_fields[i][j] = (i == j) ? 1.0f : 0.0f; + + return mResult; + } + + nfBool fnMATRIX3_isIdentity(_In_ const NMATRIX3 mMatrix) + { + nfDouble dDelta = 0.0; + nfInt32 i, j; + for (i = 0; i < 4; i++) + for (j = 0; j < 4; j++) { + nfDouble dId = (i == j) ? 1.0f : 0.0f; + nfDouble dM = mMatrix.m_fields[i][j]; + nfDouble dX = dM - dId; + dDelta += dX * dX; + } + + return dDelta < NMR_MATRIX_IDENTITYTHRESHOLD; + } + + NMATRIX3 fnMATRIX3_rotation(_In_ const NVEC3 vAxis, _In_ const nfFloat fAngle) + { + NVEC3 vNormalAxis = fnVEC3_normalize(vAxis); + + NMATRIX3 mResult; + nfFloat s = sinf(fAngle); + nfFloat c = cosf(fAngle); + nfFloat c1 = 1 - c; + + mResult.m_fields[0][0] = vNormalAxis.m_fields[0] * vNormalAxis.m_fields[0] * c1 + c; + mResult.m_fields[0][1] = vNormalAxis.m_fields[1] * vNormalAxis.m_fields[0] * c1 + vNormalAxis.m_fields[2] * s; + mResult.m_fields[0][2] = vNormalAxis.m_fields[2] * vNormalAxis.m_fields[0] * c1 - vNormalAxis.m_fields[1] * s; + mResult.m_fields[0][3] = 0.0f; + mResult.m_fields[1][0] = vNormalAxis.m_fields[0] * vNormalAxis.m_fields[1] * c1 - vNormalAxis.m_fields[2] * s; + mResult.m_fields[1][1] = vNormalAxis.m_fields[1] * vNormalAxis.m_fields[1] * c1 + c; + mResult.m_fields[1][2] = vNormalAxis.m_fields[2] * vNormalAxis.m_fields[1] * c1 + vNormalAxis.m_fields[0] * s; + mResult.m_fields[1][3] = 0.0f; + mResult.m_fields[2][0] = vNormalAxis.m_fields[0] * vNormalAxis.m_fields[2] * c1 + vNormalAxis.m_fields[1] * s; + mResult.m_fields[2][1] = vNormalAxis.m_fields[1] * vNormalAxis.m_fields[2] * c1 - vNormalAxis.m_fields[0] * s; + mResult.m_fields[2][2] = vNormalAxis.m_fields[2] * vNormalAxis.m_fields[2] * c1 + c; + mResult.m_fields[2][3] = 0.0f; + mResult.m_fields[3][0] = 0.0f; + mResult.m_fields[3][1] = 0.0f; + mResult.m_fields[3][2] = 0.0f; + mResult.m_fields[3][3] = 1.0f; + + return mResult; + } + + NMATRIX3 fnMATRIX3_translation(_In_ const NVEC3 vTranslation) + { + NMATRIX3 mResult; + + mResult.m_fields[0][0] = 1.0f; + mResult.m_fields[0][1] = 0.0f; + mResult.m_fields[0][2] = 0.0f; + mResult.m_fields[0][3] = vTranslation.m_fields[0]; + mResult.m_fields[1][0] = 0.0f; + mResult.m_fields[1][1] = 1.0f; + mResult.m_fields[1][2] = 0.0f; + mResult.m_fields[1][3] = vTranslation.m_fields[1]; + mResult.m_fields[2][0] = 0.0f; + mResult.m_fields[2][1] = 0.0f; + mResult.m_fields[2][2] = 1.0f; + mResult.m_fields[2][3] = vTranslation.m_fields[2]; + mResult.m_fields[3][0] = 0.0f; + mResult.m_fields[3][1] = 0.0f; + mResult.m_fields[3][2] = 0.0f; + mResult.m_fields[3][3] = 1.0f; + + return mResult; + } + + NMATRIX3 fnMATRIX3_transformation(_In_ const NVEC3 vAxis, _In_ const nfFloat fAngle, _In_ const NVEC3 vTranslation) + { + NMATRIX3 mResult = fnMATRIX3_rotation(vAxis, fAngle); + + mResult.m_fields[0][3] = vTranslation.m_fields[0]; + mResult.m_fields[1][3] = vTranslation.m_fields[1]; + mResult.m_fields[2][3] = vTranslation.m_fields[2]; + + return mResult; + } + + NMATRIX3 fnMATRIX3_multiply(_In_ const NMATRIX3 mMatrix1, _In_ const NMATRIX3 mMatrix2) + { + NMATRIX3 mResult; + nfInt32 i, j; + for (i = 0; i < 4; i++) + for (j = 0; j < 4; j++) + mResult.m_fields[i][j] = mMatrix1.m_fields[i][0] * mMatrix2.m_fields[0][j] + + mMatrix1.m_fields[i][1] * mMatrix2.m_fields[1][j] + + mMatrix1.m_fields[i][2] * mMatrix2.m_fields[2][j] + + mMatrix1.m_fields[i][3] * mMatrix2.m_fields[3][j]; + + return mResult; + + } + + NMATRIX3 fnMATRIX3_uniformscale(_In_ nfFloat fScale) + { + NMATRIX3 mResult; + + mResult.m_fields[0][0] = fScale; + mResult.m_fields[0][1] = 0.0f; + mResult.m_fields[0][2] = 0.0f; + mResult.m_fields[0][3] = 0.0f; + mResult.m_fields[1][0] = 0.0f; + mResult.m_fields[1][1] = fScale; + mResult.m_fields[1][2] = 0.0f; + mResult.m_fields[1][3] = 0.0f; + mResult.m_fields[2][0] = 0.0f; + mResult.m_fields[2][1] = 0.0f; + mResult.m_fields[2][2] = fScale; + mResult.m_fields[2][3] = 0.0f; + mResult.m_fields[3][0] = 0.0f; + mResult.m_fields[3][1] = 0.0f; + mResult.m_fields[3][2] = 0.0f; + mResult.m_fields[3][3] = 1.0f; + + return mResult; + } + + NMATRIX3 fnMATRIX3_scale(_In_ nfFloat fScaleX, _In_ nfFloat fScaleY, _In_ nfFloat fScaleZ) + { + NMATRIX3 mResult; + + mResult.m_fields[0][0] = fScaleX; + mResult.m_fields[0][1] = 0.0f; + mResult.m_fields[0][2] = 0.0f; + mResult.m_fields[0][3] = 0.0f; + mResult.m_fields[1][0] = 0.0f; + mResult.m_fields[1][1] = fScaleY; + mResult.m_fields[1][2] = 0.0f; + mResult.m_fields[1][3] = 0.0f; + mResult.m_fields[2][0] = 0.0f; + mResult.m_fields[2][1] = 0.0f; + mResult.m_fields[2][2] = fScaleZ; + mResult.m_fields[2][3] = 0.0f; + mResult.m_fields[3][0] = 0.0f; + mResult.m_fields[3][1] = 0.0f; + mResult.m_fields[3][2] = 0.0f; + mResult.m_fields[3][3] = 1.0f; + + return mResult; + } + + NVEC3 fnMATRIX3_apply(_In_ const NMATRIX3 mMatrix, _In_ const NVEC3 vVector) + { + NVEC3 vResult; + nfInt32 i; + for (i = 0; i < 3; i++) + vResult.m_fields[i] = mMatrix.m_fields[i][0] * vVector.m_fields[0] + mMatrix.m_fields[i][1] * vVector.m_fields[1] + mMatrix.m_fields[i][2] * vVector.m_fields[2] + mMatrix.m_fields[i][3]; + + return vResult; + } + + std::string fnMATRIX3_toString(_In_ const NMATRIX3 mMatrix) { + std::stringstream sStream; + nfInt32 i, j; + + for (j = 0; j < 4; j++) { + for (i = 0; i < 3; i++) { + sStream << mMatrix.m_fields[i][j]; + if ((i != 2) || (j != 3)) + sStream << " "; + } + } + + return sStream.str(); + } + + NMATRIX3 fnMATRIX3_fromString(_In_ const std::string sString) + { + nfUint32 nValueCount = 0; + nfFloat nValues[12]; + + const nfChar * pszString = sString.c_str(); + const nfChar * pCurrent = pszString; + + nfBool bFinished = false; + while (!bFinished) { + // Find next space + const nfChar * pBegin = pCurrent; + while ((*pCurrent != ' ') && (*pCurrent)) + pCurrent++; + + // If we have not found a space, convert value to double + if (pBegin != pCurrent) { + if (nValueCount >= 12) + throw CNMRException(NMR_ERROR_TOOMANYVALUESINMATRIXSTRING); + nValues[nValueCount] = fnStringToFloat(pBegin); + nValueCount++; + } + + // If we are finished, break, otherwise skip space! + if (!*pCurrent) + bFinished = true; + else + pCurrent++; + } + + if (nValueCount < 12) + throw CNMRException(NMR_ERROR_NOTENOUGHVALUESINMATRIXSTRING); + + NMATRIX3 mResult; + + nfInt32 i, j; + for (j = 0; j < 4; j++) { + for (i = 0; i < 3; i++) { + mResult.m_fields[i][j] = nValues[i + j * 3]; + } + } + + mResult.m_fields[3][0] = 0.0f; + mResult.m_fields[3][1] = 0.0f; + mResult.m_fields[3][2] = 0.0f; + mResult.m_fields[3][3] = 1.0f; + + return mResult; + } + + nfBool fnMATRIX3_isplanar(_In_ const NMATRIX3 mMatrix) + { + const double eps = 1e-7; + return (fabs(mMatrix.m_fields[2][0]) < eps) && (fabs(mMatrix.m_fields[2][1]) < eps) && (fabs(mMatrix.m_fields[2][2] - 1 ) < eps) + && (fabs(mMatrix.m_fields[0][2]) < eps) && (fabs(mMatrix.m_fields[1][2]) < eps); + } + +} diff --git a/Source/Common/Math/NMR_PairMatchingTree.cpp b/Source/Common/Math/NMR_PairMatchingTree.cpp new file mode 100644 index 0000000..cb36e22 --- /dev/null +++ b/Source/Common/Math/NMR_PairMatchingTree.cpp @@ -0,0 +1,115 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_PairMatchingTree.cpp implements a n-log-n tree class which is able to identify +duplicate pairs of numbers in a given data set. + +--*/ + + +#include "Common/Math/NMR_PairMatchingTree.h" +#include "Common/NMR_Exception.h" +#include +#include + +namespace NMR { + + bool operator< (_In_ const PAIRMATCHINGTREEENTRY & entry1, _In_ const PAIRMATCHINGTREEENTRY & entry2) + { + for (int i = 0; i < 2; i++) { + if (entry1.m_pair[i] < entry2.m_pair[i]) + return true; + if (entry1.m_pair[i] > entry2.m_pair[i]) + return false; + } + return false; + } + + + CPairMatchingTree::CPairMatchingTree() + { + } + + CPairMatchingTree::~CPairMatchingTree() + { + } + + void CPairMatchingTree::addMatch(_In_ nfInt32 data1, _In_ nfInt32 data2, _In_ nfInt32 param) + { + PAIRMATCHINGTREEENTRY entry; + if (data1 < data2) { + entry.m_pair[0] = data1; + entry.m_pair[1] = data2; + } + else { + entry.m_pair[0] = data2; + entry.m_pair[1] = data1; + } + + m_entries.insert(std::make_pair(entry, param)); + } + + _Success_(return) nfBool CPairMatchingTree::checkMatch(_In_ nfInt32 data1, _In_ nfInt32 data2, _Out_opt_ nfInt32 ¶m) + { + std::map::iterator iter; + PAIRMATCHINGTREEENTRY entry; + if (data1 < data2) { + entry.m_pair[0] = data1; + entry.m_pair[1] = data2; + } + else { + entry.m_pair[0] = data2; + entry.m_pair[1] = data1; + } + + iter = m_entries.find(entry); + if (iter != m_entries.end()) { + param = iter->second; + return true; + } + + return false; + } + + void CPairMatchingTree::deleteMatch(_In_ nfInt32 data1, _In_ nfInt32 data2) + { + PAIRMATCHINGTREEENTRY entry; + if (data1 < data2) { + entry.m_pair[0] = data1; + entry.m_pair[1] = data2; + } + else { + entry.m_pair[0] = data2; + entry.m_pair[1] = data1; + } + m_entries.erase(entry); + + } + +} + diff --git a/Source/Common/Math/NMR_Vector.cpp b/Source/Common/Math/NMR_Vector.cpp new file mode 100644 index 0000000..856e720 --- /dev/null +++ b/Source/Common/Math/NMR_Vector.cpp @@ -0,0 +1,723 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_Vector.cpp implements all needed direct operations on 2D and 3D vectors. + +--*/ + +#include "Common/Math/NMR_Geometry.h" +#include "Common/Math/NMR_Vector.h" +#include "Common/NMR_Exception.h" +#include +#include +#include + +namespace NMR { + + NVEC2 fnVEC2_make(_In_ nfFloat fX, _In_ nfFloat fY) + { + NVEC2 vResult; + vResult.m_values.x = fX; + vResult.m_values.y = fY; + return vResult; + } + + NVEC2 fnVEC2_add(_In_ const NVEC2 vVector1, _In_ const NVEC2 vVector2) + { + nfInt32 j; + NVEC2 vResult; + + for (j = 0; j < 2; j++) + vResult.m_fields[j] = vVector1.m_fields[j] + vVector2.m_fields[j]; + + return vResult; + } + + NVEC2 fnVEC2_sub(_In_ const NVEC2 vMinuend, _In_ const NVEC2 vSubtrahend) + { + nfInt32 j; + NVEC2 vResult; + + for (j = 0; j < 2; j++) + vResult.m_fields[j] = vMinuend.m_fields[j] - vSubtrahend.m_fields[j]; + + return vResult; + } + + + NVEC2 fnVEC2_scale(_In_ const NVEC2 vVector, _In_ nfFloat vFactor) + { + nfInt32 j; + NVEC2 vResult; + + for (j = 0; j < 2; j++) + vResult.m_fields[j] = vVector.m_fields[j] * vFactor; + + return vResult; + } + + NVEC2 fnVEC2_combine(_In_ const NVEC2 vVector1, _In_ nfFloat vFactor1, _In_ const NVEC2 vVector2, _In_ nfFloat vFactor2) + { + nfInt32 j; + NVEC2 vResult; + + for (j = 0; j < 2; j++) + vResult.m_fields[j] = vVector1.m_fields[j] * vFactor1 + vVector2.m_fields[j] * vFactor2; + + return vResult; + } + + nfFloat fnVEC2_dotproduct(_In_ const NVEC2 vVector1, _In_ const NVEC2 vVector2) + { + return vVector1.m_values.x * vVector2.m_values.x + vVector1.m_values.y * vVector2.m_values.y; + } + + nfFloat fnVEC2_crossproduct(_In_ const NVEC2 vVector1, _In_ const NVEC2 vVector2) + { + return vVector1.m_values.x * vVector2.m_values.y - vVector1.m_values.y * vVector2.m_values.x; + } + + nfFloat fnVEC2_length(_In_ const NVEC2 vVector) + { + return sqrtf(vVector.m_values.x * vVector.m_values.x + vVector.m_values.y * vVector.m_values.y); + } + + nfFloat fnVEC2_distance(_In_ const NVEC2 vPoint1, _In_ const NVEC2 vPoint2) + { + return fnVEC2_length(fnVEC2_sub(vPoint1, vPoint2)); + } + + NVEC2 fnVEC2_normalize(_In_ const NVEC2 vVector) + { + nfFloat fLength = fnVEC2_length(vVector); + if (fLength < NMR_VECTOR_MINNORMALIZELENGTH) + throw CNMRException(NMR_ERROR_NORMALIZEDZEROVECTOR); + + return fnVEC2_scale(vVector, 1.0f / fLength); + } + + NVEC2I fnVEC2I_make(_In_ nfInt32 nX, _In_ nfInt32 nY) + { + NVEC2I vResult; + vResult.m_values.x = nX; + vResult.m_values.y = nY; + return vResult; + } + + NVEC2I fnVEC2I_floor(_In_ NVEC2 vVector, _In_ nfFloat fUnits) + { + if ((fUnits < NMR_VECTOR_MINUNITS) || (fUnits > NMR_VECTOR_MAXUNITS)) + throw CNMRException(NMR_ERROR_INVALIDUNITS); + + NVEC2I vResult; + vResult.m_values.x = (nfInt32) floor(vVector.m_values.x / fUnits); + vResult.m_values.y = (nfInt32) floor(vVector.m_values.y / fUnits); + return vResult; + } + + NVEC2 fnVEC2I_uncast(_In_ NVEC2I vVector, _In_ nfFloat fUnits) + { + if ((fUnits < NMR_VECTOR_MINUNITS) || (fUnits > NMR_VECTOR_MAXUNITS)) + throw CNMRException(NMR_ERROR_INVALIDUNITS); + + NVEC2 vResult; + vResult.m_values.x = (nfFloat)(vVector.m_values.x) * fUnits; + vResult.m_values.y = (nfFloat)(vVector.m_values.y) * fUnits; + return vResult; + } + + NVEC2I fnVEC2I_add(_In_ const NVEC2I vVector1, _In_ const NVEC2I vVector2) + { + nfInt32 j; + NVEC2I vResult; + + for (j = 0; j < 2; j++) + vResult.m_fields[j] = vVector1.m_fields[j] + vVector2.m_fields[j]; + + return vResult; + } + + NVEC2I fnVEC2I_sub(_In_ const NVEC2I vMinuend, _In_ const NVEC2I vSubtrahend) + { + nfInt32 j; + NVEC2I vResult; + + for (j = 0; j < 2; j++) + vResult.m_fields[j] = vMinuend.m_fields[j] - vSubtrahend.m_fields[j]; + + return vResult; + } + + NVEC2I fnVEC2I_scale(_In_ const NVEC2I vVector, _In_ nfInt32 vFactor) + { + nfInt32 j; + NVEC2I vResult; + + for (j = 0; j < 2; j++) + vResult.m_fields[j] = vVector.m_fields[j] * vFactor; + + return vResult; + } + + nfInt64 fnVEC2I_dotproduct(_In_ const NVEC2I vVector1, _In_ const NVEC2I vVector2) + { + nfInt64 v1x = vVector1.m_values.x; + nfInt64 v1y = vVector1.m_values.y; + nfInt64 v2x = vVector2.m_values.x; + nfInt64 v2y = vVector2.m_values.y; + return v1x * v2x + v1y * v2y; + } + + nfFloat fnVEC2I_length(_In_ const NVEC2I vVector) + { + nfInt64 vx = vVector.m_values.x; + nfInt64 vy = vVector.m_values.y; + nfInt64 dotproduct = vx * vx + vy * vy; + return sqrtf((nfFloat)dotproduct); + } + + nfFloat fnVEC2I_distance(_In_ const NVEC2I vPoint1, _In_ const NVEC2I vPoint2) + { + return fnVEC2I_length(fnVEC2I_sub(vPoint1, vPoint2)); + } + + NVEC3 fnVEC3_make(_In_ nfFloat fX, _In_ nfFloat fY, _In_ nfFloat fZ) + { + NVEC3 vResult; + vResult.m_values.x = fX; + vResult.m_values.y = fY; + vResult.m_values.z = fZ; + return vResult; + } + + NVEC3I fnVEC3I_floor(_In_ NVEC3 vVector, _In_ nfFloat fUnits) + { + if ((fUnits < NMR_VECTOR_MINUNITS) || (fUnits > NMR_VECTOR_MAXUNITS)) + throw CNMRException(NMR_ERROR_INVALIDUNITS); + + NVEC3I vResult; + vResult.m_values.x = (nfInt32) floor(vVector.m_values.x / fUnits); + vResult.m_values.y = (nfInt32) floor(vVector.m_values.y / fUnits); + vResult.m_values.z = (nfInt32) floor(vVector.m_values.z / fUnits); + return vResult; + } + + NVEC3I fnVEC3I_round(_In_ NVEC3 vVector, _In_ nfFloat fUnits) + { + if ((fUnits < NMR_VECTOR_MINUNITS) || (fUnits > NMR_VECTOR_MAXUNITS)) + throw CNMRException(NMR_ERROR_INVALIDUNITS); + + NVEC3I vResult; + vResult.m_values.x = (nfInt32)round(vVector.m_values.x / fUnits); + vResult.m_values.y = (nfInt32)round(vVector.m_values.y / fUnits); + vResult.m_values.z = (nfInt32)round(vVector.m_values.z / fUnits); + return vResult; + } + + NVEC3 fnVEC3I_uncast(_In_ NVEC3I vVector, _In_ nfFloat fUnits) + { + if ((fUnits < NMR_VECTOR_MINUNITS) || (fUnits > NMR_VECTOR_MAXUNITS)) + throw CNMRException(NMR_ERROR_INVALIDUNITS); + + NVEC3 vResult; + vResult.m_values.x = (nfFloat)(vVector.m_values.x) * fUnits; + vResult.m_values.y = (nfFloat)(vVector.m_values.y) * fUnits; + vResult.m_values.z = (nfFloat)(vVector.m_values.z) * fUnits; + return vResult; + } + + NVEC3 fnVEC3_add(_In_ const NVEC3 vVector1, _In_ const NVEC3 vVector2) + { + nfInt32 j; + NVEC3 vResult; + + for (j = 0; j < 3; j++) + vResult.m_fields[j] = vVector1.m_fields[j] + vVector2.m_fields[j]; + + return vResult; + } + + NVEC3 fnVEC3_sub(_In_ const NVEC3 vMinuend, _In_ const NVEC3 vSubtrahend) + { + nfInt32 j; + NVEC3 vResult; + + for (j = 0; j < 3; j++) + vResult.m_fields[j] = vMinuend.m_fields[j] - vSubtrahend.m_fields[j]; + + return vResult; + } + + NVEC3 fnVEC3_scale(_In_ const NVEC3 vVector, _In_ nfFloat vFactor) + { + nfInt32 j; + NVEC3 vResult; + + for (j = 0; j < 3; j++) + vResult.m_fields[j] = vVector.m_fields[j] * vFactor; + + return vResult; + } + + NVEC3 fnVEC3_combine(_In_ const NVEC3 vVector1, _In_ nfFloat vFactor1, _In_ const NVEC3 vVector2, _In_ nfFloat vFactor2) + { + nfInt32 j; + NVEC3 vResult; + + for (j = 0; j < 3; j++) + vResult.m_fields[j] = vVector1.m_fields[j] * vFactor1 + vVector2.m_fields[j] * vFactor2; + + return vResult; + } + + nfFloat fnVEC3_dotproduct(_In_ const NVEC3 vVector1, _In_ const NVEC3 vVector2) + { + return vVector1.m_values.x * vVector2.m_values.x + + vVector1.m_values.y * vVector2.m_values.y + + vVector1.m_values.z * vVector2.m_values.z; + } + + NVEC3 fnVEC3_crossproduct(_In_ const NVEC3 vVector1, _In_ const NVEC3 vVector2) + { + NVEC3 vResult; + + vResult.m_values.x = vVector1.m_values.y * vVector2.m_values.z - vVector1.m_values.z * vVector2.m_values.y; + vResult.m_values.y = vVector1.m_values.z * vVector2.m_values.x - vVector1.m_values.x * vVector2.m_values.z; + vResult.m_values.z = vVector1.m_values.x * vVector2.m_values.y - vVector1.m_values.y * vVector2.m_values.x; + + return vResult; + } + + nfFloat fnVEC3_length(_In_ const NVEC3 vVector) + { + return sqrtf(vVector.m_values.x * vVector.m_values.x + vVector.m_values.y * vVector.m_values.y + vVector.m_values.z * vVector.m_values.z); + } + + nfFloat fnVEC3_distance(_In_ const NVEC3 vPoint1, _In_ const NVEC3 vPoint2) + { + return fnVEC3_length(fnVEC3_sub(vPoint1, vPoint2)); + } + + NVEC3 fnVEC3_normalize(_In_ const NVEC3 vVector) + { + nfFloat fLength = fnVEC3_length(vVector); + if (fLength < NMR_VECTOR_MINNORMALIZELENGTH) + throw CNMRException(NMR_ERROR_NORMALIZEDZEROVECTOR); + + return fnVEC3_scale(vVector, 1.0f / fLength); + } + + NVEC3 fnVEC3_calcTriangleNormal(_In_ const NVEC3 vVector1, _In_ const NVEC3 vVector2, _In_ const NVEC3 vVector3) + { + NVEC3 vVectorU = fnVEC3_sub(vVector2, vVector1); + NVEC3 vVectorV = fnVEC3_sub(vVector3, vVector1); + NVEC3 vResult = fnVEC3_crossproduct(vVectorU, vVectorV); + nfFloat fLength = fnVEC3_length(vResult); + + if (fLength > NMR_VECTOR_MINNORMALIZELENGTH) + return fnVEC3_scale(vResult, 1.0f / fLength); + else + return fnVEC3_make(0.0f, 0.0f, 0.0f); + } + + NVEC3I fnVEC3I_make(_In_ nfInt32 nX, _In_ nfInt32 nY, _In_ nfInt32 nZ) + { + NVEC3I vResult; + vResult.m_values.x = nX; + vResult.m_values.y = nY; + vResult.m_values.z = nZ; + return vResult; + } + + NVEC3I fnVEC3I_add(_In_ const NVEC3I vVector1, _In_ const NVEC3I vVector2) + { + nfInt32 j; + NVEC3I vResult; + + for (j = 0; j < 3; j++) + vResult.m_fields[j] = vVector1.m_fields[j] + vVector2.m_fields[j]; + + return vResult; + } + + NVEC3I fnVEC3I_sub(_In_ const NVEC3I vMinuend, _In_ const NVEC3I vSubtrahend) + { + nfInt32 j; + NVEC3I vResult; + + for (j = 0; j < 3; j++) + vResult.m_fields[j] = vMinuend.m_fields[j] - vSubtrahend.m_fields[j]; + + return vResult; + } + + NVEC3I fnVEC3I_scale(_In_ const NVEC3I vVector, _In_ nfInt32 vFactor) + { + nfInt32 j; + NVEC3I vResult; + + for (j = 0; j < 3; j++) + vResult.m_fields[j] = vVector.m_fields[j] * vFactor; + + return vResult; + } + + nfInt64 fnVEC3I_dotproduct(_In_ const NVEC3I vVector1, _In_ const NVEC3I vVector2) + { + nfInt64 v1x = vVector1.m_values.x; + nfInt64 v1y = vVector1.m_values.y; + nfInt64 v1z = vVector1.m_values.z; + nfInt64 v2x = vVector2.m_values.x; + nfInt64 v2y = vVector2.m_values.y; + nfInt64 v2z = vVector2.m_values.z; + return v1x * v2x + v1y * v2y + v1z * v2z; + } + + nfFloat fnVEC3I_length(_In_ const NVEC3I vVector) + { + nfInt64 vx = vVector.m_values.x; + nfInt64 vy = vVector.m_values.y; + nfInt64 vz = vVector.m_values.z; + nfInt64 dotproduct = vx * vx + vy * vy + vz * vz; + return sqrtf((nfFloat)dotproduct); + } + + nfFloat fnVEC3I_distance(_In_ const NVEC3I vPoint1, _In_ const NVEC3I vPoint2) + { + return fnVEC3I_length(fnVEC3I_sub(vPoint1, vPoint2)); + } + + nfInt32 fnVEC3I_comparelexicographic(_In_ const NVEC3I vVector1, _In_ const NVEC3I vVector2) + { + nfInt32 nResult = fnInt32_compare(vVector1.m_fields[0], vVector2.m_fields[0]); + if (nResult == 0) { + nResult = fnInt32_compare(vVector1.m_fields[1], vVector2.m_fields[1]); + if (nResult == 0) + nResult = fnInt32_compare(vVector1.m_fields[2], vVector2.m_fields[2]); + } + return nResult; + } + + nfBool fnVEC3I_iszero(_In_ const NVEC3I vVector) + { + return ((vVector.m_fields[0] == 0) && (vVector.m_fields[1] == 0) && (vVector.m_fields[2] == 0)); + } + + NVEC3I fnVEC3I_crossproduct(_In_ const NVEC3I vVector1, _In_ const NVEC3I vVector2) + { + NVEC3I vResult; + // Attention! there may be a int32 overflow + vResult.m_values.x = vVector1.m_values.y * vVector2.m_values.z - vVector1.m_values.z * vVector2.m_values.y; + vResult.m_values.y = vVector1.m_values.z * vVector2.m_values.x - vVector1.m_values.x * vVector2.m_values.z; + vResult.m_values.z = vVector1.m_values.x * vVector2.m_values.y - vVector1.m_values.y * vVector2.m_values.x; + + return vResult; + } + + NVEC3I64 fnVEC3I_crossproduct64(_In_ const NVEC3I vVector1, _In_ const NVEC3I vVector2) + { + NVEC3I64 vResult; + vResult.m_values.x = nfInt64(vVector1.m_values.y) * nfInt64(vVector2.m_values.z) - nfInt64(vVector1.m_values.z) * nfInt64(vVector2.m_values.y); + vResult.m_values.y = nfInt64(vVector1.m_values.z) * nfInt64(vVector2.m_values.x) - nfInt64(vVector1.m_values.x) * nfInt64(vVector2.m_values.z); + vResult.m_values.z = nfInt64(vVector1.m_values.x) * nfInt64(vVector2.m_values.y) - nfInt64(vVector1.m_values.y) * nfInt64(vVector2.m_values.x); + + return vResult; + } + + nfBool fnVEC3I_triangleIsDegenerate(_In_ const NVEC3I vVector1, _In_ const NVEC3I vVector2, _In_ const NVEC3I vVector3) + { + NVEC3I vU = fnVEC3I_sub(vVector2, vVector1); + NVEC3I vV = fnVEC3I_sub(vVector3, vVector1); + + NVEC3I64 vNormal = fnVEC3I_crossproduct64(vU, vV); + + return ((vNormal.m_fields[0] == 0) && (vNormal.m_fields[1] == 0) && (vNormal.m_fields[2] == 0)); + } + + NVEC3I fnVEC3I_setOrderedVector(_In_ nfInt32 nValue1, _In_ nfInt32 nValue2, _In_ nfInt32 nValue3) + { + NVEC3I vResult; + + if ((nValue1 <= nValue2) && (nValue1 <= nValue3)) { + vResult.m_fields[0] = nValue1; + if (nValue2 <= nValue3) { + vResult.m_fields[1] = nValue2; + vResult.m_fields[2] = nValue3; + } + else { + vResult.m_fields[1] = nValue3; + vResult.m_fields[2] = nValue2; + } + } + else if ((nValue2 <= nValue1) && (nValue2 <= nValue3)) { + vResult.m_fields[0] = nValue2; + if (nValue1 <= nValue3) { + vResult.m_fields[1] = nValue1; + vResult.m_fields[2] = nValue3; + } + else { + vResult.m_fields[1] = nValue3; + vResult.m_fields[2] = nValue1; + } + } + else { + vResult.m_fields[0] = nValue3; + if (nValue1 <= nValue2) { + vResult.m_fields[1] = nValue1; + vResult.m_fields[2] = nValue2; + } + else { + vResult.m_fields[1] = nValue2; + vResult.m_fields[2] = nValue1; + } + } + + return vResult; + } + + nfBool fnVEC3I_checkForCollinearity(_In_ NVEC3I vVector1, _In_ NVEC3I vVector2) + { + if (vVector1.m_fields[1] * vVector2.m_fields[2] != vVector1.m_fields[2] * vVector2.m_fields[1]) + return false; + if (vVector1.m_fields[2] * vVector2.m_fields[0] != vVector1.m_fields[0] * vVector2.m_fields[2]) + return false; + if (vVector1.m_fields[0] * vVector2.m_fields[1] != vVector1.m_fields[1] * vVector2.m_fields[0]) + return false; + // else + return true; + } + + NVEC2 operator+ (_In_ const NVEC2 vVector1, _In_ const NVEC2 vVector2) + { + return fnVEC2_add(vVector1, vVector2); + } + + NVEC2 operator- (_In_ const NVEC2 vMinuend, _In_ const NVEC2 vSubtrahend) + { + return fnVEC2_sub(vMinuend, vSubtrahend); + } + + NVEC2 operator* (_In_ const NVEC2 vVector, _In_ nfFloat vFactor) + { + return fnVEC2_scale(vVector, vFactor); + } + + NVEC2 operator* (_In_ nfFloat vFactor, _In_ const NVEC2 vVector) + { + return fnVEC2_scale(vVector, vFactor); + } + + nfFloat operator* (_In_ const NVEC2 vVector1, _In_ const NVEC2 vVector2) + { + return fnVEC2_dotproduct(vVector1, vVector2); + } + + NVEC2I operator+ (_In_ const NVEC2I vVector1, _In_ const NVEC2I vVector2) + { + return fnVEC2I_add(vVector1, vVector2); + } + + NVEC2I operator- (_In_ const NVEC2I vMinuend, _In_ const NVEC2I vSubtrahend) + { + return fnVEC2I_sub(vMinuend, vSubtrahend); + } + + NVEC2I operator* (_In_ const NVEC2I vVector, _In_ nfInt32 vFactor) + { + return fnVEC2I_scale(vVector, vFactor); + } + + NVEC2I operator* (_In_ nfInt32 vFactor, _In_ const NVEC2I vVector) + { + return fnVEC2I_scale(vVector, vFactor); + } + + nfUint64 operator* (_In_ const NVEC2I vVector1, _In_ const NVEC2I vVector2) + { + return fnVEC2I_dotproduct(vVector1, vVector2); + } + + NVEC3 operator+ (_In_ const NVEC3 vVector1, _In_ const NVEC3 vVector2) + { + return fnVEC3_add(vVector1, vVector2); + } + + NVEC3 operator- (_In_ const NVEC3 vMinuend, _In_ const NVEC3 vSubtrahend) + { + return fnVEC3_sub(vMinuend, vSubtrahend); + } + + NVEC3 operator* (_In_ const NVEC3 vVector, nfFloat vFactor) + { + return fnVEC3_scale(vVector, vFactor); + } + + NVEC3 operator* (nfFloat vFactor, _In_ const NVEC3 vVector) + { + return fnVEC3_scale(vVector, vFactor); + } + + nfFloat operator* (_In_ const NVEC3 vVector1, _In_ const NVEC3 vVector2) + { + return fnVEC3_dotproduct(vVector1, vVector2); + } + + NVEC3I operator+ (_In_ const NVEC3I vVector1, _In_ const NVEC3I vVector2) + { + return fnVEC3I_add(vVector1, vVector2); + } + + NVEC3I operator- (_In_ const NVEC3I vMinuend, _In_ const NVEC3I vSubtrahend) + { + return fnVEC3I_sub(vMinuend, vSubtrahend); + } + + NVEC3I operator* (_In_ const NVEC3I vVector, _In_ nfInt32 vFactor) + { + return fnVEC3I_scale(vVector, vFactor); + } + + NVEC3I operator* (_In_ nfInt32 vFactor, _In_ const NVEC3I vVector) + { + return fnVEC3I_scale(vVector, vFactor); + } + + nfUint64 operator* (_In_ const NVEC3I vVector1, _In_ const NVEC3I vVector2) + { + return fnVEC3I_dotproduct(vVector1, vVector2); + } + + nfInt32 fnInt32_sign(_In_ nfInt32 nValue) + { + return nValue < 0 ? -1 : nValue > 0 ? 1 : 0; + } + + nfInt32 fnInt64_sign(_In_ nfInt64 nValue) { + return nValue < 0 ? -1 : nValue > 0 ? 1 : 0; + } + + nfInt32 fnInt32_compare(_In_ nfInt32 nValue1, _In_ nfInt32 nValue2) + { + if (nValue1 > nValue2) + return 1; + else if (nValue1 < nValue2) + return -1; + else + return 0; + } + + nfInt32 fnInt64_compare(_In_ nfInt64 nValue1, _In_ nfInt64 nValue2) + { + if (nValue1 > nValue2) + return 1; + else if (nValue1 < nValue2) + return -1; + else + return 0; + } + + void fnOutboxInitialize(_Out_ NOUTBOX3 &oOutbox) + { + for (nfInt32 i = 0; i < 3; i++){ + oOutbox.m_max.m_fields[i] = -std::numeric_limits::max(); + oOutbox.m_min.m_fields[i] = std::numeric_limits::max(); + } + } + + void fnOutboxMergeVector(_Inout_ NOUTBOX3 &oOutbox, _In_ NVEC3 vVector) + { + for (nfUint32 i = 0; i < 3; i++){ + oOutbox.m_min.m_fields[i] = std::min(oOutbox.m_min.m_fields[i], vVector.m_fields[i]); + oOutbox.m_max.m_fields[i] = std::max(oOutbox.m_max.m_fields[i], vVector.m_fields[i]); + } + } + + void fnOutboxMergeOutbox(_Inout_ NOUTBOX3 &oOutboxDest, _In_ NOUTBOX3 &oOutboxSource) + { + fnOutboxMergeVector(oOutboxDest, oOutboxSource.m_max); + fnOutboxMergeVector(oOutboxDest, oOutboxSource.m_min); + } + + nfBool fnOutboxIsValid(_In_ const NOUTBOX3 oOutbox) + { + return ((fabs(oOutbox.m_min.m_values.x) < NMR_OUTBOX_MAXCOORDINATE) && + (fabs(oOutbox.m_min.m_values.y) < NMR_OUTBOX_MAXCOORDINATE) && + (fabs(oOutbox.m_min.m_values.z) < NMR_OUTBOX_MAXCOORDINATE) && + (fabs(oOutbox.m_max.m_values.x) < NMR_OUTBOX_MAXCOORDINATE) && + (fabs(oOutbox.m_max.m_values.y) < NMR_OUTBOX_MAXCOORDINATE) && + (fabs(oOutbox.m_max.m_values.z) < NMR_OUTBOX_MAXCOORDINATE)); + } + + void fnOutbox3IMergeVector(_Inout_ NOUTBOX3I &oOutbox, _In_ NVEC3I vVector) + { + for (nfUint32 i = 0; i < 3; i++) { + if (vVector.m_fields[i] < oOutbox.m_vMin.m_fields[i]) + oOutbox.m_vMin.m_fields[i] = vVector.m_fields[i]; + if (vVector.m_fields[i] > oOutbox.m_vMax.m_fields[i]) + oOutbox.m_vMax.m_fields[i] = vVector.m_fields[i]; + } + } + + void fnOutbox3IMergeOutbox(_Inout_ NOUTBOX3I &oOutboxDest, _In_ NOUTBOX3I &oOutboxSource) + { + for (nfUint32 i = 0; i < 3; i++) { + if (oOutboxSource.m_vMin.m_fields[i] < oOutboxDest.m_vMin.m_fields[i]) + oOutboxDest.m_vMin.m_fields[i] = oOutboxSource.m_vMin.m_fields[i]; + if (oOutboxSource.m_vMax.m_fields[i] > oOutboxDest.m_vMax.m_fields[i]) + oOutboxDest.m_vMax.m_fields[i] = oOutboxSource.m_vMax.m_fields[i]; + } + } + + NOUTBOX3I fnCalcTriangleOutbox3I(_In_ const NVEC3I vVector1, _In_ const NVEC3I vVector2, _In_ const NVEC3I vVector3) + { + NOUTBOX3I oOutbox; + oOutbox.m_vMin = vVector1; + oOutbox.m_vMax = vVector1; + fnOutbox3IMergeVector(oOutbox, vVector2); + fnOutbox3IMergeVector(oOutbox, vVector3); + + return oOutbox; + } + + nfBool fnOutbox3IDoIntersect(_In_ const NOUTBOX3I oOutbox1, _In_ const NOUTBOX3I oOutbox2) + { + nfBool bResult = true; + nfBool bIntervalIntersects; + for (nfUint32 i = 0; i < 3; i++) { + bIntervalIntersects = (((oOutbox1.m_vMin.m_fields[i] >= oOutbox2.m_vMin.m_fields[i]) && (oOutbox1.m_vMin.m_fields[i] <= oOutbox2.m_vMax.m_fields[i])) + || ((oOutbox1.m_vMax.m_fields[i] >= oOutbox2.m_vMin.m_fields[i]) && (oOutbox1.m_vMax.m_fields[i] <= oOutbox2.m_vMax.m_fields[i])) + || ((oOutbox2.m_vMin.m_fields[i] >= oOutbox1.m_vMin.m_fields[i]) && (oOutbox2.m_vMin.m_fields[i] <= oOutbox1.m_vMax.m_fields[i])) + || ((oOutbox2.m_vMax.m_fields[i] >= oOutbox1.m_vMin.m_fields[i]) && (oOutbox2.m_vMax.m_fields[i] <= oOutbox1.m_vMax.m_fields[i]))); + + bResult = bResult && bIntervalIntersects; + } + + return bResult; + } + +} diff --git a/Source/Common/Math/NMR_VectorTree.cpp b/Source/Common/Math/NMR_VectorTree.cpp new file mode 100644 index 0000000..e594dc8 --- /dev/null +++ b/Source/Common/Math/NMR_VectorTree.cpp @@ -0,0 +1,191 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_VectorTree.cpp implements a n*log(n) lookup tree class to identify vectors +by their position. + +--*/ + +#include "Common/Math/NMR_VectorTree.h" +#include "Common/Math/NMR_Vector.h" +#include "Common/NMR_Exception.h" +#include +#include + +namespace NMR { + + bool operator< (_In_ const VECTORTREEENTRY & entry1, _In_ const VECTORTREEENTRY & entry2) + { + for (int i = 0; i < 3; i++) { + if (entry1.m_position.m_fields[i] < entry2.m_position.m_fields[i]) + return true; + if (entry1.m_position.m_fields[i] > entry2.m_position.m_fields[i]) + return false; + } + + return false; + } + + CVectorTree::CVectorTree() + { + setUnits(NMR_VECTOR_DEFAULTUNITS); + } + + CVectorTree::CVectorTree(_In_ nfFloat fUnits) + { + setUnits(fUnits); + } + + nfFloat CVectorTree::getUnits() + { + return m_fUnits; + } + + void CVectorTree::setUnits(_In_ nfFloat fUnits) + { + if ((fUnits < NMR_VECTOR_MINUNITS) || (fUnits > NMR_VECTOR_MAXUNITS)) + throw CNMRException(NMR_ERROR_INVALIDUNITS); + if (m_entries.size() > 0) + throw CNMRException(NMR_ERROR_COULDNOTSETUNITS); + + m_fUnits = fUnits; + } + + _Success_(return) nfBool CVectorTree::findVector2(_In_ NVEC2 vVector, _Out_opt_ nfUint32 & value) + { + NVEC3 vVector3; + vVector3.m_fields[0] = vVector.m_fields[0]; + vVector3.m_fields[1] = vVector.m_fields[1]; + vVector3.m_fields[2] = 0.0f; + return findVector3(vVector3, value); + } + + _Success_(return) nfBool CVectorTree::findVector3(_In_ NVEC3 vVector, _Out_opt_ nfUint32 & value) + { + VECTORTREEENTRY entry; + entry.m_position = fnVEC3I_floor(vVector, m_fUnits); + + std::map ::iterator iter = m_entries.find(entry); + + if (iter != m_entries.end()) { + value = iter->second; + return true; + } + else + return false; + } + + _Success_(return) nfBool CVectorTree::findIntVector2(_In_ NVEC2I vVector, _Out_opt_ nfUint32 & value) + { + NVEC3I vVector3; + vVector3.m_fields[0] = vVector.m_fields[0]; + vVector3.m_fields[1] = vVector.m_fields[1]; + vVector3.m_fields[2] = 0; + return findIntVector3(vVector3, value); + } + + _Success_(return) nfBool CVectorTree::findIntVector3(_In_ NVEC3I vVector, _Out_opt_ nfUint32 & value) + { + VECTORTREEENTRY entry; + entry.m_position = vVector; + + std::map ::iterator iter = m_entries.find(entry); + + if (iter != m_entries.end()) { + value = iter->second; + return true; + } + else + return false; + } + + void CVectorTree::addVector2(_In_ NVEC2 vVector, _In_ nfUint32 value) + { + NVEC3 vVector3; + vVector3.m_fields[0] = vVector.m_fields[0]; + vVector3.m_fields[1] = vVector.m_fields[1]; + vVector3.m_fields[2] = 0.0f; + addVector3(vVector3, value); + } + + void CVectorTree::addVector3(_In_ NVEC3 vVector, _In_ nfUint32 value) + { + VECTORTREEENTRY entry; + entry.m_position = fnVEC3I_floor(vVector, m_fUnits); + m_entries.insert(std::make_pair(entry, value)); + } + + void CVectorTree::addIntVector2(_In_ NVEC2I vVector, _In_ nfUint32 value) + { + NVEC3I vVector3; + vVector3.m_fields[0] = vVector.m_fields[0]; + vVector3.m_fields[1] = vVector.m_fields[1]; + vVector3.m_fields[2] = 0; + addIntVector3(vVector3, value); + } + + void CVectorTree::addIntVector3(_In_ NVEC3I vVector, _In_ nfUint32 value) + { + VECTORTREEENTRY entry; + entry.m_position = vVector; + m_entries.insert(std::make_pair(entry, value)); + } + + void CVectorTree::removeVector2(_In_ NVEC2 vVector) + { + NVEC3 vVector3; + vVector3.m_fields[0] = vVector.m_fields[0]; + vVector3.m_fields[1] = vVector.m_fields[1]; + vVector3.m_fields[2] = 0.0f; + removeVector3(vVector3); + } + + void CVectorTree::removeVector3(_In_ NVEC3 vVector) + { + VECTORTREEENTRY entry; + entry.m_position = fnVEC3I_floor(vVector, m_fUnits); + m_entries.erase(entry); + } + + void CVectorTree::removeIntVector2(_In_ NVEC2I vVector) + { + NVEC3I vVector3; + vVector3.m_fields[0] = vVector.m_fields[0]; + vVector3.m_fields[1] = vVector.m_fields[1]; + vVector3.m_fields[2] = 0; + removeIntVector3(vVector3); + } + + void CVectorTree::removeIntVector3(_In_ NVEC3I vVector) + { + VECTORTREEENTRY entry; + entry.m_position = vVector; + m_entries.erase(entry); + } + +} diff --git a/Source/Common/Mesh/NMR_BeamLattice.cpp b/Source/Common/Mesh/NMR_BeamLattice.cpp new file mode 100644 index 0000000..ae5a4f1 --- /dev/null +++ b/Source/Common/Mesh/NMR_BeamLattice.cpp @@ -0,0 +1,59 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_MeshBeamLattice.h implements the class CMeshBeamLattice. + +--*/ + +#include "Common/Mesh/NMR_BeamLattice.h" + +namespace NMR { + + CBeamLattice::CBeamLattice(_In_ MESHNODES &nodes) : m_Nodes(nodes) + { + m_dMinLength = 0.0001; + m_eBallMode = eModelBeamLatticeBallMode::MODELBEAMLATTICEBALLMODE_NONE; + m_dDefaultBallRadius = 0.0; + } + + void CBeamLattice::clearBeams() { + m_Beams.clearAllData(); + m_pBeamSets.clear(); + m_OccupiedNodes.clear(); + } + + void CBeamLattice::clearBalls() { + m_Balls.clearAllData(); + } + + void CBeamLattice::clear() { + clearBeams(); + clearBalls(); + } + +} diff --git a/Source/Common/Mesh/NMR_Mesh.cpp b/Source/Common/Mesh/NMR_Mesh.cpp new file mode 100644 index 0000000..b02d3dc --- /dev/null +++ b/Source/Common/Mesh/NMR_Mesh.cpp @@ -0,0 +1,613 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_Mesh.cpp implements the class CMesh. + +The class CMesh is not really a mesh, since it lacks the component edges and the +topological information. It only holds the nodes and the faces (triangles). +Each node, and face have a ID, which allows to identify them. Each face have an +orientation (i.e. the face can look up or look down) and have three nodes. +The orientation is defined by the order of its nodes. + +You can only add nodes and faces to mesh. You cannot remove the existing +structure. + +--*/ + +#include "Common/Mesh/NMR_Mesh.h" +#include "Common/Math/NMR_Matrix.h" +#include "Common/NMR_Exception.h" +#include "Common/MeshInformation/NMR_MeshInformation_Properties.h" +#include + +namespace NMR { + + CMesh::CMesh(): m_BeamLattice(this->m_Nodes) + { + // empty on purpose + } + + CMesh::CMesh(_In_opt_ CMesh * pMesh) : m_BeamLattice(this->m_Nodes) + { + if (!pMesh) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + mergeMesh(pMesh); + } + + void CMesh::mergeMesh(_In_opt_ CMesh * pMesh) + { + mergeMesh(pMesh, fnMATRIX3_identity()); + } + + void CMesh::mergeMesh(_In_opt_ CMesh * pMesh, _In_ NMATRIX3 mMatrix) + { + if (!pMesh) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + nfInt32 nIdx, nNodeCount, nFaceCount, nBeamCount, nBallCount, j; + MESHNODE * pNode; + MESHFACE * pFace; + MESHBEAM * pBeam; + MESHBALL * pBall; + MESHNODE * pFaceNodes[3]; + MESHNODE * pBeamNodes[2]; + MESHNODE * pBallNode; + + // Copy Mesh Information + CMeshInformationHandler * pOtherMeshInformationHandler = pMesh->getMeshInformationHandler(); + if (pOtherMeshInformationHandler) { + createMeshInformationHandler(); + m_pMeshInformationHandler->addInfoTableFrom(pOtherMeshInformationHandler, getFaceCount ()); + } + + nNodeCount = pMesh->getNodeCount(); + nFaceCount = pMesh->getFaceCount(); + nBeamCount = pMesh->getBeamCount(); + nBallCount = pMesh->getBallCount(); + + if (nNodeCount > 0) { + std::vector aNewNodes; + aNewNodes.resize(nNodeCount); + + for (nIdx = 0; nIdx < nNodeCount; nIdx++) { + pNode = pMesh->getNode(nIdx); + NVEC3 vPosition = fnMATRIX3_apply(mMatrix, pNode->m_position); + aNewNodes[nIdx] = addNode(vPosition); + } + + if (nFaceCount > 0) { + if (m_pMeshInformationHandler && pOtherMeshInformationHandler) { + m_pMeshInformationHandler->cloneDefaultInfosFrom(pOtherMeshInformationHandler); + } + + for (nIdx = 0; nIdx < nFaceCount; nIdx++) { + pFace = pMesh->getFace(nIdx); + for (j = 0; j < 3; j++) { + if ((pFace->m_nodeindices[j] < 0) || (pFace->m_nodeindices[j] >= nNodeCount)) + throw CNMRException(NMR_ERROR_INVALIDNODEINDEX); + + pFaceNodes[j] = aNewNodes[pFace->m_nodeindices[j]]; + } + + MESHFACE * pNewFace = addFace(pFaceNodes[0], pFaceNodes[1], pFaceNodes[2]); + if (m_pMeshInformationHandler && pOtherMeshInformationHandler) { + m_pMeshInformationHandler->cloneFaceInfosFrom(pNewFace->m_index, pOtherMeshInformationHandler, pFace->m_index); + } + } + } + if (nBeamCount > 0) { + for (nIdx = 0; nIdx < nBeamCount; nIdx++) { + pBeam = pMesh->getBeam(nIdx); + for (j = 0; j < 2; j++) { + if ((pBeam->m_nodeindices[j] < 0) || (pBeam->m_nodeindices[j] >= nNodeCount)) + throw CNMRException(NMR_ERROR_INVALIDNODEINDEX); + + pBeamNodes[j] = aNewNodes[pBeam->m_nodeindices[j]]; + } + addBeam(pBeamNodes[0], pBeamNodes[1], pBeam->m_radius[0], pBeam->m_radius[1], pBeam->m_capMode[0], pBeam->m_capMode[1]); + } + } + if (nBallCount > 0) { + for (nIdx = 0; nIdx < nBallCount; nIdx++) { + pBall = pMesh->getBall(nIdx); + if ((pBall->m_nodeindex < 0) || (pBall->m_nodeindex >= nNodeCount)) + throw CNMRException(NMR_ERROR_INVALIDNODEINDEX); + + pBallNode = aNewNodes[pBall->m_nodeindex]; + addBall(pBallNode, pBall->m_radius); + } + } + + } + } + + void CMesh::addToMesh(_In_opt_ CMesh * pMesh) + { + if (!pMesh) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + pMesh->mergeMesh(this, fnMATRIX3_identity()); + } + + void CMesh::addToMesh(_In_opt_ CMesh * pMesh, _In_ NMATRIX3 mMatrix) + { + if (!pMesh) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + pMesh->mergeMesh(this, mMatrix); + } + + _Ret_notnull_ MESHNODE * CMesh::addNode(_In_ const NVEC3 vPosition) + { + MESHNODE * pNode; + nfUint32 j; + + // Check Position Validity + for (j = 0; j < 3; j++) + if (fabs(vPosition.m_fields[j]) > NMR_MESH_MAXCOORDINATE) + throw CNMRException(NMR_ERROR_INVALIDCOORDINATES); + + // Check Node Quota + nfUint32 nNodeCount = getNodeCount(); + if (nNodeCount >= NMR_MESH_MAXNODECOUNT) + throw CNMRException(NMR_ERROR_TOOMANYNODES); + + // Allocate Data + nfUint32 nNewIndex; + pNode = m_Nodes.allocData(nNewIndex); + pNode->m_index = nNewIndex; + pNode->m_position = vPosition; + + return pNode; + } + _Ret_notnull_ MESHNODE * CMesh::addNode(_In_ const nfFloat posX, _In_ const nfFloat posY, _In_ const nfFloat posZ) + { + MESHNODE * pNode; + + // Check Position Validity + if (fabs(posX) > NMR_MESH_MAXCOORDINATE) + throw CNMRException(NMR_ERROR_INVALIDCOORDINATES); + if (fabs(posY) > NMR_MESH_MAXCOORDINATE) + throw CNMRException(NMR_ERROR_INVALIDCOORDINATES); + if (fabs(posZ) > NMR_MESH_MAXCOORDINATE) + throw CNMRException(NMR_ERROR_INVALIDCOORDINATES); + + // Check Node Quota + nfUint32 nNodeCount = getNodeCount(); + if (nNodeCount >= NMR_MESH_MAXNODECOUNT) + throw CNMRException(NMR_ERROR_TOOMANYNODES); + + // Allocate Data + nfUint32 nNewIndex; + pNode = m_Nodes.allocData(nNewIndex); + pNode->m_index = nNewIndex; + pNode->m_position.m_values.x = posX; + pNode->m_position.m_values.y = posY; + pNode->m_position.m_values.z = posZ; + + return pNode; + } + + _Ret_notnull_ MESHFACE * CMesh::addFace(_In_ MESHNODE * pNode1, _In_ MESHNODE * pNode2, _In_ MESHNODE * pNode3) + { + if ((!pNode1) || (!pNode2) || (!pNode3)) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + if ((pNode1 == pNode2) || (pNode1 == pNode3) || (pNode2 == pNode3)) + throw CNMRException(NMR_ERROR_DUPLICATENODE); + + MESHFACE * pFace; + nfUint32 nFaceCount = getFaceCount (); + + if (nFaceCount >= NMR_MESH_MAXFACECOUNT) + throw CNMRException(NMR_ERROR_TOOMANYFACES); + + nfUint32 nNewIndex = 0; + + pFace = m_Faces.allocData (nNewIndex); + pFace->m_nodeindices[0] = pNode1->m_index; + pFace->m_nodeindices[1] = pNode2->m_index; + pFace->m_nodeindices[2] = pNode3->m_index; + pFace->m_index = nNewIndex; + + if (m_pMeshInformationHandler) + m_pMeshInformationHandler->addFace(getFaceCount()); + + return pFace; + } + + _Ret_notnull_ MESHFACE * CMesh::addFace(_In_ nfInt32 nNodeIndex1, _In_ nfInt32 nNodeIndex2, _In_ nfInt32 nNodeIndex3) + { + if ((nNodeIndex1 == nNodeIndex2) || (nNodeIndex1 == nNodeIndex3) || (nNodeIndex2 == nNodeIndex3)) + throw CNMRException(NMR_ERROR_DUPLICATENODE); + + MESHFACE * pFace; + nfUint32 nFaceCount = getFaceCount(); + + if (nFaceCount >= NMR_MESH_MAXFACECOUNT) + throw CNMRException(NMR_ERROR_TOOMANYFACES); + + nfUint32 nNewIndex; + + pFace = m_Faces.allocData(nNewIndex); + pFace->m_nodeindices[0] = nNodeIndex1; + pFace->m_nodeindices[1] = nNodeIndex2; + pFace->m_nodeindices[2] = nNodeIndex3; + pFace->m_index = nNewIndex; + + if (m_pMeshInformationHandler) + m_pMeshInformationHandler->addFace(getFaceCount()); + + return pFace; + } + + _Ret_notnull_ MESHBEAM * CMesh::addBeam(_In_ MESHNODE * pNode1, _In_ MESHNODE * pNode2, + _In_ nfDouble dRadius1, _In_ nfDouble dRadius2, + _In_ nfInt32 eCapMode1, _In_ nfInt32 eCapMode2) + { + if ((!pNode1) || (!pNode2)) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + if (pNode1 == pNode2) + throw CNMRException(NMR_ERROR_DUPLICATENODE); + + MESHBEAM * pBeam; + nfUint32 nBeamCount = getBeamCount(); + + if (nBeamCount >= NMR_MESH_MAXBEAMCOUNT) + throw CNMRException(NMR_ERROR_TOOMANYBEAMS); + + nfUint32 nNewIndex; + + pBeam = m_BeamLattice.m_Beams.allocData(nNewIndex); + pBeam->m_nodeindices[0] = pNode1->m_index; + pBeam->m_nodeindices[1] = pNode2->m_index; + pBeam->m_index = nNewIndex; + pBeam->m_radius[0] = dRadius1; + pBeam->m_radius[1] = dRadius2; + + pBeam->m_capMode[0] = eCapMode1; + pBeam->m_capMode[1] = eCapMode2; + + m_BeamLattice.m_OccupiedNodes.insert({ pNode1->m_index, pNode2->m_index }); + + return pBeam; + } + + PBEAMSET CMesh::addBeamSet() + { + m_BeamLattice.m_pBeamSets.push_back(std::make_shared()); + return m_BeamLattice.m_pBeamSets.back(); + } + + _Ret_notnull_ MESHBALL * CMesh::addBall(_In_ MESHNODE * pNode, _In_ nfDouble dRadius) + { + if ((!pNode)) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + MESHBALL * pBall; + nfUint32 nBallCount = getBallCount(); + + if (nBallCount >= NMR_MESH_MAXBALLCOUNT) + throw CNMRException(NMR_ERROR_TOOMANYBALLS); + + // Ensure that at least one beam exists at this node + if (m_BeamLattice.m_OccupiedNodes.find(pNode->m_index) == m_BeamLattice.m_OccupiedNodes.end()) { + throw CNMRException(NMR_ERROR_INVALIDPARAM); + } + + nfUint32 nNewIndex; + + pBall = m_BeamLattice.m_Balls.allocData(nNewIndex); + pBall->m_nodeindex = pNode->m_index; + pBall->m_index = nNewIndex; + pBall->m_radius = dRadius; + + return pBall; + } + + + nfUint32 CMesh::getNodeCount() { + return m_Nodes.getCount (); + } + + nfUint32 CMesh::getFaceCount() + { + return m_Faces.getCount (); + } + + nfUint32 CMesh::getBeamCount() + { + return m_BeamLattice.m_Beams.getCount(); + } + + nfUint32 CMesh::getBeamSetCount() + { + return (nfUint32)(m_BeamLattice.m_pBeamSets.size()); + } + + nfUint32 CMesh::getBallCount() + { + return m_BeamLattice.m_Balls.getCount(); + } + + nfUint32 CMesh::getOccupiedNodeCount() + { + return (nfUint32)m_BeamLattice.m_OccupiedNodes.size(); + } + + nfBool CMesh::isNodeOccupied(_In_ nfUint32 nIdx) + { + return m_BeamLattice.m_OccupiedNodes.find(nIdx) != m_BeamLattice.m_OccupiedNodes.end(); + } + + _Ret_notnull_ MESHNODE * CMesh::getNode(_In_ nfUint32 nIdx) + { + return m_Nodes.getData(nIdx); + } + + _Ret_notnull_ MESHFACE * CMesh::getFace(_In_ nfUint32 nIdx) + { + return m_Faces.getData(nIdx); + } + + _Ret_notnull_ MESHBEAM * CMesh::getBeam(_In_ nfUint32 nIdx) + { + return m_BeamLattice.m_Beams.getData(nIdx); + } + + _Ret_notnull_ PBEAMSET CMesh::getBeamSet(_In_ nfUint32 nIdx) + { + if (nIdx >= m_BeamLattice.m_pBeamSets.size()) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + return m_BeamLattice.m_pBeamSets[nIdx]; + } + + _Ret_notnull_ MESHBALL * CMesh::getBall(_In_ nfUint32 nIdx) + { + return m_BeamLattice.m_Balls.getData(nIdx); + } + + _Ret_notnull_ MESHNODE * CMesh::getOccupiedNode(_In_ nfUint32 nIdx) + { + std::unordered_set::iterator iter = m_BeamLattice.m_OccupiedNodes.begin(); + std::advance(iter, nIdx); + return getNode(*iter); + } + + void CMesh::setBeamLatticeMinLength(nfDouble dMinLength) + { + m_BeamLattice.m_dMinLength = dMinLength; + } + + nfDouble CMesh::getBeamLatticeMinLength() + { + return m_BeamLattice.m_dMinLength; + } + + nfDouble CMesh::getDefaultBeamRadius() + { + return 1.0; + } + + void CMesh::setDefaultBallRadius(nfDouble dDefaultBallRadius) + { + m_BeamLattice.m_dDefaultBallRadius = dDefaultBallRadius; + } + + nfDouble CMesh::getDefaultBallRadius() + { + return m_BeamLattice.m_dDefaultBallRadius; + } + + nfBool CMesh::getBeamLatticeAccuracy(nfDouble& dAccuracy) + { + dAccuracy = 1.0; + return false; + } + + void CMesh::setBeamLatticeBallMode(eModelBeamLatticeBallMode eBallMode) + { + m_BeamLattice.m_eBallMode = eBallMode; + } + + eModelBeamLatticeBallMode CMesh::getBeamLatticeBallMode() + { + return m_BeamLattice.m_eBallMode; + } + + eModelBeamLatticeCapMode CMesh::getBeamLatticeCapMode() + { + return eModelBeamLatticeCapMode::MODELBEAMLATTICECAPMODE_SPHERE; + } + + nfBool CMesh::checkSanity() + { + nfUint32 nIdx, j; + + nfUint32 nNodeCount = getNodeCount(); + nfUint32 nFaceCount = getFaceCount(); + nfUint32 nBeamCount = getBeamCount(); + nfUint32 nBallCount = getBallCount(); + + // max 2^31-1 billion Nodes/Faces + if (nNodeCount > NMR_MESH_MAXNODECOUNT) + return false; + if (nFaceCount > NMR_MESH_MAXFACECOUNT) + return false; + if (nBeamCount > NMR_MESH_MAXBEAMCOUNT) + return false; + if (nBallCount > NMR_MESH_MAXBALLCOUNT) + return false; + + for (nIdx = 0; nIdx < nNodeCount; nIdx++) { + MESHNODE * node = getNode(nIdx); + if (node->m_index != (nfInt32) nIdx) + return false; + for (j = 0; j < 3; j++) + if (fabs(node->m_position.m_fields[j]) > NMR_MESH_MAXCOORDINATE) + return false; + } + + for (nIdx = 0; nIdx < nFaceCount; nIdx++) { + MESHFACE * face = getFace(nIdx); + for (j = 0; j < 3; j++) + if ((face->m_nodeindices[j] < 0) || (((nfUint32)face->m_nodeindices[j]) >= nNodeCount)) + return false; + + if ((face->m_nodeindices[0] == face->m_nodeindices[1]) || + (face->m_nodeindices[0] == face->m_nodeindices[2]) || + (face->m_nodeindices[1] == face->m_nodeindices[2])) + return false; + } + + for (nIdx = 0; nIdx < nBeamCount; nIdx++) { + MESHBEAM * beam = getBeam(nIdx); + for (j = 0; j < 2; j++) + if ((beam->m_nodeindices[j] < 0) || (((nfUint32)beam->m_nodeindices[j]) >= nNodeCount)) + return false; + + if (beam->m_nodeindices[0] == beam->m_nodeindices[1]) + return false; + } + + for (nIdx = 0; nIdx < nBallCount; nIdx++) { + MESHBALL* ball = getBall(nIdx); + if ((ball->m_nodeindex < 0) || (((nfUint32)ball->m_nodeindex) >= nNodeCount)) + return false; + } + return true; + } + + void CMesh::clear() + { + m_pMeshInformationHandler.reset(); + m_Faces.clearAllData(); + m_Nodes.clearAllData(); + clearBeamLattice(); + } + + void CMesh::clearBeamLattice() { + m_BeamLattice.clear(); + } + + void CMesh::clearBeamLatticeBeams() { + m_BeamLattice.clearBeams(); + } + + void CMesh::clearBeamLatticeBalls() { + m_BeamLattice.clearBalls(); + } + + void CMesh::scanOccupiedNodes() { + m_BeamLattice.m_OccupiedNodes.clear(); + + nfUint32 beamCount = m_BeamLattice.m_Beams.getCount(); + for (nfUint32 iBeam = 0; iBeam < beamCount; iBeam++) { + MESHBEAM * meshBeam = getBeam(iBeam); + m_BeamLattice.m_OccupiedNodes.insert({ meshBeam->m_nodeindices[0], meshBeam->m_nodeindices[1] }); + } + } + + void CMesh::validateBeamLatticeBalls() { + nfUint32 ballCount = m_BeamLattice.m_Balls.getCount(); + MESHBALL * ballData = new MESHBALL[ballCount]; + for (nfUint32 iBall = 0; iBall < ballCount; iBall++) { + ballData[iBall] = *m_BeamLattice.m_Balls.getData(iBall); + } + + clearBeamLatticeBalls(); + for (nfUint32 iBall = 0; iBall < ballCount; iBall++) { + try { + addBall(getNode(ballData[iBall].m_nodeindex), ballData[iBall].m_radius); + } + catch (CNMRException) {} + } + + delete [] ballData; + } + + void CMesh::clearMeshInformationHandler() + { + m_pMeshInformationHandler.reset(); + } + + void CMesh::patchMeshInformationResources(_In_ std::map &oldToNewMapping) + { + NMR::CMeshInformationHandler *pMeshInformationHandler = this->getMeshInformationHandler(); + if (pMeshInformationHandler) { + NMR::CMeshInformation *pProperties = dynamic_cast(pMeshInformationHandler->getInformationByType(0, NMR::emiProperties)); + if (pProperties) { + NMR::MESHINFORMATION_PROPERTIES * pDefaultData = (NMR::MESHINFORMATION_PROPERTIES*)pProperties->getDefaultData(); + if (pDefaultData && pDefaultData->m_nUniqueResourceID != 0) { + NMR::UniqueResourceID nNewResourceID = oldToNewMapping[pDefaultData->m_nUniqueResourceID]; + if (nNewResourceID == 0) + throw CNMRException(NMR_ERROR_UNKNOWNMODELRESOURCE); + pDefaultData->m_nUniqueResourceID = nNewResourceID; + } + for (NMR::nfUint32 nFaceIndex = 0; nFaceIndex < this->getFaceCount(); nFaceIndex++) { + NMR::MESHINFORMATION_PROPERTIES * pFaceData = (NMR::MESHINFORMATION_PROPERTIES*)pProperties->getFaceData(nFaceIndex); + if (pFaceData && pFaceData->m_nUniqueResourceID != 0) { + NMR::UniqueResourceID nNewResourceID = oldToNewMapping[pFaceData->m_nUniqueResourceID]; + if (nNewResourceID == 0) + throw CNMRException(NMR_ERROR_UNKNOWNMODELRESOURCE); + pFaceData->m_nUniqueResourceID = nNewResourceID; + } + } + } + } + } + + _Ret_maybenull_ CMeshInformationHandler * CMesh::getMeshInformationHandler() + { + return m_pMeshInformationHandler.get(); + } + + _Ret_notnull_ CMeshInformationHandler * CMesh::createMeshInformationHandler() + { + if (!m_pMeshInformationHandler) + m_pMeshInformationHandler = std::make_shared(); + + return m_pMeshInformationHandler.get(); + } + + void CMesh::extendOutbox(_Out_ NOUTBOX3& vOutBox, _In_ const NMATRIX3 mAccumulatedMatrix) + { + if (fnMATRIX3_isIdentity(mAccumulatedMatrix)) { + for (nfUint32 iNode = 0; iNode < getNodeCount(); iNode++) { + fnOutboxMergeVector(vOutBox, getNode(iNode)->m_position); + } + } + else { + for (nfUint32 iNode = 0; iNode < getNodeCount(); iNode++) { + fnOutboxMergeVector(vOutBox, fnMATRIX3_apply(mAccumulatedMatrix, getNode(iNode)->m_position)); + } + } + } +} diff --git a/Source/Common/Mesh/NMR_MeshBuilder.cpp b/Source/Common/Mesh/NMR_MeshBuilder.cpp new file mode 100644 index 0000000..1fa8fd4 --- /dev/null +++ b/Source/Common/Mesh/NMR_MeshBuilder.cpp @@ -0,0 +1,125 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_MeshBuilder.cpp implements the class CMeshBuilder. + +The class CMeshBuilder is auxiliary class, which construct a valid mesh by adding single faces and nodes. +In addition already existing meshes can be added. + +--*/ + +#include "Common/Mesh/NMR_MeshBuilder.h" +#include "Common/NMR_Exception.h" +#include + +namespace NMR { + + CMeshBuilder::CMeshBuilder() + { + // empty on purpose + } + + CMeshBuilder::CMeshBuilder(_In_ nfFloat fUnits) + { + m_VectorTree.setUnits(fUnits); + } + + nfUint32 CMeshBuilder::addNode(_In_ const NVEC3 vPoint) + { + nfUint32 nIdx; + + if (m_VectorTree.findVector3(vPoint, nIdx)) + return nIdx; + + NVEC3 * pPoint = m_Nodes.allocData(nIdx); + pPoint->m_values = vPoint.m_values; + + m_VectorTree.addVector3(vPoint, nIdx); + + return nIdx; + } + + nfUint32 CMeshBuilder::addFace(_In_ const NVEC3 vPoint1, _In_ const NVEC3 vPoint2, _In_ const NVEC3 vPoint3) + { + NVEC3I vFaceVec; + vFaceVec.m_fields[0] = addNode(vPoint1); + vFaceVec.m_fields[1] = addNode(vPoint2); + vFaceVec.m_fields[2] = addNode(vPoint3); + + nfUint32 nIdx; + NVEC3I * pFace = m_Faces.allocData (nIdx); + *pFace = vFaceVec; + + return nIdx; + } + + PMesh CMeshBuilder::createMesh(_In_ nfBool bIgnoreInvalidFaces) + { + PMesh pResult (new CMesh); + addToMesh(pResult.get(), bIgnoreInvalidFaces); + + return pResult; + } + + void CMeshBuilder::addToMesh(_In_ CMesh * pMesh, _In_ nfBool bIgnoreInvalidFaces) + { + nfUint32 nIdx, j; + if (!pMesh) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + std::vector pNodes; + + nfUint32 nNodeCount = m_Nodes.getCount(); + nfUint32 nFaceCount = m_Faces.getCount(); + pNodes.resize(nNodeCount); + + for (nIdx = 0; nIdx < nNodeCount; nIdx++) { + NVEC3 * pPosition = m_Nodes.getData(nIdx); + pNodes[nIdx] = pMesh->addNode(*pPosition); + } + + for (nIdx = 0; nIdx < nFaceCount; nIdx++) { + NVEC3I * pFaceVec = m_Faces.getData(nIdx); + MESHNODE * pNewNodes[3]; + + for (j = 0; j < 3; j++) { + pNewNodes[j] = pNodes[pFaceVec->m_fields[j]]; + } + + if ((pNewNodes[0] == pNewNodes[1]) || (pNewNodes[0] == pNewNodes[2]) || (pNewNodes[1] == pNewNodes[2])) { + if (!bIgnoreInvalidFaces) + throw CNMRException(NMR_ERROR_DUPLICATENODE); + + } + else { + pMesh->addFace(pNewNodes[0], pNewNodes[1], pNewNodes[2]); + } + } + } + +} diff --git a/Source/Common/MeshExport/NMR_MeshExportEdgeMap.cpp b/Source/Common/MeshExport/NMR_MeshExportEdgeMap.cpp new file mode 100644 index 0000000..f92dbd2 --- /dev/null +++ b/Source/Common/MeshExport/NMR_MeshExportEdgeMap.cpp @@ -0,0 +1,64 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_MeshExportEdgeMap.cpp implements the Mesh Export Edge Map Class. +This class acts as a container for additional topology information. + +--*/ + +#include "Common/MeshExport/NMR_MeshExportEdgeMap.h" +#include "Common/NMR_Exception.h" +#include + +namespace NMR { + + CMeshExportEdgeMap::CMeshExportEdgeMap(nfUint32 nFaceCount) + { + nfUint32 nIdx; + m_FaceInfos.resize(nFaceCount); + + NMESHEXPORTFACE ExportFace; + ExportFace.m_edgeindices[0] = -1; + ExportFace.m_edgeindices[1] = -1; + ExportFace.m_edgeindices[2] = -1; + + for (nIdx = 0; nIdx < nFaceCount; nIdx++) + m_FaceInfos[nIdx] = ExportFace; + } + + NMESHEXPORTFACE CMeshExportEdgeMap::getFaceData(_In_ nfInt32 nIdx) + { + return m_FaceInfos[nIdx]; + } + + void CMeshExportEdgeMap::setFaceData(_In_ nfInt32 nIdx, _In_ NMESHEXPORTFACE ExportFace) + { + m_FaceInfos[nIdx] = ExportFace; + } + +} diff --git a/Source/Common/MeshExport/NMR_MeshExporter.cpp b/Source/Common/MeshExport/NMR_MeshExporter.cpp new file mode 100644 index 0000000..aa7a4f5 --- /dev/null +++ b/Source/Common/MeshExport/NMR_MeshExporter.cpp @@ -0,0 +1,65 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_MeshExporter.cpp implements the Mesh Exporter Class. +This is an abstract base class for exporting different Mesh Formats. + +--*/ + +#include "Common/MeshExport/NMR_MeshExporter.h" +#include "Common/NMR_Exception.h" +#include + +namespace NMR { + + CMeshExporter::CMeshExporter() + { + // empty on purpose + } + + CMeshExporter::CMeshExporter(_In_ PExportStream pStream) + { + setStream(pStream); + } + + void CMeshExporter::setStream(_In_ PExportStream pStream) + { + m_stream = pStream; + } + + CExportStream * CMeshExporter::getStream() + { + return m_stream.get(); + } + + void CMeshExporter::exportMesh(_In_ CMesh * pMesh, _In_opt_ NMATRIX3 * pmMatrix) + { + exportMeshEx(pMesh, pmMatrix, nullptr); + } + +} diff --git a/Source/Common/MeshExport/NMR_MeshExporter_STL.cpp b/Source/Common/MeshExport/NMR_MeshExporter_STL.cpp new file mode 100644 index 0000000..886cab9 --- /dev/null +++ b/Source/Common/MeshExport/NMR_MeshExporter_STL.cpp @@ -0,0 +1,121 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_MeshExporter_STL.cpp implements the Mesh Exporter Class. +This is a derived class for Exporting the binary STL and color STL Mesh Format. + +--*/ + +#include "Common/MeshExport/NMR_MeshExporter_STL.h" +#include "Common/MeshImport/NMR_MeshImporter_STL.h" +#include "Common/Math/NMR_Matrix.h" +#include "Common/Math/NMR_Vector.h" +#include "Common/NMR_Exception.h" +#include +#include + +namespace NMR { + + CMeshExporter_STL::CMeshExporter_STL() : CMeshExporter() + { + // empty on purpose + } + + CMeshExporter_STL::CMeshExporter_STL(PExportStream pStream) : CMeshExporter(pStream) + { + // empty on purpose + } + + void CMeshExporter_STL::exportMeshEx(_In_ CMesh * pMesh, _In_opt_ NMATRIX3 * pmMatrix, _In_opt_ CMeshExportEdgeMap * pExportEdgeMap) + { + if (!pMesh) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + CExportStream * pStream = getStream(); + if (!pStream) + throw CNMRException(NMR_ERROR_NOEXPORTSTREAM); + + nfUint32 nIdx, j; + nfUint32 nFaceCount = pMesh->getFaceCount(); + MESHFACE * face; + MESHNODE * node; + + MESHFORMAT_STL_FACET facet; + std::list facetdata; + + for (nIdx = 0; nIdx < nFaceCount; nIdx++) { + + face = pMesh->getFace(nIdx); + for (j = 0; j < 3; j++) { + node = pMesh->getNode (face->m_nodeindices[j]); + if (pmMatrix) + facet.m_vertices[j] = fnMATRIX3_apply(*pmMatrix, node->m_position); + else + facet.m_vertices[j] = node->m_position; + } + + // Calculate Triangle Normals + facet.m_normal = fnVEC3_calcTriangleNormal(facet.m_vertices[0], facet.m_vertices[1], facet.m_vertices[2]); + facet.m_attribute = 0; + + facetdata.push_back(facet); + } + + nfByte stlheader[80]; + char HeaderMessage[34] = "STL Export by Lib3MF"; + nfUint32 nFacetCount = (nfUint32) facetdata.size(); + + // Fill Header + for (nIdx = 0; nIdx < 33; nIdx++) + stlheader[nIdx] = (nfByte)HeaderMessage[nIdx]; + for (nIdx = 33; nIdx < 80; nIdx++) + stlheader[nIdx] = 32; + + // Write Header + pStream->writeBuffer(&stlheader[0], 80); + if (isBigEndian()) + nFacetCount = swapBytes(nFacetCount); + pStream->writeBuffer(&nFacetCount, sizeof (nFacetCount)); + + std::list::iterator iter; + if (isBigEndian()) { + MESHFORMAT_STL_FACET tmpFacet; + for (iter = facetdata.begin(); iter != facetdata.end(); iter++) { + tmpFacet = *iter; + tmpFacet.swapByteOrder(); + pStream->writeBuffer(&tmpFacet, sizeof(MESHFORMAT_STL_FACET)); + } + } + else { + for (iter = facetdata.begin(); iter != facetdata.end(); iter++) { + pStream->writeBuffer(&(*iter), sizeof(MESHFORMAT_STL_FACET)); + } + } + } + +} diff --git a/Source/Common/MeshImport/NMR_MeshImporter.cpp b/Source/Common/MeshImport/NMR_MeshImporter.cpp new file mode 100644 index 0000000..6e2aba0 --- /dev/null +++ b/Source/Common/MeshImport/NMR_MeshImporter.cpp @@ -0,0 +1,60 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_MeshImporter.cpp implements the Mesh Importer Class. +This is an abstract base class for Importing different Mesh Formats. + +--*/ + +#include "Common/MeshImport/NMR_MeshImporter.h" +#include "Common/NMR_Exception.h" +#include + +namespace NMR { + + CMeshImporter::CMeshImporter() + { + // empty on purpose + } + + CMeshImporter::CMeshImporter(_In_ PImportStream pStream) + { + setStream(pStream); + } + + void CMeshImporter::setStream(_In_ PImportStream pStream) + { + m_pStream = pStream; + } + + CImportStream * CMeshImporter::getStream() + { + return m_pStream.get(); + } + +} diff --git a/Source/Common/MeshImport/NMR_MeshImporter_STL.cpp b/Source/Common/MeshImport/NMR_MeshImporter_STL.cpp new file mode 100644 index 0000000..f99bbdf --- /dev/null +++ b/Source/Common/MeshImport/NMR_MeshImporter_STL.cpp @@ -0,0 +1,209 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_MeshImporter_STL.cpp implements the Mesh Importer Class. +This is a derived class for Importing the binary STL and color STL Mesh Format. + +--*/ + +#include "Common/MeshImport/NMR_MeshImporter_STL.h" +#include "Common/MeshInformation/NMR_MeshInformation.h" +#include "Common/MeshInformation/NMR_MeshInformation_Properties.h" +#include "Common/Math/NMR_VectorTree.h" +#include "Common/Math/NMR_Matrix.h" +#include "Common/NMR_Exception.h" +#include +#include +#include + +namespace NMR { + + CMeshImporter_STL::CMeshImporter_STL() : CMeshImporter() + { + setUnits(NMR_VECTOR_DEFAULTUNITS); + setIgnoreInvalidFaces(true); + setImportColors(false); + } + + CMeshImporter_STL::CMeshImporter_STL(_In_ PImportStream pStream) : CMeshImporter(pStream) + { + setUnits(NMR_VECTOR_DEFAULTUNITS); + setIgnoreInvalidFaces(true); + setImportColors(false); + } + + CMeshImporter_STL::CMeshImporter_STL(_In_ PImportStream pStream, _In_ nfFloat fUnits) : CMeshImporter(pStream) + { + setUnits(fUnits); + setIgnoreInvalidFaces(true); + setImportColors(false); + } + + CMeshImporter_STL::CMeshImporter_STL(_In_ PImportStream pStream, _In_ nfFloat fUnits, _In_ nfBool bImportColors) : CMeshImporter(pStream) + { + setUnits(fUnits); + setIgnoreInvalidFaces(true); + setImportColors(bImportColors); + } + + void CMeshImporter_STL::setUnits(_In_ nfFloat fUnits) + { + if ((fUnits < NMR_VECTOR_MINUNITS) || (fUnits > NMR_VECTOR_MAXUNITS)) + throw CNMRException(NMR_ERROR_INVALIDUNITS); + + m_fUnits = fUnits; + } + + nfFloat CMeshImporter_STL::getUnits() + { + return m_fUnits; + } + + void CMeshImporter_STL::setIgnoreInvalidFaces(_In_ nfBool bIgnoreInvalidFaces) + { + m_bIgnoreInvalidFaces = bIgnoreInvalidFaces; + } + + nfBool CMeshImporter_STL::getIgnoreInvalidFaces() + { + return m_bIgnoreInvalidFaces; + } + + void CMeshImporter_STL::setImportColors(_In_ nfBool bImportColors) + { + m_bImportColors = bImportColors; + } + + nfBool CMeshImporter_STL::getImportColors() + { + return m_bImportColors; + } + + void CMeshImporter_STL::loadMesh(_In_ CMesh * pMesh, _In_opt_ NMATRIX3 * pmMatrix) + { + if (!pMesh) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + CImportStream * pStream = getStream(); + if (!pStream) + throw CNMRException(NMR_ERROR_NOIMPORTSTREAM); + + // TODO: handle colors + //CMeshInformationHandler * pMeshInformationHandler = pMesh->createMeshInformationHandler(); + //CMeshInformation * pInformation = pMeshInformationHandler->getInformationByType(0, emiProperties); + //CMeshInformation_Properties * pProperties = nullptr; + + //if (!pProperties) { + // PMeshInformation_Properties pNewMeshInformation = std::make_shared(pMesh->getFaceCount()); + // pMeshInformationHandler->addInformation(pNewMeshInformation); + + // pProperties = pNewMeshInformation.get(); + //} + + std::array aSTLHeader; + nfUint32 nFaceCount = 0; + nfUint32 nGlobalColor = 0xffffffff; + + pStream->readIntoBuffer(&aSTLHeader[0], 80, true); + pStream->readIntoBuffer((nfByte*)&nFaceCount, sizeof(nFaceCount), true); + if (isBigEndian()) { + nFaceCount = swapBytes(nFaceCount); + } + + if (nFaceCount > NMR_MESH_MAXFACECOUNT) + throw CNMRException(NMR_ERROR_INVALIDFACECOUNT); + + std::string sHeaderString(std::begin(aSTLHeader), std::end(aSTLHeader)); + std::size_t nFound = sHeaderString.find("COLOR="); + if (nFound != std::string::npos) { + if (nFound <= 76) { + nGlobalColor = ((nfUint32)aSTLHeader[nFound + 6]) + (((nfUint32)aSTLHeader[nFound + 7]) << 8) + (((nfUint32)aSTLHeader[nFound + 8]) << 16) + + (((nfUint32)aSTLHeader[nFound + 9]) << 24); + } + } + + nfUint32 nNodeIdx; + MESHNODE * pNodes[3]; + MESHFORMAT_STL_FACET Facet; + CVectorTree VectorTree; + nfBool bIsValid; + + VectorTree.setUnits(m_fUnits); + + for (nfUint32 nIdx = 0; nIdx < nFaceCount; nIdx++) { + pStream->readIntoBuffer((nfByte*)&Facet, sizeof(Facet), true); + if (isBigEndian()) { + Facet.swapByteOrder(); + } + + // Check, if Coordinates are in Valid Space + bIsValid = true; + for (nfUint32 j = 0; j < 3; j++) + for (nfUint32 k = 0; k < 3; k++) + bIsValid &= (fabs(Facet.m_vertices[j].m_fields[k]) < NMR_MESH_MAXCOORDINATE); + + // Identify Nodes via Tree + if (bIsValid) { + + for (nfUint32 j = 0; j < 3; j++) { + NVEC3 vPosition = Facet.m_vertices[j]; + if (pmMatrix) + vPosition = fnMATRIX3_apply(*pmMatrix, vPosition); + + if (VectorTree.findVector3(vPosition, nNodeIdx)) { + pNodes[j] = pMesh->getNode(nNodeIdx); + } + else { + pNodes[j] = pMesh->addNode(vPosition); + VectorTree.addVector3(pNodes[j]->m_position, (nfUint32)pNodes[j]->m_index); + } + } + + // check, if Nodes are separate + bIsValid = (pNodes[0] != pNodes[1]) && (pNodes[0] != pNodes[2]) && (pNodes[1] != pNodes[2]); + } + + // Throw "Invalid Exception" + if ((!bIsValid) && !m_bIgnoreInvalidFaces) + throw CNMRException(NMR_ERROR_INVALIDCOORDINATES); + + if (bIsValid) { + MESHFACE * pFace = pMesh->addFace(pNodes[0], pNodes[1], pNodes[2]); + //if (pProperties) { + // nfUint32 nRed = (nfUint32) ((nfFloat) (Facet.m_attribute & 0x1f) / (255.0f / 31.0f)); + // nfUint32 nGreen = (nfUint32)((nfFloat)((Facet.m_attribute >> 5) & 0x1f) / (255.0f / 31.0f)); + // nfUint32 nBlue = (nfUint32)((nfFloat)((Facet.m_attribute >> 10) & 0x1f) / (255.0f / 31.0f)); + + // // MESHINFORMATION_PROPERTIES * pFaceData = (NMR::MESHINFORMATION_PROPERTIES*)pProperties->getFaceData(pFace->m_index); + //} + } + } + + } + +} \ No newline at end of file diff --git a/Source/Common/MeshInformation/NMR_MeshInformation.cpp b/Source/Common/MeshInformation/NMR_MeshInformation.cpp new file mode 100644 index 0000000..f053eda --- /dev/null +++ b/Source/Common/MeshInformation/NMR_MeshInformation.cpp @@ -0,0 +1,86 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_MeshInformation.cpp implements the Mesh Information Class. +This is a base class for handling all the mesh-related linear information +(like face colors, textures, etc...). It provides abstract functions to +interpolate and reconstruct informations while the mesh topology is changing. + +--*/ + +#include "Common/MeshInformation/NMR_MeshInformation.h" +#include "Common/NMR_Exception.h" +#include + +namespace NMR { + + CMeshInformation::CMeshInformation() + { + m_nInternalID = 0; + } + + _Ret_notnull_ MESHINFORMATIONFACEDATA * CMeshInformation::getFaceData(nfUint32 nFaceIndex) + { + if (!m_pContainer) + throw CNMRException(NMR_ERROR_NOMESHINFORMATIONCONTAINER); + return m_pContainer->getFaceData(nFaceIndex); + } + + void CMeshInformation::resetFaceInformation(_In_ nfUint32 nFaceIndex) + { + MESHINFORMATIONFACEDATA * pData = getFaceData(nFaceIndex); + if (pData) + this->invalidateFace(pData); + } + + _Ret_notnull_ MESHINFORMATIONFACEDATA * CMeshInformation::addFaceData(_In_ nfUint32 nNewFaceCount) + { + return m_pContainer->addFaceData(nNewFaceCount); + } + + void CMeshInformation::resetAllFaceInformation() + { + nfUint32 nCount = m_pContainer->getCurrentFaceCount(); + nfUint32 nIndex; + + for (nIndex = 0; nIndex < nCount; nIndex++) { + resetFaceInformation(nIndex); + } + } + + void CMeshInformation::setInternalID(nfUint64 nInternalID) + { + m_nInternalID = nInternalID; + } + + nfUint64 CMeshInformation::getInternalID() + { + return m_nInternalID; + } + +} diff --git a/Source/Common/MeshInformation/NMR_MeshInformationContainer.cpp b/Source/Common/MeshInformation/NMR_MeshInformationContainer.cpp new file mode 100644 index 0000000..57ee37b --- /dev/null +++ b/Source/Common/MeshInformation/NMR_MeshInformationContainer.cpp @@ -0,0 +1,129 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_MeshInformationContainer.cpp implements the Mesh Information Container +Class. This class provides a memory container for holding the texture +information state of a complete mesh structure. + +--*/ + +#include "Common/MeshInformation/NMR_MeshInformationContainer.h" +#include "Common/NMR_Exception.h" +#include + +namespace NMR { + + CMeshInformationContainer::CMeshInformationContainer() + { + m_nFaceCount = 0; + m_nRecordSize = 0; + m_CurrentDataBlock = NULL; + } + + CMeshInformationContainer::CMeshInformationContainer(nfUint32 nCurrentFaceCount, nfUint32 nRecordSize) + { + m_nFaceCount = 0; + m_nRecordSize = nRecordSize; + m_CurrentDataBlock = NULL; + + nfUint32 nIdx; + for (nIdx = 1; nIdx <= nCurrentFaceCount; nIdx++) + addFaceData(nIdx); + } + + CMeshInformationContainer::~CMeshInformationContainer() + { + clear(); + } + + _Ret_notnull_ MESHINFORMATIONFACEDATA * CMeshInformationContainer::addFaceData(nfUint32 nNewFaceCount) + { + nfUint32 j, nPageSize; + MESHINFORMATIONFACEDATA * pByte; + + if (m_nRecordSize == 0) + throw CNMRException(NMR_ERROR_INVALIDRECORDSIZE); + + nfUint32 nIdx = m_nFaceCount % MESHINFORMATIONCOUNTER_BUFFERSIZE; + if (nIdx == 0) { + nPageSize = m_nRecordSize * MESHINFORMATIONCOUNTER_BUFFERSIZE; + m_CurrentDataBlock = new MESHINFORMATIONFACEDATA[nPageSize]; + + m_DataBlocks.push_back(m_CurrentDataBlock); + + pByte = m_CurrentDataBlock; + for (j = 0; j < nPageSize; j++) { + *pByte = 0; + pByte++; + } + } + + if (!m_CurrentDataBlock) + throw CNMRException(NMR_ERROR_INVALIDMESHINFORMATIONDATA); + + MESHINFORMATIONFACEDATA * result = &m_CurrentDataBlock[m_nRecordSize * nIdx]; + + m_nFaceCount++; + if (m_nFaceCount != nNewFaceCount) + throw CNMRException(NMR_ERROR_MESHINFORMATIONCOUNTMISMATCH); + + return result; + } + + _Ret_notnull_ MESHINFORMATIONFACEDATA * CMeshInformationContainer::getFaceData(nfUint32 nIdx) + { + if (nIdx >= m_nFaceCount) + throw CNMRException(NMR_ERROR_INVALIDMESHINFORMATIONINDEX); + + nfUint32 nBlockIdx = nIdx / MESHINFORMATIONCOUNTER_BUFFERSIZE; + nfUint32 nModIdx = nIdx % MESHINFORMATIONCOUNTER_BUFFERSIZE; + + MESHINFORMATIONFACEDATA * pBlock = m_DataBlocks[nBlockIdx]; + return &pBlock[m_nRecordSize * nModIdx]; + } + + nfUint32 CMeshInformationContainer::getCurrentFaceCount() + { + return m_nFaceCount; + } + + void CMeshInformationContainer::clear() + { + std::vector::iterator iter = m_DataBlocks.begin (); + while (iter != m_DataBlocks.end()){ + MESHINFORMATIONFACEDATA * pBlock = *iter; + delete[] pBlock; + iter++; + } + + m_nFaceCount = 0; + m_nRecordSize = 0; + m_CurrentDataBlock = NULL; + } + +} diff --git a/Source/Common/MeshInformation/NMR_MeshInformationFactory.cpp b/Source/Common/MeshInformation/NMR_MeshInformationFactory.cpp new file mode 100644 index 0000000..776ca2c --- /dev/null +++ b/Source/Common/MeshInformation/NMR_MeshInformationFactory.cpp @@ -0,0 +1,56 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_MeshInformationFactory.cpp implements the Mesh Information Factory Class. +It allows a dynamic creation of different Classes of Information. + +--*/ + +#include "Common/MeshInformation/NMR_MeshInformationFactory.h" +#include "Common/NMR_Exception.h" +#include + +namespace NMR { + + CMeshInformationFactory::CMeshInformationFactory() + { + // empty on purpose + } + + PMeshInformation CMeshInformationFactory::createMeshInformation(eMeshInformationType eType, nfUint32 nCurrentFaceCount) + { + switch (eType) { + case emiProperties: + return std::make_shared(nCurrentFaceCount); + + default: + throw CNMRException(NMR_ERROR_INVALIDINFORMATIONTYPE); + } + } + +} diff --git a/Source/Common/MeshInformation/NMR_MeshInformationHandler.cpp b/Source/Common/MeshInformation/NMR_MeshInformationHandler.cpp new file mode 100644 index 0000000..dbf223b --- /dev/null +++ b/Source/Common/MeshInformation/NMR_MeshInformationHandler.cpp @@ -0,0 +1,202 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_MeshInformationHandler.cpp implements the Mesh Information Handler Class. +It allows to include different kinds of information in one mesh (like Textures AND colors). + +--*/ + +#include "Common/MeshInformation/NMR_MeshInformationHandler.h" +#include "Common/Math/NMR_Vector.h" +#include "Common/NMR_Exception.h" +#include + +namespace NMR { + + CMeshInformationHandler::CMeshInformationHandler() + { + nfInt32 eType; + for (eType = emiAbstract; eType < emiLastType; eType++) { + m_pLookup[eType] = NULL; + } + + m_nInternalIDCounter = 1; + + } + + void CMeshInformationHandler::addInformation(_In_ PMeshInformation pInformation) + { + __NMRASSERT(pInformation.get()); + + eMeshInformationType eType = pInformation->getType(); + + m_pInformations.push_back(pInformation); + m_pLookup[eType] = pInformation.get(); + + pInformation->setInternalID(m_nInternalIDCounter); + m_nInternalIDCounter++; + + if (m_nInternalIDCounter > MESHINFORMATION_MAXINTERNALID) + throw CNMRException(NMR_ERROR_HANDLEOVERFLOW); + } + + void CMeshInformationHandler::addFace(_In_ nfUint32 nNewFaceCount) + { + std::vector::iterator iter = m_pInformations.begin(); + + while (iter != m_pInformations.end()) { + MESHINFORMATIONFACEDATA * pData = (*iter)->addFaceData(nNewFaceCount); + if (pData) + (*iter)->invalidateFace(pData); + + iter++; + } + } + + CMeshInformation * CMeshInformationHandler::getInformationIndexed(_In_ nfUint32 nIdx) + { + if (nIdx >= (nfUint32)m_pInformations.size()) + throw CNMRException(NMR_ERROR_INVALIDMESHINFORMATIONINDEX); + + return m_pInformations[nIdx].get(); + } + + PMeshInformation CMeshInformationHandler::getPInformationIndexed(_In_ nfUint32 nIdx) + { + if (nIdx >= (nfUint32)m_pInformations.size()) + throw CNMRException(NMR_ERROR_INVALIDMESHINFORMATIONINDEX); + + return m_pInformations[nIdx]; + } + + CMeshInformation * CMeshInformationHandler::getInformationByType(_In_ nfUint32 nChannel, _In_ eMeshInformationType eType) + { + return m_pLookup[eType]; + } + + nfUint32 CMeshInformationHandler::getInformationCount() + { + return (nfUint32)m_pInformations.size(); + } + + void CMeshInformationHandler::addInfoTableFrom(_In_ CMeshInformationHandler * pOtherInfoHandler, _In_ nfUint32 nCurrentFaceCount) + { + nfInt32 eType; + for (eType = emiAbstract; eType < emiLastType; eType++) { + if ((pOtherInfoHandler->m_pLookup[eType]) && (!m_pLookup[eType])) + addInformation(pOtherInfoHandler->m_pLookup[eType]->cloneInstance(nCurrentFaceCount)); + if ((pOtherInfoHandler->m_pLookup[eType]) && (m_pLookup[eType])) + m_pLookup[eType]->mergeInformationFrom(pOtherInfoHandler->m_pLookup[eType]); + } + } + + void CMeshInformationHandler::cloneDefaultInfosFrom(_In_ CMeshInformationHandler * pOtherInfoHandler) + { + nfInt32 eType; + for (eType = emiAbstract; eType < emiLastType; eType++) { + if ((pOtherInfoHandler->m_pLookup[eType]) && (m_pLookup[eType])) + m_pLookup[eType]->cloneDefaultInfosFrom(pOtherInfoHandler->m_pLookup[eType]); + } + } + + void CMeshInformationHandler::cloneFaceInfosFrom(_In_ nfUint32 nFaceIdx, _In_ CMeshInformationHandler * pOtherInfoHandler, _In_ nfUint32 nOtherFaceIndex) + { + nfInt32 eType; + for (eType = emiAbstract; eType < emiLastType; eType++) { + if ((pOtherInfoHandler->m_pLookup[eType]) && (m_pLookup[eType])) + m_pLookup[eType]->cloneFaceInfosFrom(nFaceIdx, pOtherInfoHandler->m_pLookup[eType], nOtherFaceIndex); + } + } + + void CMeshInformationHandler::permuteNodeInformation(_In_ nfUint32 nFaceIdx, _In_ nfUint32 nNodeIndex1, _In_ nfUint32 nNodeIndex2, _In_ nfUint32 nNodeIndex3) + { + std::vector::iterator iter = m_pInformations.begin(); + + while (iter != m_pInformations.end()) { + (*iter)->permuteNodeInformation(nFaceIdx, nNodeIndex1, nNodeIndex2, nNodeIndex3); + iter++; + } + } + + void CMeshInformationHandler::resetFaceInformation(_In_ nfUint32 nFaceIdx) + { + std::vector::iterator iter = m_pInformations.begin(); + + while (iter != m_pInformations.end()) { + (*iter)->resetFaceInformation(nFaceIdx); + iter++; + } + } + + void CMeshInformationHandler::removeInformation(eMeshInformationType eType) + { + nfUint32 nCount = (nfUint32)m_pInformations.size(); + nfUint32 nIdx; + nfUint32 nNewIdx = 0; + + m_pLookup[eType] = NULL; + + for (nIdx = 0; nIdx < nCount; nIdx++) { + eMeshInformationType eCurrentType = m_pInformations[nIdx]->getType(); + if (eCurrentType != eType) { + m_pInformations[nNewIdx] = m_pInformations[nIdx]; + nNewIdx++; + } + } + + if (nNewIdx < nCount) { + for (nIdx = nNewIdx; nIdx < nCount; nIdx++) + m_pInformations.pop_back(); + } + } + + + void CMeshInformationHandler::removeInformationIndexed(_In_ nfUint32 nIndex) + { + nfUint32 nCount = (nfUint32)m_pInformations.size(); + nfUint32 nIdx; + if (nIndex >= nCount) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + + PMeshInformation pInformation = m_pInformations[nIndex]; + eMeshInformationType eType = pInformation->getType(); + + // clean lookup table + if (m_pLookup[eType] == pInformation.get()) { + m_pLookup[eType] = nullptr; + } + + // reorder vector + for (nIdx = nIndex; nIdx < nCount - 1; nIdx++) { + m_pInformations[nIdx] = m_pInformations[nIdx + 1]; + } + m_pInformations[nCount - 1] = nullptr; + m_pInformations.pop_back(); + } + +} diff --git a/Source/Common/MeshInformation/NMR_MeshInformation_Properties.cpp b/Source/Common/MeshInformation/NMR_MeshInformation_Properties.cpp new file mode 100644 index 0000000..1e55b34 --- /dev/null +++ b/Source/Common/MeshInformation/NMR_MeshInformation_Properties.cpp @@ -0,0 +1,198 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_MeshInformation_Properties.cpp implements the Texture Mesh Information Class. + +--*/ + +#include "Common/MeshInformation/NMR_MeshInformation_Properties.h" +#include "Common/NMR_Exception.h" +#include "Common/Math/NMR_Vector.h" +#include + +namespace NMR { + + + CMeshInformation_PropertyIndexMapping::CMeshInformation_PropertyIndexMapping() + { + } + + nfUint32 CMeshInformation_PropertyIndexMapping::registerPropertyID(UniqueResourceID nUniqueResourceID, ModelPropertyID nPropertyID, nfUint32 nResourceIndex) + { + if (nUniqueResourceID == 0) + throw CNMRException(NMR_ERROR_INVALIDPROPERTYRESOURCEID); + + m_IDMap.insert(std::make_pair(std::make_pair(nUniqueResourceID, nPropertyID), nResourceIndex)); + + return nResourceIndex; + } + + + nfUint32 CMeshInformation_PropertyIndexMapping::mapPropertyIDToIndex(UniqueResourceID nUniqueResourceID, ModelPropertyID nPropertyID) + { + if (nUniqueResourceID == 0) + throw CNMRException(NMR_ERROR_INVALIDPROPERTYRESOURCEID); + + auto iIterator = m_IDMap.find(std::make_pair(nUniqueResourceID, nPropertyID)); + if (iIterator == m_IDMap.end()) + throw CNMRException(NMR_ERROR_PROPERTYIDNOTFOUND); + + return iIterator->second; + } + + +/* void CMeshInformation_PropertyIndexMapping::findDefaultProperties() + { + nfUint32 nMaxCount = 0; + auto iIterator = m_IDMap.begin(); + while (iIterator != m_IDMap.end()) { + nfUint32 nCurrentCount = iIterator->second.second; + if (nCurrentCount > nMaxCount) { + m_nDefaultResourceID = iIterator->first.first; + m_nDefaultResourceIndex = iIterator->second.first; + + nMaxCount = nCurrentCount; + } + + iIterator++; + } + } */ + + + CMeshInformation_Properties::CMeshInformation_Properties() : CMeshInformation() + { + m_pContainer = std::make_shared(0, (nfUint32) sizeof(MESHINFORMATION_PROPERTIES)); + } + + CMeshInformation_Properties::CMeshInformation_Properties(nfUint32 nCurrentFaceCount) + { + nfUint32 nIdx; + m_pContainer = std::make_shared(nCurrentFaceCount, (nfUint32) sizeof(MESHINFORMATION_PROPERTIES)); + for (nIdx = 0; nIdx < nCurrentFaceCount; nIdx++) + invalidateFace(m_pContainer->getFaceData(nIdx)); + } + + void CMeshInformation_Properties::invalidateFace(_In_ MESHINFORMATIONFACEDATA * pData) + { + nfUint32 j; + + MESHINFORMATION_PROPERTIES * pProperties = (MESHINFORMATION_PROPERTIES *)pData; + if (pProperties) { + pProperties->m_nUniqueResourceID = 0; + for (j = 0; j < 3; j++) { + pProperties->m_nPropertyIDs[j] = 0; + } + } + } + + eMeshInformationType CMeshInformation_Properties::getType() + { + return emiProperties; + } + + void CMeshInformation_Properties::cloneDefaultInfosFrom(_In_ CMeshInformation * pOtherInformation) + { + MESHINFORMATION_PROPERTIES * pTargetDefaultData = (MESHINFORMATION_PROPERTIES*)getDefaultData(); + if (!pTargetDefaultData) { + setDefaultData((MESHINFORMATIONFACEDATA*)new MESHINFORMATION_PROPERTIES); + pTargetDefaultData = (MESHINFORMATION_PROPERTIES*)getDefaultData(); + } + MESHINFORMATION_PROPERTIES * pSourceDefaultData = (MESHINFORMATION_PROPERTIES*)pOtherInformation->getDefaultData(); + if (pTargetDefaultData && pSourceDefaultData) { + for (nfUint32 j = 0; j < 3; j++) + pTargetDefaultData->m_nPropertyIDs[j] = pSourceDefaultData->m_nPropertyIDs[j]; + + pTargetDefaultData->m_nUniqueResourceID = pSourceDefaultData->m_nUniqueResourceID; + } + } + + + void CMeshInformation_Properties::cloneFaceInfosFrom(_In_ nfUint32 nFaceIndex, _In_ CMeshInformation * pOtherInformation, _In_ nfUint32 nOtherFaceIndex) + { + __NMRASSERT(pOtherInformation); + + MESHINFORMATION_PROPERTIES * pTargetFaceData = (MESHINFORMATION_PROPERTIES*)getFaceData(nFaceIndex); + MESHINFORMATION_PROPERTIES * pSourceFaceData = (MESHINFORMATION_PROPERTIES*)pOtherInformation->getFaceData(nOtherFaceIndex); + + if (pTargetFaceData && pSourceFaceData) { + for (nfUint32 j = 0; j < 3; j++) + pTargetFaceData->m_nPropertyIDs[j] = pSourceFaceData->m_nPropertyIDs[j]; + + pTargetFaceData->m_nUniqueResourceID = pSourceFaceData->m_nUniqueResourceID; + } + } + + PMeshInformation CMeshInformation_Properties::cloneInstance(_In_ nfUint32 nCurrentFaceCount) + { + return std::make_shared(nCurrentFaceCount); + } + + void CMeshInformation_Properties::permuteNodeInformation(_In_ nfUint32 nFaceIndex, _In_ nfUint32 nNodeIndex1, _In_ nfUint32 nNodeIndex2, _In_ nfUint32 nNodeIndex3) + { + MESHINFORMATION_PROPERTIES * pFaceData = (MESHINFORMATION_PROPERTIES*)getFaceData(nFaceIndex); + if (pFaceData && (nNodeIndex1 < 3) && (nNodeIndex2 < 3) && (nNodeIndex3 < 3)) { + MESHINFORMATION_PROPERTIES FaceDataCopy = *pFaceData; + + pFaceData->m_nPropertyIDs[0] = FaceDataCopy.m_nPropertyIDs[nNodeIndex1]; + pFaceData->m_nPropertyIDs[1] = FaceDataCopy.m_nPropertyIDs[nNodeIndex2]; + pFaceData->m_nPropertyIDs[2] = FaceDataCopy.m_nPropertyIDs[nNodeIndex3]; + } + } + + nfUint32 CMeshInformation_Properties::getBackupSize() + { + return (nfUint32) sizeof (MESHINFORMATION_PROPERTIES); + } + + void CMeshInformation_Properties::mergeInformationFrom(_In_ CMeshInformation * pInformation) + { + __NMRASSERT(pInformation); + + } + + nfBool CMeshInformation_Properties::faceHasData(_In_ nfUint32 nFaceIndex) + { + MESHINFORMATION_PROPERTIES * pFaceData = (MESHINFORMATION_PROPERTIES*)getFaceData(nFaceIndex); + if (pFaceData) + return (pFaceData->m_nUniqueResourceID != 0); + + return false; + } + + void CMeshInformation_Properties::setDefaultData(MESHINFORMATIONFACEDATA* pData) + { + MESHINFORMATION_PROPERTIES * pProperties = (MESHINFORMATION_PROPERTIES *)pData; + + m_pDefaultProperty.reset(pProperties); + } + + MESHINFORMATIONFACEDATA* CMeshInformation_Properties::getDefaultData() + { + return (MESHINFORMATIONFACEDATA*)m_pDefaultProperty.get(); + } +} diff --git a/Source/Common/NMR_Exception.cpp b/Source/Common/NMR_Exception.cpp new file mode 100644 index 0000000..607b32d --- /dev/null +++ b/Source/Common/NMR_Exception.cpp @@ -0,0 +1,482 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_Exception.cpp implements the generic Exception Class. +Each exception is identified via a global ErrorCode +(to be looked up in NMR_ErrorConst.h) + +--*/ + +#include "Common/NMR_Exception.h" +#include + +namespace NMR { + + CNMRException::CNMRException(_In_ nfError errorcode) : std::exception() + { + m_errorcode = errorcode; + } + + const char * CNMRException::what() const throw () + { + switch (m_errorcode) { + // Success / user interaction (0x0XXX) + case NMR_USERABORTED: return "The called function was aborted by the user"; + // General error codes (0x1XXX) + case NMR_ERROR_NOTIMPLEMENTED: return "The called function is not fully implemented"; + case NMR_ERROR_INVALIDPARAM: return "The call parameter to the function was invalid"; + case NMR_ERROR_CALCULATIONTERMINATED: return "The Calculation has to be canceled"; + case NMR_ERROR_COULDNOTLOADLIBRARY: return "The DLL Library of the DLL Filters could not be loaded"; + case NMR_ERROR_GETPROCFAILED: return "The DLL Library of the DLL Filters is invalid"; + case NMR_ERROR_DLLNOTLOADED: return "The DLL Library has not been loaded or could not be loaded"; + case NMR_ERROR_DLLFUNCTIONNOTFOUND: return "The DLL Library of the DLL Filters is invalid"; + case NMR_ERROR_DLLINVALIDPARAM: return "The DLL Library has got an invalid parameter"; + case NMR_ERROR_DLLNOINSTANCE: return "No Instance of the DLL has been created"; + case NMR_ERROR_DLLINVALIDFILTERNAME: return "The DLL does not support the suspected filters"; + case NMR_ERROR_DLLMISSINGPARAMETER: return "Not all parameters are provided to the DLL"; + case NMR_ERROR_INVALIDBLOCKSIZE: return "The provided Blocksize is invalid (like in CPagedVector)"; + case NMR_ERROR_INVALIDINDEX: return "The provided Index is invalid (like in CPagedVector, Node Index)"; + case NMR_ERROR_SINGULARMATRIX: return "A Matrix could not be inverted in the Matrix functions (as it is singular)"; + case NMR_ERROR_MODELMISMATCH: return "The Model Object does not match the model which is it added to"; + case NMR_ERROR_ABSTRACT: return "The function called is abstract and should not have been called"; + case NMR_ERROR_INVALIDHEADBLOCK: return "The current block is not assigned"; + case NMR_ERROR_COMINITIALIZATIONFAILED: return "COM CoInitialize failed"; + case NMR_ERROR_STANDARDCPPEXCEPTION: return "A Standard C++ Exception occurred"; + case NMR_ERROR_INVALIDMESH: return "No mesh has been given"; + case NMR_ERROR_COULDNOTCREATECONTEXT: return "Context could not be created"; + case NMR_ERROR_EMPTYSTRINGTOINTCONVERSION: return "Wanted to convert empty string to integer"; + case NMR_ERROR_INVALIDSTRINGTOINTCONVERSION: return "Wanted to convert string with non-numeric characters to integer"; + case NMR_ERROR_STRINGTOINTCONVERSIONOUTOFRANGE: return "Wanted to convert too large number string to integer"; + case NMR_ERROR_EMPTYSTRINGTODOUBLECONVERSION: return "Wanted to convert empty string to double"; + case NMR_ERROR_INVALIDSTRINGTODOUBLECONVERSION: return "Wanted to convert string with non-numeric characters to double"; + case NMR_ERROR_STRINGTODOUBLECONVERSIONOUTOFRANGE: return "Wanted to convert too large number string to double"; + case NMR_ERROR_TOOMANYVALUESINMATRIXSTRING: return "Too many values (>12) have been found in a matrix string"; + case NMR_ERROR_NOTENOUGHVALUESINMATRIXSTRING: return "Not enough values (<12) have been found in a matrix string"; + case NMR_ERROR_INVALIDBUFFERSIZE: return "Invalid buffer size"; + case NMR_ERROR_INSUFFICIENTBUFFERSIZE: return "Insufficient buffer size"; + case NMR_ERROR_INVALIDCOMPONENT: return "No component has been given"; + case NMR_ERROR_INVALIDHEXVALUE: return "Invalid hex value"; + case NMR_ERROR_RANGEERROR: return "Range error"; + case NMR_ERROR_INVALIDPOINTER: return "Passed invalid null pointer"; + case NMR_ERROR_XMLELEMENTNOTOPEN: return "XML Element not open"; + case NMR_ERROR_INVALIDXMLNAME: return "Invalid XML Name"; + case NMR_ERROR_INVALIDINTEGERTRIPLET: return "Invalid Integer Triplet String"; + case NMR_ERROR_INVALIDZIPENTRYKEY: return "Invalid ZIP Entry key"; + case NMR_ERRORINVALIDZIPNAME: return "Invalid ZIP Name"; + case NMR_ERROR_ZIPSTREAMCANNOTSEEK: return "ZIP Stream cannot seek"; + case NMR_ERROR_COULDNOTCONVERTTOUTF8: return "Could not convert to UTF8"; + case NMR_ERROR_COULDNOTCONVERTTOUTF16: return "Could not convert to UTF16"; + case NMR_ERROR_ZIPENTRYOVERFLOW: return "ZIP Entry overflow"; + case NMR_ERROR_INVALIDZIPENTRY: return "Invalid ZIP Entry"; + case NMR_ERROR_EXPORTSTREAMNOTEMPTY: return "Export Stream not empty"; + case NMR_ERROR_DEFLATEINITFAILED: return "Deflate init failed"; + case NMR_ERROR_ZIPALREADYFINISHED: return "Zip already finished"; + case NMR_ERROR_COULDNOTDEFLATE: return "Could not deflate data"; + case NMR_ERROR_XMLWRITER_CLOSENODEERROR: return "Could not close written XML node"; + case NMR_ERROR_INVALIDOPCPARTURI: return "Invalid OPC Part URI"; + case NMR_ERROR_COULDNOTCONVERTNUMBER: return "Could not convert number"; + case NMR_ERROR_COULDNOTGETSTREAMPOSITION: return "Could not get stream position"; + case NMR_ERROR_COULDNOTREADZIPFILE: return "Could not read ZIP file"; + case NMR_ERROR_COULDNOTSEEKINZIP: return "Could not seek in ZIP file"; + case NMR_ERROR_COULDNOTSTATZIPENTRY: return "Could not stat ZIP entry"; + case NMR_ERROR_COULDNOTOPENZIPENTRY: return "Could not open ZIP entry"; + case NMR_ERROR_INVALIDXMLDEPTH: return "Invalid XML Depth"; + case NMR_ERROR_XMLELEMENTNOTEMPTY: return "XML Element not empty"; + case NMR_ERROR_COULDNOTINITITALIZECOM: return "Could not initialize COM"; + case NMR_ERROR_CALLBACKSTREAMCANNOTSEEK: return "Callback stream cannot seek"; + case NMR_ERROR_COULDNOTWRITETOCALLBACKSTREAM: return "Could not write to callback stream"; + case NMR_ERROR_INVALIDCAST: return "Invalid Type Case"; + case NMR_ERROR_BUFFERISFULL: return "Buffer is full"; + case NMR_ERROR_COULDNOTREADFROMCALLBACKSTREAM: return "Could not read from callback stream"; + case NMR_ERROR_OPC_MISSING_EXTENSION_FOR_RELATIONSHIP: return "Content Types does not contain extension for relatioship."; + case NMR_ERROR_OPC_MISSING_EXTENSION_FOR_MODEL: return "Content Types does not contain extension or partname for model."; + case NMR_ERROR_INVALIDXMLENCODING: return "Document is not UTF-8 encoded."; + case NMR_ERROR_FORBIDDENXMLATTRITIBUTE: return "Document contains a forbidden XML-attribute."; + case NMR_ERROR_DUPLICATE_PRINTTICKET: return "Document contains more than one printticket."; + case NMR_ERROR_OPC_DUPLICATE_RELATIONSHIP_ID: return "Document contains a duplicate relationship ID."; + case NMR_ERROR_INVALIDRELATIONSHIPTYPEFORTEXTURE: return "A texture must use a OPC part with relationshiptype 3D Texture."; + case NMR_ERROR_IMPORTSTREAMISEMPTY: return "An attachment to be read does not have any content."; + case NMR_ERROR_UUIDGENERATIONFAILED: return "Generation of a UUID failed."; + case NMR_ERROR_ZIPENTRYNON64_TOOLARGE: return "A ZIP Entry is too large for non zip64 zip-file"; + case NMR_ERROR_ATTACHMENTTOOLARGE: return "An individual custom attachment is too large."; + case NMR_ERROR_ZIPCALLBACK: return "Error in libzip callback."; + case NMR_ERROR_ZIPCONTAINSINCONSISTENCIES: return "ZIP file contains inconsistencies. It might load with errors or incorrectly."; + case NMR_ERROR_XMLNAMESPACEALREADYREGISTERED: return "An XML namespace is already registered."; + case NMR_ERROR_XMLPREFIXALREADYREGISTERED: return "An XML prefix is already registered."; + + + // Unhandled exception + case NMR_ERROR_GENERICEXCEPTION: return NMR_GENERICEXCEPTIONSTRING; + + + // Core framework error codes (0x2XXX) + case NMR_ERROR_NOPROGRESSINTERVAL: return "No Progress Interval has been specified in the progress handler"; + case NMR_ERROR_DUPLICATENODE: return "An Edge with two identical nodes has been tried to added to a mesh"; + case NMR_ERROR_TOOMANYNODES: return "The mesh exceeds more than NMR_MESH_MAXEDGECOUNT (2^31-1, around two billion) nodes"; + case NMR_ERROR_TOOMANYFACES: return "The mesh exceeds more than NMR_MESH_MAXFACECOUNT (2^31-1, around two billion) faces"; + case NMR_ERROR_INVALIDNODEINDEX: return "The index provided for the node is invalid"; + case NMR_ERROR_INVALIDFACEINDEX: return "The index provided for the face is invalid"; + case NMR_ERROR_INVALIDMESHTOPOLOGY: return "The mesh topology structure is corrupt"; + case NMR_ERROR_INVALIDCOORDINATES: return "The coordinates exceed NMR_MESH_MAXCOORDINATE (= 1 billion mm)"; + case NMR_ERROR_NORMALIZEDZEROVECTOR: return "A zero Vector has been tried to normalized, which is impossible"; + case NMR_ERROR_COULDNOTOPENFILE: return "The specified file could not be opened"; + case NMR_ERROR_COULDNOTCREATEFILE: return "The specified file could not be created"; + case NMR_ERROR_COULDNOTSEEKSTREAM: return "Seeking in a stream was not possible"; + case NMR_ERROR_COULDNOTREADSTREAM: return "Reading from a stream was not possible"; + case NMR_ERROR_COULDNOTWRITESTREAM: return "Writing to a stream was not possible"; + case NMR_ERROR_COULDNOTREADFULLDATA: return "Reading from a stream was only possible partially"; + case NMR_ERROR_COULDNOTWRITEFULLDATA: return "Writing to a stream was only possible partially"; + case NMR_ERROR_NOIMPORTSTREAM: return "No Import Stream was provided to the importer"; + case NMR_ERROR_INVALIDFACECOUNT: return "The specified facecount in the file was not valid"; + case NMR_ERROR_INVALIDUNITS: return "The specified units of the file was not valid"; + case NMR_ERROR_COULDNOTSETUNITS: return "The specified units could not be set (for example, the CVectorTree already had some entries)"; + case NMR_ERROR_TOOMANYEDGES: return "The mesh exceeds more than NMR_MESH_MAXEDGECOUNT (2^31-1, around two billion) edges"; + case NMR_ERROR_INVALIDEDGEINDEX: return "The index provided for the edge is invalid"; + case NMR_ERROR_DUPLICATEEDGE: return "The mesh has an face with two identical edges"; + case NMR_ERROR_MANIFOLDEDGES: return "Could not add face to an edge, because it was already two-manifold"; + case NMR_ERROR_COULDNOTDELETEEDGE: return "Could not delete edge, because it had attached faces"; + case NMR_ERROR_INTERNALMERGEERROR: return "Mesh Merging has failed, because the mesh structure was currupted"; + case NMR_ERROR_EDGESARENOTFORMINGTRIANGLE: return "The internal triangle structure is corrupted"; + case NMR_ERROR_NOEXPORTSTREAM: return "No Export Stream was provided to the exporter"; + case NMR_ERROR_COULDNOTSETPARAMETER: return "Could not set parameter, because the queue was not empty"; + case NMR_ERROR_INVALIDRECORDSIZE: return "Mesh Information records size is invalid"; + case NMR_ERROR_MESHINFORMATIONCOUNTMISMATCH: return "Mesh Information Face Count dies not match with mesh face count"; + case NMR_ERROR_INVALIDMESHINFORMATIONINDEX: return "Could not access mesh information"; + case NMR_ERROR_MESHINFORMATIONBUFFER_FULL: return "Mesh Information Backup could not be created"; + case NMR_ERROR_NOMESHINFORMATIONCONTAINER: return "No Mesh Information Container has been assigned"; + case NMR_ERROR_DISCRETEMERGEERROR: return "Internal Mesh Merge Error because of corrupt mesh structure"; + case NMR_ERROR_DISCRETEEDGELENGTHVIOLATION: return "Discrete Edges may only have a max length of 30000."; + case NMR_ERROR_OCTTREE_OUTOFBOUNDS: return "OctTree Node is out of the OctTree Structure"; + case NMR_ERROR_COULDNOTDELETENODE: return "Could not delete mesh node, because it still had some edges connected to it"; + case NMR_ERROR_INVALIDINFORMATIONTYPE: return "Mesh Information has not been found"; + case NMR_ERROR_FACESARENOTIDENTICAL: return "Mesh Information could not be copied"; + case NMR_ERROR_DUPLICATETEXTURE: return "Texture is already existing"; + case NMR_ERROR_DUPLICATETEXTUREID: return "Texture ID is already existing"; + case NMR_ERROR_PARTTOOLARGE: return "Part is too large"; + case NMR_ERROR_DUPLICATETEXTUREPATH: return "Texture getPath is already existing"; + case NMR_ERROR_DUPLICATETEXTUREWIDTH: return "Texture width is already existing"; + case NMR_ERROR_DUPLICATETEXTUREHEIGHT: return "Texture height is already existing"; + case NMR_ERROR_DUPLICATETEXTUREDEPTH: return "Texture depth is already existing"; + case NMR_ERROR_DUPLICATETEXTURECONTENTTYPE: return "Texture content type is already existing"; + case NMR_ERROR_DUPLICATETEXTUREU: return "Texture U coordinate is already existing"; + case NMR_ERROR_DUPLICATETEXTUREV: return "Texture V coordinate is already existing"; + case NMR_ERROR_DUPLICATETEXTUREW: return "Texture W coordinate is already existing"; + case NMR_ERROR_DUPLICATETEXTURESCALE: return "Texture scale is already existing"; + case NMR_ERROR_DUPLICATETEXTUREROTATION: return "Texture rotation is already existing"; + case NMR_ERROR_DUPLICATETILESTYLEU: return "Texture tilestyle U is already existing"; + case NMR_ERROR_DUPLICATETILESTYLEV: return "Texture tilestyle V is already existing"; + case NMR_ERROR_DUPLICATETILESTYLEW: return "Texture tilestyle W is already existing"; + case NMR_ERROR_DUPLICATECOLORID: return "Color ID is already existing"; + case NMR_ERROR_INVALIDMESHINFORMATIONDATA: return "Mesh Information Block was not assigned"; + case NMR_ERROR_INVALIDMESHINFORMATION: return "Mesh Information Object was not assigned"; + case NMR_ERROR_TOOMANYBEAMS: return "The mesh exceeds more than NMR_MESH_MAXBEAMCOUNT (2^31-1, around two billion) beams"; + + // Model error codes (0x8XXX) + case NMR_ERROR_OPCREADFAILED: return "3MF Loading - OPC could not be loaded"; + case NMR_ERROR_NOMODELSTREAM: return "No model stream in OPC Container"; + case NMR_ERROR_MODELREADFAILED: return "Model XML could not be parsed"; + case NMR_ERROR_NO3MFOBJECT: return "No 3MF Object in OPC Container"; + case NMR_ERROR_COULDNOTWRITEMODELSTREAM: return "Could not write Model Stream to OPC Container"; + case NMR_ERROR_OPCFACTORYCREATEFAILED: return "Could not create OPC Factory"; + case NMR_ERROR_OPCPARTSETREADFAILED: return "Could not read OPC Part Set"; + case NMR_ERROR_OPCRELATIONSHIPSETREADFAILED: return "Could not read OPC Relationship Set"; + case NMR_ERROR_OPCRELATIONSHIPSOURCEURIFAILED: return "Could not get Relationship Source URI"; + case NMR_ERROR_OPCRELATIONSHIPTARGETURIFAILED: return "Could not get Relationship Target URI"; + case NMR_ERROR_OPCRELATIONSHIPCOMBINEURIFAILED: return "Could not Combine Relationship URIs"; + case NMR_ERROR_OPCRELATIONSHIPGETPARTFAILED: return "Could not get Relationship Part"; + case NMR_ERROR_OPCGETCONTENTTYPEFAILED: return "Could not retrieve content type"; + case NMR_ERROR_OPCCONTENTTYPEMISMATCH: return "Content type mismatch"; + case NMR_ERROR_OPCRELATIONSHIPENUMERATIONFAILED: return "Could not enumerate relationships"; + case NMR_ERROR_OPCRELATIONSHIPNOTFOUND: return "Could not find relationship type"; + case NMR_ERROR_OPCRELATIONSHIPNOTUNIQUE: return "Ambiguous relationship type"; + case NMR_ERROR_OPCCOULDNOTGETMODELSTREAM: return "Could not get OPC Model Stream"; + case NMR_ERROR_CREATEXMLREADERFAILED: return "Could not create XML Reader"; + case NMR_ERROR_SETXMLREADERINPUTFAILED: return "Could not set XML reader input"; + case NMR_ERROR_COULDNOTSEEKMODELSTREAM: return "Could not seek in XML Model Stream"; + case NMR_ERROR_SETXMLPROPERTIESFAILED: return "Could not set XML reader properties"; + case NMR_ERROR_READXMLNODEFAILED: return "Could not read XML node"; + case NMR_ERROR_COULDNOTGETLOCALXMLNAME: return "Could not retrieve local xml node name"; + case NMR_ERROR_COULDPARSEXMLCONTENT: return "Could not parse XML Node content"; + case NMR_ERROR_COULDNOTGETXMLTEXT: return "Could not get XML Node value"; + case NMR_ERROR_COULDNOTGETXMLATTRIBUTES: return "Could not retrieve XML Node attributes"; + case NMR_ERROR_COULDNOTGETXMLVALUE: return "Could not get XML attribute value"; + case NMR_ERROR_ALREADYPARSEDXMLNODE: return "XML Node has already been parsed"; + case NMR_ERROR_INVALIDMODELUNIT: return "Invalid Model Unit"; + case NMR_ERROR_INVALIDMODELOBJECTID: return "Invalid Model Object ID"; + case NMR_ERROR_MISSINGMODELOBJECTID: return "No Model Object ID has been given"; + case NMR_ERROR_DUPLICATEMODELOBJECT: return "Model Object is already existing"; + case NMR_ERROR_DUPLICATEOBJECTID: return "Model Object ID was given twice"; + case NMR_ERROR_AMBIGUOUSOBJECTDEFINITON: return "Model Object Content was ambiguous"; + case NMR_ERROR_MODELCOORDINATEMISSING: return "Model Vertex is missing a coordinate"; + case NMR_ERROR_INVALIDMODELCOORDINATES: return "Invalid Model Coordinates"; + case NMR_ERROR_INVALIDMODELCOORDINATEINDICES: return "Invalid Model Coordinate Indices"; + case NMR_ERROR_NODENAMEISEMPTY: return "XML Node Name is empty"; + case NMR_ERROR_INVALIDMODELNODEINDEX: return "Invalid model node index"; + case NMR_ERROR_OPCPACKAGECREATEFAILED: return "Could not create OPC Package"; + case NMR_ERROR_COULDNOTWRITEOPCPACKAGETOSTREAM: return "Could not write OPC Package to Stream"; + case NMR_ERROR_COULDNOTCREATEOPCPARTURI: return "Could not create OPC Part URI"; + case NMR_ERROR_COULDNOTCREATEOPCPART: return "Could not create OPC Part"; + case NMR_ERROR_OPCCOULDNOTGETCONTENTSTREAM: return "Could not get OPC Content Stream"; + case NMR_ERROR_OPCCOULDNOTRESIZESTREAM: return "Could not resize OPC Stream"; + case NMR_ERROR_OPCCOULDNOTSEEKSTREAM: return "Could not seek in OPC Stream"; + case NMR_ERROR_OPCCOULDNOTCOPYSTREAM: return "Could not copy OPC Stream"; + case NMR_ERROR_COULDNOTRETRIEVEOPCPARTNAME: return "Could not retrieve OPC Part name"; + case NMR_ERROR_COULDNOTCREATEOPCRELATIONSHIP: return "Could not create OPC Relationship"; + case NMR_ERROR_COULDNOTCREATEXMLWRITER: return "Could not create XML Writer"; + case NMR_ERROR_COULDNOTSETXMLOUTPUT: return "Could not set XML Output stream"; + case NMR_ERROR_COULDNOTSETXMLPROPERTY: return "Could not set XML Property"; + case NMR_ERROR_COULDNOTWRITEXMLSTARTDOCUMENT: return "Could not write XML Start Document"; + case NMR_ERROR_COULDNOTWRITEXMLENDDOCUMENT: return "Could not write XML End Document"; + case NMR_ERROR_COULDNOTFLUSHXMLWRITER: return "Could not flush XML Writer"; + case NMR_ERROR_COULDNOTWRITEXMLSTARTELEMENT: return "Could not write XML Start Element"; + case NMR_ERROR_COULDNOTWRITEXMLENDELEMENT: return "Could not write XML End Element"; + case NMR_ERROR_COULDNOTWRITEXMLATTRIBUTE: return "Could not write XML Attribute String"; + case NMR_ERROR_MISSINGBUILDITEMOBJECTID: return "Build item Object ID was not specified"; + case NMR_ERROR_DUPLICATEBUILDITEMOBJECTID: return "Build item Object ID is ambiguous "; + case NMR_ERROR_INVALIDBUILDITEMOBJECTID: return "Build item Object ID is invalid"; + case NMR_ERROR_COULDNOTFINDBUILDITEMOBJECT: return "Could not find Object associated to the Build item "; + case NMR_ERROR_COULDNOTFINDCOMPONENTOBJECT: return "Could not find Object associated to Component"; + case NMR_ERROR_DUPLICATECOMPONENTOBJECTID: return "Component Object ID is ambiguous "; + case NMR_ERROR_MISSINGMODELTEXTUREID: return "Texture ID was not specified"; + case NMR_ERROR_MISSINGOBJECTCONTENT: return "An object has no supported content type"; + case NMR_ERROR_INVALIDREADEROBJECT: return "Invalid model reader object"; + case NMR_ERROR_INVALIDWRITEROBJECT: return "Invalid model writer object"; + case NMR_ERROR_UNKNOWNMODELRESOURCE: return "Unknown model resource"; + case NMR_ERROR_INVALIDSTREAMTYPE: return "Invalid stream type"; + case NMR_ERROR_DUPLICATEMATERIALID: return "Duplicate Material ID"; + case NMR_ERROR_DUPLICATEWALLTHICKNESS: return "Duplicate Wallthickness"; + case NMR_ERROR_DUPLICATEFIT: return "Duplicate Fit"; + case NMR_ERROR_DUPLICATEOBJECTTYPE: return "Duplicate Object Type"; + case NMR_ERROR_MODELTEXTURECOORDINATEMISSING: return "Texture coordinates missing"; + case NMR_ERROR_TOOMANYVALUESINCOLORSTRING: return "Too many values in color string"; + case NMR_ERROR_INVALIDVALUEINCOLORSTRING: return "Invalid value in color string"; + case NMR_ERROR_DUPLICATECOLORVALUE: return "Duplicate node color value"; + case NMR_ERROR_MISSINGMODELCOLORID: return "Missing model color ID"; + case NMR_ERROR_MISSINGMODELMATERIALID: return "Missing model material ID"; + case NMR_ERROR_INVALIDBUILDITEM: return "No Build Item has been given"; + case NMR_ERROR_INVALIDOBJECT: return "No Object has been given"; + case NMR_ERROR_INVALIDMODEL: return "No Model has been given"; + case NMR_ERROR_INVALIDMODELRESOURCE: return "No valid Model Resource has been given"; + case NMR_ERROR_DUPLICATEMETADATA: return "Duplicate Model Metadata"; + case NMR_ERROR_INVALIDMETADATA: return "Invalid Model Metadata"; + case NMR_ERROR_INVALIDMODELCOMPONENT: return "Invalid Model Component"; + case NMR_ERROR_INVALIDMODELOBJECTTYPE: return "Invalid Model Object Type"; + case NMR_ERROR_MISSINGMODELRESOURCEID: return "Missing Model Resource ID"; + case NMR_ERROR_DUPLICATERESOURCEID: return "Duplicate Resource ID"; + case NMR_ERROR_COULDNOTWRITEXMLCONTENT: return "Could not write XML Content"; + case NMR_ERROR_COULDNOTGETNAMESPACE: return "Could not get XML Namespace"; + case NMR_ERROR_HANDLEOVERFLOW: return "Handle overflow"; + case NMR_ERROR_NORESOURCES: return "No resources in model file"; + case NMR_ERROR_NOBUILD: return "No build section in model file"; + case NMR_ERROR_DUPLICATERESOURCES: return "Duplicate resources section in model file"; + case NMR_ERROR_DUPLICATEBUILDSECTION: return "Duplicate build section in model file"; + case NMR_ERROR_DUPLICATEMODELNODE: return "Duplicate model node in XML Stream"; + case NMR_ERROR_NOMODELNODE: return "No model node in XML Stream"; + case NMR_ERROR_RESOURCENOTFOUND: return "Resource not found"; + case NMR_ERROR_UNKNOWNREADERCLASS: return "Unknown reader class"; + case NMR_ERROR_UNKNOWNWRITERCLASS: return "Unknown writer class"; + case NMR_ERROR_MODELTEXTURENOTFOUND: return "Texture not found"; + case NMR_ERROR_INVALIDCONTENTTYPE: return "Invalid Content Type"; + case NMR_ERROR_INVALIDBASEMATERIAL: return "Invalid Base Material"; + case NMR_ERROR_TOOMANYMATERIALS: return "Too many materials"; + case NMR_ERROR_INVALIDTEXTURE: return "Invalid texture"; + case NMR_ERROR_COULDNOTGETHANDLE: return "Could not get handle"; + case NMR_ERROR_BUILDITEMNOTFOUND: return "Build item not found"; + case NMR_ERROR_OPCCOULDNOTGETTEXTUREURI: return "Could not get texture URI"; + case NMR_ERROR_MODELRELATIONSHIPSETREADFAILED: return "Model Relationship read failed"; + case NMR_ERROR_NOTEXTURESTREAM: return "Texture stream is not available"; + case NMR_ERROR_COULDNOTCREATESTREAM: return "Could not create stream"; + case NMR_ERROR_NOTSUPPORTINGLEGACYCMYK: return "Not supporting legacy CMYK color"; + case NMR_ERROR_INVALIDTEXTUREREFERENCE: return "Invalid Texture Reference"; + case NMR_ERROR_INVALIDTEXTUREID: return "Invalid Texture ID"; + case NMR_ERROR_NOMODELTOWRITE: return "No model to write"; + case NMR_ERROR_OPCRELATIONSHIPGETTYPEFAILED: return "Failed to get OPC Relationship type"; + case NMR_ERROR_OPCCOULDNOTGETATTACHMENTURI: return "Could not get attachment URI"; + case NMR_ERROR_DUPLICATEATTACHMENTPATH: return "Duplicate Attachment Path"; + case NMR_ERROR_INVALIDMODELATTACHMENT: return "Invalid Model Attachment"; + case NMR_ERROR_ATTACHMENTNOTFOUND: return "Could not find Model Attachment"; + case NMR_ERROR_INVALIDREQUIREDEXTENSIONPREFIX: return "The prefix of a required extension is invalid"; + case NMR_ERROR_REQUIREDEXTENSIONNOTSUPPORTED: return "A required extension is not supported"; + case NMR_ERROR_BEAMLATTICECLIPPINGRESOURCENOTDEFINED: return "The resource defined as clippingmesh has not yet been defined in the model"; + case NMR_ERROR_BEAMLATTICEINVALIDATTRIBUTE: return "An attribute of the beamlattice is invalid"; + case NMR_ERROR_OPCCOULDNOTGETSLICEREFURI: return "Could not get sliceref URI"; + case NMR_ERROR_OPCCOULDNOTGETSLICEREFSTREAM: return "Could not get sliceref stream"; + case NMR_ERROR_OPCCOULDNOTGETATTACHMENTSTREAM: return "Could not get attachment stream"; + case NMR_ERROR_DUPLICATE_SLICESTACKID: return "Object has dublicate slicestack ID"; + case NMR_ERROR_SLICESTACKRESOURCE_NOT_FOUND: return "Could not find Slicestack Resource"; + case NMR_ERROR_SLICESTACK_SLICESANDSLICEREF: return "Slicestack contains slices and slicerefs"; + case NMR_ERROR_ILLFORMATUUID: return "A UUID is ill formatted"; + case NMR_ERROR_INVALIDSLICESTACK: return "A slice stack resource is invalid"; + case NMR_ERROR_DUPLICATEPATH: return "Duplicate getPath attribute"; + case NMR_ERROR_DUPLICATEUUID: return "Duplicate UUID attribute"; + case NMR_ERROR_REFERENCESTOODEEP: return "References in production extension go deeper than one level."; + case NMR_ERROR_SLICEREFSTOODEEP: return "A slicestack referenced via a slicepath cannot reference another slicestack."; + case NMR_ERROR_SLICES_Z_NOTINCREASING: return "The z-coordinates of slices within a slicestack are not increasing."; + case NMR_ERROR_SLICEPOLYGONNOTCLOSED: return "A slice polygon of a model- or solidsupport-object is not closed."; + case NMR_ERROR_CLOSED_SLICE_POLYGON_IS_LINE: return "A closed slice polygon is actually a line."; + case NMR_ERROR_NAMESPACE_INVALID_ELEMENT: return "Invalid Element in namespace."; + case NMR_ERROR_NAMESPACE_INVALID_ATTRIBUTE: return "Invalid Attribute in namespace."; + case NMR_ERROR_DUPLICATETEZTOP: return "Duplicate Z-top-value in a slice."; + case NMR_ERROR_MISSINGTEZTOP: return "Z-top-value is missing in a slice."; + case NMR_ERROR_SLICE_INVALIDATTRIBUTE: return "Invalid attribute in slice extension"; + case NMR_ERROR_SLICETRANSFORMATIONPLANAR: return "A slicestack posesses a nonplanar transformation."; + case NMR_ERROR_UUID_NOT_UNIQUE: return "A UUID is not unique within a package."; + case NMR_ERROR_METADATA_COULDNOTGETNAMESPACE: return "Could not get XML Namespace for a metadatum."; + case NMR_ERROR_INVALID_SLICESEGMENT_VERTEXINDEX: return "Invalid index for slice segment or polygon."; + case NMR_ERROR_MISSINGUUID: return "A UUID for a build, build item or object is missing."; + case NMR_ERROR_INVALID_SLICEPATH: return "A slicepath is invalid."; + case NMR_ERROR_UNKNOWNMETADATA: return "Unknown Model Metadata."; + case NMR_ERROR_DUPLICATE_MESHRESOLUTION: return "Object has duplicate meshresolution attribute."; + case NMR_ERROR_INVALID_MESHRESOLUTION: return "Object has invalid value for meshresolution attribute."; + case NMR_ERROR_INVALIDREADERWARNINGSOBJECT: return "Invalid model reader warnings object."; + case NMR_ERROR_OPCCOULDNOTGETTHUMBNAILSTREAM: return "Could not get OPC thumbnail stream."; + case NMR_ERROR_DUPLICATEOBJECTTHUMBNAIL: return "Duplicate object thumbnail."; + case NMR_ERROR_DUPLICATETHUMBNAIL: return "Duplicate thumbnail."; + case NMR_ERROR_DUPLICATEPID: return "Duplicate Property ID."; + case NMR_ERROR_DUPLICATEPINDEX: return "Duplicate Property Index."; + case NMR_ERROR_MISSINGOBJECTLEVELPID: return "A MeshObject with triangle-properties is missing an object-level property."; + case NMR_ERROR_INVALIDOBJECTLEVELPID: return "A MeshObject with triangle-properties has an invalid object-level property."; + case NMR_ERROR_BUILDITEMOBJECT_MUSTNOTBE_OTHER: return "Build-item must not reference object of type OTHER."; + case NMR_ERROR_OBJECTLEVELPID_ON_COMPONENTSOBJECT: return "A components object must not have an object-level PID."; + case NMR_ERROR_BEAMLATTICENODESTOOCLOSE: return "Nodes used for a beam are closer then the specified minimal length."; + case NMR_ERROR_BEAMLATTICE_INVALID_REPRESENTATIONRESOURCE: return "The resource defined as representationmesh is invalid."; + case NMR_ERROR_BEAMLATTICE_INVALID_OBJECTTYPE: return "Beamlattice is defined on wrong object type."; + case NMR_ERROR_SLICE_ONEVERTEX: return "Slice only contains one vertex."; + case NMR_ERROR_SLICE_ONEPOINT: return "Slice contains only one point within a polygon"; + case NMR_ERROR_INVALIDTILESTYLE: return "Invalid Tile Style"; + case NMR_ERROR_INVALIDFILTER: return "Invalid Filter"; + case NMR_ERROR_DUPLICATEMETADATAGROUP: return "Duplicate MetaDataGroup"; + case NMR_ERROR_SLICES_MIXING_SLICES_WITH_SLICEREFS: return "A SliceStack must not contain slices and slicerefs"; + case NMR_ERROR_SLICES_SLICEREF_CIRCULAR: return "SliceStack references must not be circular"; + case NMR_ERROR_SLICES_REFS_Z_NOTINCREASING: return "z-position of slicerefs is not increasing"; + case NMR_ERROR_SLICES_REFS_LEVELTOODEEP: return "level of slicereferences is too deep"; + case NMR_ERROR_PROPERTYIDALREADYREGISTERED: return "Property already registered"; + case NMR_ERROR_INVALIDPROPERTYRESOURCEID: return "Invalid Property Resource ID"; + case NMR_ERROR_PROPERTYIDNOTFOUND: return "Property ID not found"; + case NMR_ERROR_TOOMANYCOLORS: return "Too many colors."; + case NMR_ERROR_TOOMANYCOMPOSITES: return "Too many composites."; + case NMR_ERROR_MIXINGRATIO_OUTOFRANGE: return "Mixing ratio of composite out of range."; + case NMR_ERROR_MIXINGRATIO_MISSING: return "A composite mixing ratio is missing."; + case NMR_ERROR_MIXINGRATIO_TOOMANY: return "Too many composite mixing ratio in the list of values"; + case NMR_ERROR_MULTIPROPERTIES_MUST_NOT_CONTAIN_MULTIPROPERTIES: return "A multiproperties must not contain another multiproperties"; + case NMR_ERROR_MULTIPROPERTIES_MUST_NOT_CONTAIN_MULTIPLE_MATERIALS: return "A multiproperties must not contain multiple materials"; + case NMR_ERROR_MULTIPROPERTIES_MUST_NOT_CONTAIN_MULTIPLE_COLORGOURPS: return "A multiproperties must not contain multiple colorgroups"; + case NMR_ERROR_MULTIPROPERTIES_INVALID_RESOURCE: return "A resource of invalid type was passed to a MultiPropertyGroup"; + case NMR_ERROR_MULTIPROPERTIES_NOT_ENOUGH_PROPERTYIDS_SPECIFIED: return "A MultiProperty does not define enough PropertyIDs"; + case NMR_ERROR_MULTIPROPERTIES_MISSING_PIDS: return "A MultiProperty-element is missing the pids-attribute"; + case NMR_ERROR_MULTIPROPERTIES_DIFFERNT_NUMBER_OF_BLENDMETHODS_AND_PIDS: return "The number of blendmethods and pids does not match"; + case NMR_ERROR_DUPLICATE_PIDS: return "Multiproperties element has duplicate pids attribute"; + case NMR_ERROR_DUPLICATE_BLENDMETHOS: return "Multiproperties element has duplicate blendmethods attribute"; + case NMR_ERROR_INVALID_BLENDMETHOD_ATTRIBUTE: return "A blendmethods attribute is invalid"; + case NMR_ERROR_MULTIPROPERTIES_INVALID_MULTI_ELEMENT: return "A multi-element is invalid"; + case NMR_ERROR_INVALID_RESOURCE_INDEX: return "A Resource Index is invalid"; + case NMR_ERROR_VERSION093_NOT_SUPPORTED: return "This document contains content from Version 093 of the core-specification. This is not fully supported by Lib3MF version 2 or later."; + case NMR_ERROR_ATTACHMENTMODELMISMATCH: return "The model of an attachment does not match the model of a resource."; + case NMR_ERROR_DUPLICATEPACKAGEPATH: return "The PackagePath of a model is not unique."; + case NMR_ERROR_PRODUCTIONEXTENSION_REQUIRED: return "Serialization of this Model requires the production extension."; + case NMR_ERROR_MODELRESOURCE_IN_DIFFERENT_MODEL: return "Referenced model resource must not be in a different model."; + case NMR_ERROR_PATH_NOT_ABSOLUTE: return "A path attribute element is not absolute."; + case NMR_ERROR_BEAMSET_IDENTIFIER_NOT_UNIQUE: return "A beamset identifier is not unique."; + //keystore error codes + case NMR_ERROR_KEYSTOREDUPLICATECONSUMER: return "A consumer already exists for this consumerid"; + case NMR_ERROR_KEYSTOREDUPLICATECONSUMERID: return "The attribute consumerid is duplicated"; + case NMR_ERROR_KEYSTOREDUPLICATECONSUMERKEYID: return "The KeyStore Consumer key id is not unique "; + case NMR_ERROR_KEYSTOREDUPLICATERESOURCEDATAPATH: return "The attribute path is duplicated"; + case NMR_ERROR_KEYSTOREDUPLICATECONSUMERINDEX: return "The attribute consumerindex is duplicated"; + case NMR_ERROR_KEYSTOREDUPLICATERESOURCEDATA: return "A ResourceData already exists for this path in the KeyStore"; + case NMR_ERROR_KEYSTOREDUPLICATEACCESSRIGHT: return "An AccessRight already exists for this consumer in a ResourceDataGroup"; + case NMR_ERROR_KEYSTOREDUPLICATERESOURCEDATAGROUP: return "A resource data group already exist for this keyuuid"; + case NMR_ERROR_KEYSTOREINVALIDALGORITHM: return "The algorithm attribute is invalid"; + case NMR_ERROR_KEYSTOREINVALIDCOMPRESSION: return "The KeyStore ResourceData compression is invalid"; + case NMR_ERROR_KEYSTOREINVALIDCIPHERVALUE: return "Invalid CipherValue elment value"; + case NMR_ERROR_KEYSTOREINVALIDMGF: return "The mfgalgorithm attribute has invalid value"; + case NMR_ERROR_KEYSTOREINVALIDDIGEST: return "The digestmethod attribute has invalid value"; + case NMR_ERROR_KEYSTOREINVALIDCONSUMERINDEX: return "The attribute consumerindex is invalid"; + case NMR_ERROR_KEYSTOREINVALIDKEYUUID: return "Attribute keyuuid is invalid, a default value has been assigned."; + case NMR_ERROR_KEYSTOREMISSINGCIPHERDATA: return "Element cipherdata is missing"; + case NMR_ERROR_KEYSTOREMISSINGCONSUMERID: return "Attribute consumerid is missing, a default value has been assigned."; + case NMR_ERROR_KEYSTOREMISSINGCONSUMERINDEX: return "Attribute consumerindex is missing, a default value has been assigned."; + case NMR_ERROR_KEYSTOREMISSINGKEKPARAMS: return "Element kekparams is missing, , default values have been assigned."; + case NMR_ERROR_KEYSTOREMISSINGCEKPARAMS: return "Element cekparams is missing."; + case NMR_ERROR_KEYSTOREMISSINGKEYUUID: return "Attribute keyuuid is missing, , a default value has been assigned."; + case NMR_ERROR_KEYSTOREMISSINGPATH: return "Attribute path is missing on a resouredata"; + case NMR_ERROR_KEYSTOREMISSINGALGORTHM: return "An algorithm attribute is missing, a default value has been assigned."; + case NMR_ERROR_KEYSTOREINCONSISTENTKEKPARAMS: return "Element kekparams ha invalid configuration"; + case NMR_ERROR_KEYSTOREOPCCOULDNOTGETSTREAM: return "Could not get KeyStore stream"; + case NMR_ERROR_KEYSTOREUNSUPPORTEDALGORITHM: return "The algorithm attribute is unsupported"; + case NMR_ERROR_KEYSTORETOOMANYELEMENTS: return "Too many elements added to a keystore tree"; + + // XML Parser Error Constants(0x9XXX) + case NMR_ERROR_XMLPARSER_INVALIDATTRIBVALUE: return "Invalid XML attribute value"; + case NMR_ERROR_XMLPARSER_INVALIDPARSERESULT: return "Invalid XML parse result"; + case NMR_ERROR_XMLPARSER_TOOMANYUSEDCHARS: return "Too many XML characters used"; + case NMR_ERROR_XMLPARSER_INVALIDENDDELIMITER: return "Invalid XML end delimiter"; + case NMR_ERROR_XMLPARSER_INVALIDNAMESPACEPREFIX: return "Invalid XML namespace prefix"; + case NMR_ERROR_XMLPARSER_COULDNOTPARSEENTITY: return "Could not parse XML entity"; + case NMR_ERROR_XMLPARSER_EMPTYELEMENTNAME: return "Empty XML element name"; + case NMR_ERROR_XMLPARSER_INVALIDCHARACTERINELEMENTNAME: return "Invalid characters in XML element name"; + case NMR_ERROR_XMLPARSER_EMPTYINSTRUCTIONNAME: return "Empty XML instruction name"; + case NMR_ERROR_XMLPARSER_INVALIDINSTRUCTIONNAME: return "Invalid XML instruction name"; + case NMR_ERROR_XMLPARSER_COULDNOTCLOSEINSTRUCTION: return "Could not close XML instruction"; + case NMR_ERROR_XMLPARSER_COULDNOTENDELEMENT: return "Could not end XML element"; + case NMR_ERROR_XMLPARSER_EMPTYENDELEMENT: return "Empty XML end element"; + case NMR_ERROR_XMLPARSER_COULDNOTCLOSEELEMENT: return "Could not close XML element"; + case NMR_ERROR_XMLPARSER_INVALIDATTRIBUTENAME: return "Invalid XML attribute name"; + case NMR_ERROR_XMLPARSER_SPACEINATTRIBUTENAME: return "Space in XML attribute name"; + case NMR_ERROR_XMLPARSER_NOQUOTESAROUNDATTRIBUTE: return "No quotes around XML attribute"; + case NMR_ERROR_DUPLICATE_RELATIONSHIP: return "A relationship is duplicated."; + case NMR_ERROR_DUPLICATE_CONTENTTYPE: return "A content type is duplicated."; + case NMR_ERROR_CONTENTTYPE_EMPTY_EXTENSION: return "A content type does not have a valid extension."; + case NMR_ERROR_CONTENTTYPE_EMPTY_CONTENTTYPE: return "A content type does not have a content type-value."; + case NMR_ERROR_CONTENTTYPE_EMPTY_PARTNAME: return "An override content type does not have a partname."; + case NMR_ERROR_XMLPARSER_INVALID_ESCAPESTRING: return "XML contains an invalid escape character."; + case NMR_ERROR_DUPLICATE_BOX_ATTRIBUTE: return "A box attribute is duplicated."; + case NMR_ERROR_DUPLICATE_MATINDICES_ATTRIBUTE: return "A matindices attribute is duplicated."; + + // Library errors (0xAXXX) + case NMR_ERROR_COULDNOTGETINTERFACEVERSION: return "Could not get interface version"; + case NMR_ERROR_INVALIDINTERFACEVERSION: return "Invalid interface version"; + case NMR_ERROR_INVALIDSTREAMSIZE: return "Invalid stream size"; + case NMR_ERROR_INVALIDNAMELENGTH: return "Invalid name length"; + case NMR_ERROR_COULDNOTCREATEMODEL: return "Could not create model"; + case NMR_ERROR_INVALIDTEXTURETYPE: return "Invalid Texture type"; + case NMR_ERROR_KEKDESCRIPTORNOTFOUND: return "Required key encryption client was not registered for a consumer"; + case NMR_ERROR_DEKDESCRIPTORNOTFOUND: return "Required data encryption client was not registered"; + case NMR_ERROR_RNGCALLBACKNOTCRYPTOSTRONG: return "Using cryptographically weak random number generator"; + + default: + return "unknown error"; + } + } + + nfError CNMRException::getErrorCode() const + { + return m_errorcode; + } + +} diff --git a/Source/Common/NMR_Exception_Windows.cpp b/Source/Common/NMR_Exception_Windows.cpp new file mode 100644 index 0000000..eeb1d8e --- /dev/null +++ b/Source/Common/NMR_Exception_Windows.cpp @@ -0,0 +1,52 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_Exception_Windows.cpp implements the Windows Exception Class. +Each exception is identified via a global ErrorCode, and saves a Win32 HRESULT +Error Code for further information + +(ErrorCodes to be looked up in NMR_ErrorConst.h) + +--*/ + +#include "Common/NMR_Exception_Windows.h" +#include + +namespace NMR { + + CNMRException_Windows::CNMRException_Windows(_In_ nfError errorcode, _In_ HRESULT hResult) : CNMRException(errorcode) + { + m_hResult = hResult; + } + + HRESULT CNMRException_Windows::getHResult() + { + return m_hResult; + } + +} diff --git a/Source/Common/NMR_ModelWarnings.cpp b/Source/Common/NMR_ModelWarnings.cpp new file mode 100644 index 0000000..ae796c6 --- /dev/null +++ b/Source/Common/NMR_ModelWarnings.cpp @@ -0,0 +1,107 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderWarnings.cpp implements the Model Reader Warnings Class. +This class collects all import warnings with certain severity levels - in order to allow +a relaxed import policy on the file format. + +--*/ + +#include "Common/NMR_ModelWarnings.h" + +namespace NMR { + + CModelWarning::CModelWarning(std::string sMessage, eModelWarningLevel WarningLevel, nfError nErrorCode) + { + m_sMessage = sMessage; + m_WarningLevel = WarningLevel; + m_nErrorCode = nErrorCode; + } + + std::string CModelWarning::getMessage() + { + return m_sMessage; + } + + eModelWarningLevel CModelWarning::getWarningLevel() + { + return m_WarningLevel; + } + + nfError CModelWarning::getErrorCode() + { + return m_nErrorCode; + } + + CModelWarnings::CModelWarnings() + { + setCriticalWarningLevel(mrwFatal); + } + + eModelWarningLevel CModelWarnings::getCriticalWarningLevel() + { + return m_CriticalWarningLevel; + } + + void CModelWarnings::setCriticalWarningLevel(_In_ eModelWarningLevel WarningLevel) + { + m_CriticalWarningLevel = WarningLevel; + } + + void CModelWarnings::addWarning(_In_ nfError nErrorCode, eModelWarningLevel WarningLevel) + { + CNMRException e(nErrorCode); + addException(e, WarningLevel); + } + + void CModelWarnings::addException(const _In_ CNMRException & Exception, _In_ eModelWarningLevel WarningLevel) + { + if (m_Warnings.size() < NMR_MAXWARNINGCOUNT) { // Failsafe check for Index overflows + std::string sMessage (Exception.what()); + + PModelReaderWarning pWarning = std::make_shared(sMessage, WarningLevel, Exception.getErrorCode()); + m_Warnings.push_back(pWarning); + } + + if ((nfInt32)WarningLevel <= (nfInt32)m_CriticalWarningLevel) + throw Exception; + } + + nfUint32 CModelWarnings::getWarningCount() + { + return (nfUint32)m_Warnings.size(); + } + + PModelReaderWarning CModelWarnings::getWarning(_In_ nfUint32 nIndex) + { + return m_Warnings[nIndex]; + } + + + +} diff --git a/Source/Common/NMR_SecureContext.cpp b/Source/Common/NMR_SecureContext.cpp new file mode 100644 index 0000000..8449ee2 --- /dev/null +++ b/Source/Common/NMR_SecureContext.cpp @@ -0,0 +1,35 @@ + +#include "Common/NMR_SecureContext.h" +#include "Common/NMR_Exception.h" +namespace NMR { + bool CSecureContext::hasDekCtx() const { + return m_bHasDek; + } + ContentEncryptionDescriptor CSecureContext::getDekCtx() const { + return m_sDekDescriptor; + } + void CSecureContext::setDekCtx(ContentEncryptionDescriptor const & descriptor) { + m_sDekDescriptor = descriptor; + m_bHasDek = true; + } + ClientConsumerMap::const_iterator CSecureContext::kekCtxBegin() const { + return m_ConsumerMap.cbegin(); + } + ClientConsumerMap::const_iterator CSecureContext::kekCtxEnd() const { + return m_ConsumerMap.cend(); + } + void CSecureContext::addKekCtx(std::string const & consumerId, KeyWrappingDescriptor const & descriptor) { + if (m_ConsumerMap.find(consumerId) != m_ConsumerMap.end()) + throw CNMRException(NMR_ERROR_KEYSTOREDUPLICATECONSUMERID); + m_ConsumerMap[consumerId] = descriptor; + } + KeyWrappingDescriptor CSecureContext::getKekCtx(std::string const & consumerId) const { + auto it = m_ConsumerMap.find(consumerId); + if (it != m_ConsumerMap.end()) + return (*it).second; + throw CNMRException(NMR_ERROR_KEKDESCRIPTORNOTFOUND); + } + bool CSecureContext::emptyKekCtx() const { + return m_ConsumerMap.empty(); + } +} \ No newline at end of file diff --git a/Source/Common/NMR_StringUtils.cpp b/Source/Common/NMR_StringUtils.cpp new file mode 100644 index 0000000..a6d37dd --- /dev/null +++ b/Source/Common/NMR_StringUtils.cpp @@ -0,0 +1,846 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_StringUtils.cpp implements a few string helper functions that handle strings +correctly and Exception-safe + +--*/ + +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include +#include +#include +#include +#include + +namespace NMR { + + // Lookup table to convert UTF8 bytes to sequence length + const nfByte UTF8DecodeTable[256] = { + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, + 4,4,4,4,4,4,4,4,5,5,5,5,6,6,0,0 + }; + + // Masks to decode highest UTF8 sequence byte + const nfByte UTF8DecodeMask[7] = {0, 0x7f, 0x1f, 0x0f, 0x07, 0x03, 0x01}; + + + template<> + float fnStringToType(_In_z_ const nfChar * pszValue) + { + return fnStringToFloat(pszValue); + } + template<> + double fnStringToType(_In_z_ const nfChar * pszValue) + { + return fnStringToDouble(pszValue); + } + template<> + nfInt32 fnStringToType(_In_z_ const nfChar * pszValue) + { + return fnStringToInt32(pszValue); + } + template<> + nfUint32 fnStringToType(_In_z_ const nfChar * pszValue) + { + return fnStringToUint32(pszValue); + } + template<> + unsigned long fnStringToType(_In_z_ const nfChar * pszValue) + { + return fnStringToUint32(pszValue); + } + template<> + std::string fnStringToType(_In_z_ const nfChar * pszValue) + { + return std::string(pszValue); + } + + + nfInt32 fnStringToInt32(_In_z_ const nfChar * pszValue) + { + __NMRASSERT(pszValue); + nfInt64 nResult = 0; + + // Convert to integer and make a input and range check! + nfChar * pEndPtr; + + nResult = strtol(pszValue, &pEndPtr, 10); + + // Check if any conversion happened + if ((pEndPtr == pszValue) || (!pEndPtr)) + throw CNMRException(NMR_ERROR_EMPTYSTRINGTOINTCONVERSION); + + if ((*pEndPtr != '\0') && (*pEndPtr != ' ')) + throw CNMRException(NMR_ERROR_INVALIDSTRINGTOINTCONVERSION); + + if ((nResult >= LONG_MAX) || (nResult <= LONG_MIN)) + throw CNMRException(NMR_ERROR_STRINGTOINTCONVERSIONOUTOFRANGE); + + return (nfInt32)nResult; + } + + nfUint32 fnStringToUint32(_In_z_ const nfChar * pszValue) + { + __NMRASSERT(pszValue); + nfUint64 nResult = 0; + + // Convert to integer and make a input and range check! + nfChar * pEndPtr; + + nResult = strtoul(pszValue, &pEndPtr, 10); + + // Check if any conversion happened + if ((pEndPtr == pszValue) || (!pEndPtr)) + throw CNMRException(NMR_ERROR_EMPTYSTRINGTOINTCONVERSION); + + if ((*pEndPtr != '\0') && (*pEndPtr != ' ')) + throw CNMRException(NMR_ERROR_INVALIDSTRINGTOINTCONVERSION); + + if (nResult >= ULONG_MAX) + throw CNMRException(NMR_ERROR_STRINGTOINTCONVERSIONOUTOFRANGE); + + return (nfUint32)nResult; + } + + nfFloat fnStringToFloat(_In_z_ const nfChar * pszValue) + { + return (nfFloat)fnStringToDouble(pszValue); + } + + nfDouble fnStringToDouble(_In_z_ const nfChar * pszValue) + { + __NMRASSERT(pwszValue); + nfDouble dResult = 0.0; + + // Convert to double and make a input and range check! + nfChar * pEndPtr; + + dResult = strtod(pszValue, &pEndPtr); + + // Check if any conversion happened + if ((pEndPtr == pszValue) || (!pEndPtr)) + throw CNMRException(NMR_ERROR_EMPTYSTRINGTODOUBLECONVERSION); + + if ((*pEndPtr != '\0') && (*pEndPtr != ' ')) + throw CNMRException(NMR_ERROR_INVALIDSTRINGTODOUBLECONVERSION); + + if ((dResult == HUGE_VAL) || (dResult == -HUGE_VAL)) + throw CNMRException(NMR_ERROR_STRINGTODOUBLECONVERSIONOUTOFRANGE); + + return dResult; + } + + std::string fnInt32ToString(_In_ nfInt32 nValue) + { + std::stringstream sStream; + sStream << nValue; + return sStream.str(); + } + + std::string fnUint32ToString(_In_ nfUint32 nValue) + { + std::stringstream sStream; + sStream << nValue; + return sStream.str(); + } + + std::string fnFloatToString(_In_ nfFloat fValue, _In_ nfUint32 precision) + { + std::stringstream sStream; + sStream << fValue; + return sStream.str(); + } + + nfChar fnColorDigitToHex(_In_ nfByte digit) + { + if (digit < 10) + return (nfChar)(digit + 48); + if (digit < 16) + return (nfChar)(digit + 55); + + return L' '; + } + + std::string fnColorToString(_In_ nfColor cColor) + { + nfChar pBuffer[16]; + pBuffer[0] = '#'; + pBuffer[2] = fnColorDigitToHex(cColor & 0xf); // R + pBuffer[1] = fnColorDigitToHex((cColor >> 4) & 0xf); // R + pBuffer[4] = fnColorDigitToHex((cColor >> 8) & 0xf); // G + pBuffer[3] = fnColorDigitToHex((cColor >> 12) & 0xf); // G + pBuffer[6] = fnColorDigitToHex((cColor >> 16) & 0xf); // B + pBuffer[5] = fnColorDigitToHex((cColor >> 20) & 0xf); // B + pBuffer[8] = fnColorDigitToHex((cColor >> 24) & 0xf); // A + pBuffer[7] = fnColorDigitToHex((cColor >> 28) & 0xf); // A + pBuffer[9] = 0; + + return std::string(pBuffer); + } + + std::string fnDoubleToString(_In_ nfFloat dValue, _In_ nfUint32 precision) + { + std::stringstream sStream; + sStream << dValue; + return sStream.str(); + } + + nfBool fnStringToSRGBColor(_In_z_ const nfChar * pszValue, _Out_ nfColor & cResult) + { + cResult = 0; + + if (!pszValue) + return false; + + nfUint32 nRed = 255; + nfUint32 nGreen = 255; + nfUint32 nBlue = 255; + nfUint32 nAlpha = 255; + + std::string sString(pszValue); + if (sString.length() == 7) { + if (sString[0] != '#') + return false; + + nRed = fnHexStringToUint32(sString.substr(1, 2).c_str()); + nGreen = fnHexStringToUint32(sString.substr(3, 2).c_str()); + nBlue = fnHexStringToUint32(sString.substr(5, 2).c_str()); + + cResult = nRed | (nGreen << 8) | (nBlue << 16) | (nAlpha << 24); + + return true; + } + + if (sString.length() == 9) { + if (sString[0] != '#') + return false; + + nRed = fnHexStringToUint32(sString.substr(1, 2).c_str()); + nGreen = fnHexStringToUint32(sString.substr(3, 2).c_str()); + nBlue = fnHexStringToUint32(sString.substr(5, 2).c_str()); + nAlpha = fnHexStringToUint32(sString.substr(7, 2).c_str()); + + cResult = nRed | (nGreen << 8) | (nBlue << 16) | (nAlpha << 24); + + return true; + } + + return false; + } + + nfUint32 fnHexStringToUint32(_In_z_ const nfChar * pszValue) + { + if (!pszValue) + return 0; + nfChar * p; + nfUint64 nResult = strtoul(pszValue, &p, 16); + if (*p != 0) + throw CNMRException(NMR_ERROR_INVALIDHEXVALUE); + if (nResult >= ULONG_MAX) + throw CNMRException(NMR_ERROR_RANGEERROR); + + return (nfUint32)nResult; + } + + nfInt32 fnStringToInt32Comma(_In_z_ const nfChar * pszValue) + { + __NMRASSERT(pwszValue); + nfInt64 nResult = 0; + + // Convert to integer and make a input and range check! + nfChar * pEndPtr; + + nResult = strtol(pszValue, &pEndPtr, 10); + + // Check if any conversion happened + if ((pEndPtr == pszValue) || (!pEndPtr)) + throw CNMRException(NMR_ERROR_EMPTYSTRINGTOINTCONVERSION); + + if ((*pEndPtr != '\0') && (*pEndPtr != ' ') && (*pEndPtr != ',')) + throw CNMRException(NMR_ERROR_INVALIDSTRINGTOINTCONVERSION); + + if ((nResult >= LONG_MAX) || (nResult <= LONG_MIN)) + throw CNMRException(NMR_ERROR_STRINGTOINTCONVERSIONOUTOFRANGE); + + return (nfUint32)nResult; + } + + + void fnStringToCommaSeparatedIntegerTriplet(_In_z_ const nfChar * pszValue, _Out_ nfInt32 & nValue1, _Out_ nfInt32 & nValue2, _Out_ nfInt32 & nValue3) + { + const nfChar * pszCommaValue1 = strchr(pszValue, ','); + if (pszCommaValue1 != nullptr) { + if (*pszCommaValue1 == 0) + throw CNMRException(NMR_ERROR_INVALIDINTEGERTRIPLET); + pszCommaValue1++; + + const nfChar * pszCommaValue2 = strchr(pszCommaValue1, ','); + if (pszCommaValue2 != nullptr) { + if (*pszCommaValue2 == 0) + throw CNMRException(NMR_ERROR_INVALIDINTEGERTRIPLET); + pszCommaValue2++; + + nValue1 = fnStringToInt32Comma(pszValue); + nValue2 = fnStringToInt32Comma(pszCommaValue1); + nValue3 = fnStringToInt32Comma(pszCommaValue2); + } + else + throw CNMRException(NMR_ERROR_INVALIDINTEGERTRIPLET); + + } + else + throw CNMRException(NMR_ERROR_INVALIDINTEGERTRIPLET); + + } + + void fnWStringToBufferSafe(_In_ const std::wstring sString, _Out_opt_ nfWChar * pwszBuffer, nfUint32 cbBufferSize, _Out_opt_ nfUint32 * pcbNeededChars) + { + __NMRASSERT(pwszBuffer); + + // Check for possible integer overflows + size_t cbLength = sString.length(); + if (cbLength > NMR_MAXSTRINGBUFFERSIZE) + throw CNMRException(NMR_ERROR_INVALIDBUFFERSIZE); + + // return used buffer size + nfUint32 cbNeededChars = ((nfUint32)cbLength); + if (pcbNeededChars) + *pcbNeededChars = cbNeededChars; + + // copy string + if (pwszBuffer) { + if (cbNeededChars >= cbBufferSize) + throw CNMRException(NMR_ERROR_INSUFFICIENTBUFFERSIZE); + +#ifndef __GNUC__ + wcscpy_s(pwszBuffer, cbBufferSize, sString.c_str()); +#else + wcscpy(pwszBuffer, sString.c_str()); +#endif + } + } + + + template<> std::string fnVectorToSpaceDelimitedString(_In_ const std::vector v) + { + std::string result = ""; + for (auto i = v.begin(); i != v.end(); i++) { + if (i != v.begin()) + result += " "; + result += (*i); + } + return result; + }; + + + + void fnStringToBufferSafe(_In_ const std::string sString, _Out_opt_ nfChar * pszBuffer, nfUint32 cbBufferSize, _Out_opt_ nfUint32 * pcbNeededChars) + { + __NMRASSERT(pszBuffer); + + // Check for possible integer overflows + size_t cbLength = sString.length(); + if (cbLength > NMR_MAXSTRINGBUFFERSIZE) + throw CNMRException(NMR_ERROR_INVALIDBUFFERSIZE); + + // return used buffer size + nfUint32 cbNeededChars = ((nfUint32)cbLength); + if (pcbNeededChars) + *pcbNeededChars = cbNeededChars; + + // copy string + if (pszBuffer) { + if (cbNeededChars >= cbBufferSize) + throw CNMRException(NMR_ERROR_INSUFFICIENTBUFFERSIZE); + +#ifndef __GNUC__ + strcpy_s(pszBuffer, cbBufferSize, sString.c_str()); +#else + strcpy(pszBuffer, sString.c_str()); +#endif + } + } + + // UTF conversion functions + nfBool fnUTF16CharIsSurrogate(_In_ nfWChar cChar) + { + nfUint32 nSignature = (cChar & 0xfc00); + return (nSignature == 0xd800) || (nSignature == 0xdc00); + } + + nfBool fnUTF16CharIsHighSurrogate(_In_ nfWChar cChar) + { + nfUint32 nSignature = (cChar & 0xfc00); + return (nSignature == 0xd800); + } + + nfBool fnUTF16CharIsLowSurrogate(_In_ nfWChar cChar) + { + nfUint32 nSignature = (cChar & 0xfc00); + return (nSignature == 0xdc00); + } + + nfUint32 fnUTF16toCharacterID(_In_ nfUint16 nHighSurrogate, _In_ nfUint16 nLowSurrogate) + { + if ((fnUTF16CharIsHighSurrogate(nLowSurrogate)) && (fnUTF16CharIsLowSurrogate(nHighSurrogate))) { + std::swap(nLowSurrogate, nHighSurrogate); // UTF16LE + } + + if ((!fnUTF16CharIsHighSurrogate(nHighSurrogate)) || (!fnUTF16CharIsLowSurrogate(nLowSurrogate))) + throw CNMRException(NMR_ERROR_COULDNOTCONVERTTOUTF8); + + nfUint32 nCode = (((nfUint32)(nHighSurrogate & 0x3ff)) << 10 | ((nfUint32)(nLowSurrogate & 0x3ff))); + return nCode + 0x10000; + } + + void fnCharacterIDToUTF16(_In_ nfUint32 nCharacterID, _Out_ nfUint16 & nHighSurrogate, _Out_ nfUint16 & nLowSurrogate) + { + if ((nCharacterID < 0x10000) || (nCharacterID > 0x10FFFF)) + throw CNMRException(NMR_ERROR_COULDNOTCONVERTTOUTF16); + nCharacterID -= 0x10000; + nHighSurrogate = (nCharacterID >> 10) | 0xd800; + nLowSurrogate = (nCharacterID & 0x3ff) | 0xdc00; + } + + + std::string fnUTF16toUTF8(_In_ const std::wstring sString) + { + + // Check Input Sanity + size_t nLength = sString.length(); + if (nLength == 0) + return ""; + if (nLength > NMR_MAXSTRINGBUFFERSIZE) + throw CNMRException(NMR_ERROR_INVALIDBUFFERSIZE); + + // Reserve UTF8 Buffer + nfUint32 nBufferSize = (nfUint32)nLength * 4 + 1; + std::vector Buffer; + Buffer.resize(nBufferSize); + + // nfInt32 nResult; + // Alternative: Convert via Win API + // nResult = WideCharToMultiByte(CP_UTF8, 0, sString.c_str(), (nfUint32)nLength, &Buffer[0], nBufferSize, nullptr, nullptr); + // if (nResult == 0) + // throw CNMRException(NMR_ERROR_COULDNOTCONVERTTOUTF8); + + const nfWChar * pChar = sString.c_str(); + nfChar * pOutput = &Buffer[0]; + + while (*pChar) { + nfWChar cChar = *pChar; + nfUint32 nCharacter; + pChar++; + + if (fnUTF16CharIsSurrogate(cChar)) { + nfWChar cLowChar = *pChar; + if (cLowChar == 0) + throw CNMRException(NMR_ERROR_COULDNOTCONVERTTOUTF8); + pChar++; + + nCharacter = fnUTF16toCharacterID(cChar, cLowChar); + } + else { + nCharacter = cChar; + } + + if (nCharacter < 0x80) { + // One Byte Encoding + *pOutput = nCharacter; + pOutput++; + } + else if (nCharacter < 0x800) { + // Two Byte Encoding + *pOutput = (nCharacter >> 6) | 0xC0; + pOutput++; + *pOutput = (nCharacter & 0x3f) | 0x80; + pOutput++; + } + else if (nCharacter < 0x10000) { + // Three Byte Encoding + *pOutput = (nCharacter >> 12) | 0xE0; + pOutput++; + *pOutput = ((nCharacter >> 6) & 0x3f) | 0x80; + pOutput++; + *pOutput = (nCharacter & 0x3f) | 0x80; + pOutput++; + } + else if (nCharacter < 0x200000) { + // Four Byte Encoding + *pOutput = (nCharacter >> 18) | 0xF0; + pOutput++; + *pOutput = ((nCharacter >> 12) & 0x3f) | 0x80; + pOutput++; + *pOutput = ((nCharacter >> 6) & 0x3f) | 0x80; + pOutput++; + *pOutput = (nCharacter & 0x3f) | 0x80; + pOutput++; + } + else if (nCharacter < 0x4000000) { + // Five Byte Encoding + *pOutput = (nCharacter >> 24) | 0xF8; + pOutput++; + *pOutput = ((nCharacter >> 18) & 0x3f) | 0x80; + pOutput++; + *pOutput = ((nCharacter >> 12) & 0x3f) | 0x80; + pOutput++; + *pOutput = ((nCharacter >> 6) & 0x3f) | 0x80; + pOutput++; + *pOutput = (nCharacter & 0x3f) | 0x80; + pOutput++; + } + else { + // Six Byte Encoding + *pOutput = (nCharacter >> 30) | 0xFC; + pOutput++; + *pOutput = ((nCharacter >> 24) & 0x3f) | 0x80; + pOutput++; + *pOutput = ((nCharacter >> 18) & 0x3f) | 0x80; + pOutput++; + *pOutput = ((nCharacter >> 12) & 0x3f) | 0x80; + pOutput++; + *pOutput = ((nCharacter >> 6) & 0x3f) | 0x80; + pOutput++; + *pOutput = (nCharacter & 0x3f) | 0x80; + pOutput++; + } + + } + + // write end byte + *pOutput = 0; + + return std::string(&Buffer[0]); + + } + + + + + std::wstring fnUTF8toUTF16(_In_ const std::string sString) + { + + // Check Input Sanity + size_t nLength = sString.length(); + if (nLength == 0) + return L""; + if (nLength > NMR_MAXSTRINGBUFFERSIZE) + throw CNMRException(NMR_ERROR_INVALIDBUFFERSIZE); + + // Reserve UTF8 Buffer + nfUint32 nBufferSize = (nfUint32)nLength; + std::vector Buffer; + Buffer.resize(nBufferSize * 2 + 2); + + // Alternative: Convert via Win API + // nfInt32 nResult; + //nResult = MultiByteToWideChar(CP_UTF8, 0, sString.c_str(), (nfUint32)nLength, &Buffer[0], nBufferSize); + //if (nResult == 0) + //throw CNMRException(NMR_ERROR_COULDNOTCONVERTTOUTF16); + + const nfChar * pChar = sString.c_str(); + nfWChar * pOutput = &Buffer[0]; + + while (*pChar) { + nfByte cChar = (nfByte) *pChar; + nfUint32 nLength = UTF8DecodeTable[(nfUint32)cChar]; + pChar++; + + if (nLength == 0) + throw CNMRException(NMR_ERROR_COULDNOTCONVERTTOUTF16); + __NMRASSERT(nLength <= 6); + + // Check for BOM (0xEF,0xBB,0xBF), this also checks for #0 characters at the end, + // so it does not read over the string end! + nfBool bIsBOM = false; + if (cChar == 0xef) { + if (*((const nfByte*) pChar) == 0xbb) { + if (*((const nfByte*) (pChar + 1)) == 0xbf) { + bIsBOM = true; + } + } + }; + + + if (!bIsBOM) { + nfUint32 nCode = cChar & UTF8DecodeMask[nLength]; + + while (nLength > 1) { + cChar = *pChar; + if ((cChar & 0xc0) != 0x80) + throw CNMRException(NMR_ERROR_COULDNOTCONVERTTOUTF16); + pChar++; + + // Map UTF8 sequence to code + nCode = (nCode << 6) | (cChar & 0x3f); + nLength--; + } + + // Map Code to UTF16 + if ((nCode < 0xd800) || ((nCode >= 0xe000) && (nCode <= 0xffff))) { + *pOutput = nCode; + pOutput++; + } + else { + nfUint16 nHighSurrogate, nLowSurrogate; + fnCharacterIDToUTF16(nCode, nHighSurrogate, nLowSurrogate); + *pOutput = nHighSurrogate; + pOutput++; + *pOutput = nLowSurrogate; + pOutput++; + } + } + else { + // If we find a UTF8 bom, we just ignore it. + __NMRASSERT(nLength == 3); + pChar += 2; + } + } + + // write end byte + *pOutput = 0; + + return std::wstring(&Buffer[0]); + + } + + + nfUint32 fnBufferedUTF8toUTF16(_In_ const nfChar * pszInBuffer, _Out_ nfWChar * pszwOutBuffer, _In_ nfUint32 cbBufferSize, _Out_ nfUint32 * pnLastChar, _Out_ nfUint32 * pcbNeededCharacters) + { + if (pszInBuffer == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + if (pszwOutBuffer == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + if ((pnLastChar == nullptr) || (pcbNeededCharacters == nullptr)) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + if (cbBufferSize > NMR_MAXSTRINGBUFFERSIZE) + throw CNMRException(NMR_ERROR_INVALIDBUFFERSIZE); + + // Set default values + nfUint32 cbOutCount = 0; + *pnLastChar = 0; + *pcbNeededCharacters = 0; + + // Set iterating pointers + const nfChar * pInChar = pszInBuffer; + nfWChar * pOutChar = pszwOutBuffer; + + // Iterate through input + nfInt32 cbCount = (nfInt32) cbBufferSize; + while (cbCount > 0) { + nfByte cChar = *pInChar; + + // Check Multibyte Length Character + nfUint32 nLength = UTF8DecodeTable[(nfUint32)cChar]; + if (nLength == 0) + throw CNMRException(NMR_ERROR_COULDNOTCONVERTTOUTF16); + __NMRASSERT(nLength <= 6); + + // If we do not have enough Bytes left for the multibyte character, return needed count. + if (((nfInt32) nLength) > cbCount) { + *pcbNeededCharacters = nLength - cbCount; + return cbOutCount; + } + + // Set multibyte character to next char + *pnLastChar += nLength; + + // Read multibyte character byte by byte. + pInChar++; + cbCount--; + + // Check for BOM (0xEF,0xBB,0xBF), this also checks for #0 characters at the end, + // so it does not read over the string end! + nfBool bIsBOM = false; + if (cChar == 0xef) { + if (*((const nfByte *)pInChar) == 0xbb) { + if (*((const nfByte *) (pInChar + 1)) == 0xbf) { + bIsBOM = true; + } + } + }; + + if (!bIsBOM) { + // create utf16 code + nfUint32 nCode = cChar & UTF8DecodeMask[nLength]; + + while (nLength > 1) { + cChar = *pInChar; + if ((cChar & 0xc0) != 0x80) + throw CNMRException(NMR_ERROR_COULDNOTCONVERTTOUTF16); + pInChar++; + cbCount--; + + // Map UTF8 sequence to code + nCode = (nCode << 6) | (cChar & 0x3f); + nLength--; + } + + // Map Code to UTF16 + if ((nCode < 0xd800) || ((nCode >= 0xe000) && (nCode <= 0xffff))) { + *pOutChar = nCode; + pOutChar++; + cbOutCount++; + } + else { + nfUint16 nHighSurrogate, nLowSurrogate; + fnCharacterIDToUTF16(nCode, nHighSurrogate, nLowSurrogate); + *pOutChar = nHighSurrogate; + pOutChar++; + *pOutChar = nLowSurrogate; + pOutChar++; + + cbOutCount += 2; + } + } + else { + __NMRASSERT(nLength == 3); + pInChar += 2; + cbCount -= 2; + + } + + } + + // everything has been processed. + return cbOutCount; + + } + + nfBool fnStartsWithPathDelimiter(_In_ const std::string sPath) + { + const nfChar * pChar = sPath.c_str(); + return ((*pChar == '/') || (*pChar == '\\')); + } + + std::string fnRemoveLeadingPathDelimiter(_In_ const std::string sPath) + { + const nfChar * pChar = sPath.c_str(); + + while ((*pChar == '/') || (*pChar == '\\')) + pChar++; + + return std::string(pChar); + } + + std::string fnIncludeLeadingPathDelimiter(_In_ const std::string sPath) + { + if (sPath.length() == 0) { + return "/"; + } + + const nfChar * pChar = sPath.c_str(); + if ((*pChar == '/') || (*pChar == '\\')) + return sPath; + std::string sPrefix = "/"; + + return sPrefix + sPath; + } + + std::string fnExtractFileName(_In_ const std::string sFullPath) + { + const nfChar * pChar = sFullPath.c_str(); + const nfChar * pLastDelimiter = nullptr; + + while (*pChar != 0) { + if ((*pChar == '/') || (*pChar == '\\')) + pLastDelimiter = pChar; + + pChar++; + } + + if (pLastDelimiter != nullptr) { + // Leave away delimiter + pLastDelimiter++; + return std::string(pLastDelimiter); + } + else { + // We have no directory given + return sFullPath; + } + } + + std::string fnExtractFileDir(_In_ const std::string sFullPath) + { + const nfChar * pChar = sFullPath.c_str(); + const nfChar * pLastDelimiter = nullptr; + + while (*pChar != 0) { + if ((*pChar == '/') || (*pChar == '\\')) + pLastDelimiter = pChar; + pChar++; + } + + if (pLastDelimiter != nullptr) { + // Leave away delimiter + pLastDelimiter++; + return sFullPath.substr(0, pLastDelimiter - sFullPath.c_str()); + } + else { + // We have no directory given + return std::string(""); + } + } + + void decomposeKeyIntoNamespaceAndName(const std::string &sKey, std::string &sNameSpace, std::string &sName) { + size_t cInd = sKey.find(":"); + if (cInd != std::string::npos) { + sNameSpace = sKey.substr(0, cInd); + sName = sKey.substr(cInd + 1, sKey.length() - cInd); + } + else { + sNameSpace = ""; + sName = sKey; + } + } + + std::string composeNamespaceAndNameIntoKey(const std::string &sNameSpace, const std::string &sName) + { + if (sNameSpace.empty()) + return sName; + else + return sNameSpace + ":" + sName; + } + +} diff --git a/Source/Common/NMR_UUID.cpp b/Source/Common/NMR_UUID.cpp new file mode 100644 index 0000000..8fdd0c9 --- /dev/null +++ b/Source/Common/NMR_UUID.cpp @@ -0,0 +1,151 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_UUID.cpp implements a datatype and functions to handle UUIDs + +--*/ + +#include "Common/NMR_UUID.h" + +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" + +#include + +#ifdef _WIN32 +#include +#include +#else +#include +#endif + +namespace NMR +{ +#ifndef _WIN32 + bool CUUID::S_mtwister_initialised = false; + std::mutex CUUID::S_uuid_gen_mutex; + std::random_device CUUID::S_rand_dev; + std::mt19937 CUUID::S_mtwister; +#endif + + CUUID::CUUID() + { +#ifdef _WIN32 + GUID guid; + if (CoCreateGuid(&guid) != S_OK) + throw CNMRException(NMR_ERROR_UUIDGENERATIONFAILED); + LPOLESTR str; + if (StringFromCLSID(guid, &str) != S_OK) + throw CNMRException(NMR_ERROR_UUIDGENERATIONFAILED); + set(fnUTF16toUTF8(str).c_str()); +#else + std::lock_guard l_lock(S_uuid_gen_mutex); + if (!S_mtwister_initialised) + { + // Prepare seed data + uint32_t l_seed_data[std::mt19937::state_size]; + uint32_t l_cur_time = static_cast(time(nullptr)); + for (size_t i = 0; i < std::mt19937::state_size; ++i) + { + l_seed_data[i] = S_rand_dev() ^ l_cur_time; + } + + // Init Mersenne Twister pseudo-random generator + std::seed_seq l_seed_seq(std::begin(l_seed_data), std::end(l_seed_data)); + S_mtwister.seed(l_seed_seq); + + S_mtwister_initialised = true; + } + + // generation of a v4 UUID according to https://tools.ietf.org/html/rfc4122#section-4.4 + std::uniform_int_distribution distHexaDec(0, 15); + std::uniform_int_distribution dist4(0, 4); + const nfChar* hexaDec = "0123456789abcdef"; + nfChar string[33]; + for (int i = 0; i < 32; i++) + string[i] = hexaDec[distHexaDec(S_mtwister)]; + string[12] = hexaDec[4]; // set version 4 + string[16] = hexaDec[8 + dist4(S_mtwister)]; + string[32] = 0; + + set(string); +#endif + } + + CUUID::CUUID(const nfChar* pString) + { + set(pString); + } + + CUUID::CUUID(const std::string &string) + { + set(string.c_str()); + } + + std::string CUUID::toString() const + { + return m_sUUID; + } + + bool InValid(char c) + { + return !(((c >= '0') && (c <= '9')) + || ((c >= 'a') && (c <= 'f')) + // || (c == '-') + ); + } + + bool CUUID::set(const nfChar* pString) + { + // to lowercase, remove all non hex characters, insert dashes again + std::string str = pString; + std::transform(str.begin(), str.end(), str.begin(), ::tolower); + str.erase(std::remove_if(str.begin(), str.end(), &InValid), str.end()); + if (str.length() != 32) { + throw CNMRException(NMR_ERROR_ILLFORMATUUID); + } + m_sUUID = str.substr(0, 8) + '-' + str.substr(8, 4) + '-' + str.substr(12, 4) + '-' + str.substr(16, 4) + '-' + str.substr(20, 12); + return true; + } + + CUUID& CUUID::operator=(const CUUID& uuid) + { + if (&uuid == this) + return *this; + m_sUUID = uuid.m_sUUID; + return *this; + } + + bool CUUID::operator==(const CUUID& uuid) + { + if (&uuid == this) + return true; + return m_sUUID == uuid.m_sUUID; + } + +} diff --git a/Source/Common/OPC/NMR_OpcPackageContentTypesReader.cpp b/Source/Common/OPC/NMR_OpcPackageContentTypesReader.cpp new file mode 100644 index 0000000..f5303c5 --- /dev/null +++ b/Source/Common/OPC/NMR_OpcPackageContentTypesReader.cpp @@ -0,0 +1,288 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_OpcPackageReader.cpp defines an OPC Package reader of .rels files in a portable way. + +--*/ + +#include "Common/OPC/NMR_OpcPackageContentTypesReader.h" +#include "Common/OPC/NMR_OpcPackageTypes.h" +#include "Common/Platform/NMR_Platform.h" +#include "Common/Platform/NMR_WinTypes.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_StringUtils.h" + +namespace NMR { + + COpcPackageContentTypesReader::COpcPackageContentTypesReader(_In_ PImportStream pImportStream, PProgressMonitor pProgressMonitor) + { + if (pImportStream.get() == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + if (pProgressMonitor.get() == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + pProgressMonitor->ReportProgressAndQueryCancelled(true); + PXmlReader pXMLReader = fnCreateXMLReaderInstance(pImportStream, pProgressMonitor); + + eXmlReaderNodeType NodeType; + // Read all XML Root Nodes + while (!pXMLReader->IsEOF()) { + if (!pXMLReader->Read(NodeType)) + break; + + // Get Node Name + LPCSTR pszLocalName = nullptr; + pXMLReader->GetLocalName(&pszLocalName, nullptr); + if (!pszLocalName) + throw CNMRException(NMR_ERROR_COULDNOTGETLOCALXMLNAME); + + // Compare with Model Node Name + if (strcmp(pszLocalName, OPC_CONTENTTYPES_CONTAINER) == 0) { + parseRootNode(pXMLReader.get()); + } + } + } + + + COpcPackageContentTypesReader::~COpcPackageContentTypesReader() + { + + } + + void COpcPackageContentTypesReader::parseRootNode(_In_ CXmlReader * pXMLReader) + { + if (pXMLReader == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + parseAttributes(pXMLReader); + + while (!pXMLReader->IsEOF()) { + LPCSTR pszLocalName = nullptr; + LPCSTR pszNameSpaceURI = nullptr; + UINT nCount = 0; + UINT nNameSpaceCount = 0; + + eXmlReaderNodeType NodeType; + pXMLReader->Read(NodeType); + + switch (NodeType) { + case XMLREADERNODETYPE_STARTELEMENT: + pXMLReader->GetLocalName(&pszLocalName, &nCount); + if (!pszLocalName) + throw CNMRException(NMR_ERROR_COULDNOTGETLOCALXMLNAME); + + pXMLReader->GetNamespaceURI(&pszNameSpaceURI, &nNameSpaceCount); + if (!pszNameSpaceURI) + throw CNMRException(NMR_ERROR_COULDNOTGETNAMESPACE); + + if (nCount > 0) { + if (strcmp(pszNameSpaceURI, OPCPACKAGE_SCHEMA_CONTENTTYPES) == 0) { + if (strcmp(pszLocalName, OPC_CONTENTTYPES_NODE) == 0) { + parseChildNode(pXMLReader, false); + } + else if (strcmp(pszLocalName, OPC_CONTENTTYPES_NODE_OVERRIDE) == 0) { + parseChildNode(pXMLReader, true); + } + else + throw CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT); + } + } + break; + + case XMLREADERNODETYPE_ENDELEMENT: + pXMLReader->GetLocalName(&pszLocalName, &nCount); + if (!pszLocalName) + throw CNMRException(NMR_ERROR_COULDNOTGETLOCALXMLNAME); + + if (strcmp(pszLocalName, OPC_CONTENTTYPES_CONTAINER) == 0) { + return; + } + pXMLReader->CloseElement(); + break; + + case XMLREADERNODETYPE_UNKNOWN: + break; + + case XMLREADERNODETYPE_TEXT: + break; + } + } + } + + + void COpcPackageContentTypesReader::parseChildNode(_In_ CXmlReader * pXMLReader, _In_ bool bOverride) + { + if (pXMLReader == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + if (!pXMLReader->MoveToFirstAttribute()) + return; + + std::string sExtension; + std::string sPartName; + std::string sContentType; + + nfBool bContinue = true; + while (bContinue) { + + if (!pXMLReader->IsDefault()) { + LPCSTR pszLocalName = nullptr; + LPCSTR pszNameSpaceURI = nullptr; + LPCSTR pszValue = nullptr; + UINT nNameCount = 0; + UINT nValueCount = 0; + UINT nNameSpaceCount = 0; + + // Get Attribute Name + pXMLReader->GetNamespaceURI(&pszNameSpaceURI, &nNameSpaceCount); + if (!pszNameSpaceURI) + throw CNMRException(NMR_ERROR_COULDNOTGETNAMESPACE); + + pXMLReader->GetLocalName(&pszLocalName, &nNameCount); + if (!pszLocalName) + throw CNMRException(NMR_ERROR_COULDNOTGETLOCALXMLNAME); + + // Get Attribute Value + pXMLReader->GetValue(&pszValue, &nValueCount); + if (!pszValue) + throw CNMRException(NMR_ERROR_COULDNOTGETXMLVALUE); + + if (nNameSpaceCount == 0) { + if (strcmp(pszLocalName, OPC_CONTENTTYPES_ATTRIB_EXTENSION) == 0) + sExtension = pszValue; + if (strcmp(pszLocalName, OPC_CONTENTTYPES_ATTRIB_CONTENTTYPE) == 0) + sContentType = pszValue; + if (strcmp(pszLocalName, OPC_CONTENTTYPES_ATTRIB_PARTNAME) == 0) + sPartName = pszValue; + } + + } + + bContinue = pXMLReader->MoveToNextAttribute(); + } + + if (sContentType.empty()) + throw CNMRException(NMR_ERROR_CONTENTTYPE_EMPTY_CONTENTTYPE); + + if (bOverride) { + if (sPartName.empty()) + throw CNMRException(NMR_ERROR_CONTENTTYPE_EMPTY_PARTNAME); + + POpcPackageContentType_Override pRelationShip = std::make_shared(sPartName, sContentType); + for (auto it : m_Overrides) { + if (it->m_partName == sPartName) + throw CNMRException(NMR_ERROR_DUPLICATE_CONTENTTYPE); + } + m_Overrides.push_back(pRelationShip); + } + else { + if (sExtension.empty()) + throw CNMRException(NMR_ERROR_CONTENTTYPE_EMPTY_EXTENSION); + + POpcPackageContentType pContentType = std::make_shared(sExtension, sContentType); + for (auto it : m_ContentTypes) { + if (it->m_extension == sExtension) + throw CNMRException(NMR_ERROR_DUPLICATE_CONTENTTYPE); + } + m_ContentTypes.push_back(pContentType); + } + + + + pXMLReader->CloseElement(); + } + + nfUint32 COpcPackageContentTypesReader::getCount() + { + return (nfUint32)m_ContentTypes.size(); + } + + POpcPackageContentType COpcPackageContentTypesReader::getContentType(_In_ nfUint32 nIndex) + { + nfUint32 nCount = (nfUint32)m_ContentTypes.size(); + if (nIndex >= nCount) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + + return m_ContentTypes[nIndex]; + } + + nfUint32 COpcPackageContentTypesReader::getOverrideCount() + { + return (nfUint32)m_Overrides.size(); + } + + POpcPackageContentType_Override COpcPackageContentTypesReader::getOverrideContentType(_In_ nfUint32 nIndex) + { + nfUint32 nCount = (nfUint32)m_Overrides.size(); + if (nIndex >= nCount) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + + return m_Overrides[nIndex]; + } + + void COpcPackageContentTypesReader::parseAttributes(_In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pXMLReader); + + if (!pXMLReader->MoveToFirstAttribute()) + return; + + nfBool bContinue = true; + while (bContinue) { + + if (!pXMLReader->IsDefault()) { + LPCSTR pszLocalName = nullptr; + LPCSTR pszNameSpaceURI = nullptr; + LPCSTR pszValue = nullptr; + UINT nNameCount = 0; + UINT nValueCount = 0; + UINT nNameSpaceCount = 0; + + // Get Attribute Name + pXMLReader->GetNamespaceURI(&pszNameSpaceURI, &nNameSpaceCount); + if (!pszNameSpaceURI) + throw CNMRException(NMR_ERROR_COULDNOTGETNAMESPACE); + + pXMLReader->GetLocalName(&pszLocalName, &nNameCount); + if (!pszLocalName) + throw CNMRException(NMR_ERROR_COULDNOTGETLOCALXMLNAME); + + // Get Attribute Value + pXMLReader->GetValue(&pszValue, &nValueCount); + if (!pszValue) + throw CNMRException(NMR_ERROR_COULDNOTGETXMLVALUE); + } + + bContinue = pXMLReader->MoveToNextAttribute(); + } + } + + +} + + diff --git a/Source/Common/OPC/NMR_OpcPackagePart.cpp b/Source/Common/OPC/NMR_OpcPackagePart.cpp new file mode 100644 index 0000000..68b2afd --- /dev/null +++ b/Source/Common/OPC/NMR_OpcPackagePart.cpp @@ -0,0 +1,151 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_OpcPackagePart.cpp implements an OPC Package Part in a portable way. + +--*/ + +#include "Common/OPC/NMR_OpcPackagePart.h" +#include "Common/OPC/NMR_OpcPackageRelationship.h" +#include "Common/NMR_Exception.h" +#include "Common/Platform/NMR_XmlWriter_Native.h" + +namespace NMR { + + COpcPackagePart::COpcPackagePart(_In_ std::string sURI, _In_ PExportStream pExportStream) + { + if (pExportStream.get() == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + if (sURI.length() == 0) + throw CNMRException(NMR_ERROR_INVALIDOPCPARTURI); + + m_sURI = sURI; + m_pExportStream = pExportStream; + } + + + COpcPackagePart::COpcPackagePart(_In_ std::string sURI, _In_ PImportStream pImportStream) + { + if (pImportStream.get() == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + if (sURI.length() == 0) + throw CNMRException(NMR_ERROR_INVALIDOPCPARTURI); + + m_sURI = sURI; + m_pImportStream = pImportStream; + } + + COpcPackagePart::COpcPackagePart(COpcPackagePart const & cp, PExportStream pExportStream) { + if (pExportStream.get() == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + m_sURI = cp.m_sURI; + m_Relationships = cp.m_Relationships; + m_pExportStream = pExportStream; + } + + COpcPackagePart::COpcPackagePart(COpcPackagePart const & cp, PImportStream pImportStream) { + if (pImportStream.get() == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + m_sURI = cp.m_sURI; + m_Relationships = cp.m_Relationships; + m_pImportStream = pImportStream; + } + + + std::string COpcPackagePart::getURI() + { + return m_sURI; + } + + PExportStream COpcPackagePart::getExportStream() + { + if (m_pExportStream.get() == nullptr) + throw CNMRException(NMR_ERROR_INVALIDSTREAMTYPE); + return m_pExportStream; + } + + PImportStream COpcPackagePart::getImportStream() + { + if (m_pImportStream.get() == nullptr) + throw CNMRException(NMR_ERROR_INVALIDSTREAMTYPE); + return m_pImportStream; + } + + POpcPackageRelationship COpcPackagePart::addRelationship(_In_ std::string sID, _In_ std::string sType, _In_ std::string sURI) + { + POpcPackageRelationship pRelationship = std::make_shared(sID, sType, sURI); + auto range = m_Relationships.equal_range(sURI); + for (auto foundRelationShip = range.first; foundRelationShip != range.second; foundRelationShip++) { + if (foundRelationShip->second->getType() == sType) { + throw CNMRException(NMR_ERROR_DUPLICATE_RELATIONSHIP); + } + } + + // for (auto iRelationShip : m_Relationships) { + // // Include this again for + // //if (iRelationShip->getType() == sType) { + // // throw CNMRException(NMR_ERROR_DUPLICATE_RELATIONSHIP); + // //} + //} + m_Relationships.insert(std::make_pair(sURI, pRelationship)); + return pRelationship; + } + + nfBool COpcPackagePart::hasRelationships() + { + return m_Relationships.size() > 0; + } + + std::multimap& COpcPackagePart::getRelationShips() + { + return m_Relationships; + } + + void COpcPackagePart::writeRelationships(_In_ PExportStream pExportStream) + { + if (pExportStream.get() == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + PXmlWriter_Native pXMLWriter = std::make_shared(pExportStream); + + pXMLWriter->WriteStartDocument(); + pXMLWriter->WriteStartElement(nullptr, OPC_RELS_RELATIONSHIP_CONTAINER, nullptr); + pXMLWriter->WriteAttributeString(nullptr, "xmlns", nullptr, OPCPACKAGE_SCHEMA_RELATIONSHIPS); + + auto iIterator = m_Relationships.begin(); + + while (iIterator != m_Relationships.end()) { + POpcPackageRelationship pRelationShip = iIterator->second; + pRelationShip->writeToXML(pXMLWriter.get()); + iIterator++; + } + + pXMLWriter->WriteFullEndElement(); + pXMLWriter->WriteEndDocument(); + } +} diff --git a/Source/Common/OPC/NMR_OpcPackageReader.cpp b/Source/Common/OPC/NMR_OpcPackageReader.cpp new file mode 100644 index 0000000..d65c49a --- /dev/null +++ b/Source/Common/OPC/NMR_OpcPackageReader.cpp @@ -0,0 +1,359 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_OpcPackageReader.cpp defines an OPC Package reader in a portable way. + +--*/ + +#include "Common/OPC/NMR_OpcPackageReader.h" +#include "Common/OPC/NMR_OpcPackageRelationshipReader.h" +#include "Common/OPC/NMR_OpcPackageContentTypesReader.h" +#include "Common/Platform/NMR_ImportStream_ZIP.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_StringUtils.h" + +#include "Model/Classes/NMR_ModelConstants.h" + +#include + +namespace NMR { + + // custom callbck function for reading from a CImportStream on the fly + zip_int64_t custom_zip_source_callback(void *userData, void *data, zip_uint64_t len, zip_source_cmd_t cmd) { + if (userData == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + CImportStream* pImportStream = (CImportStream*)(userData); + + switch (cmd) { + case ZIP_SOURCE_SUPPORTS: + zip_int64_t bitmap; + bitmap = zip_source_make_command_bitmap(ZIP_SOURCE_OPEN, ZIP_SOURCE_READ, ZIP_SOURCE_CLOSE, + ZIP_SOURCE_STAT, ZIP_SOURCE_ERROR, ZIP_SOURCE_FREE, ZIP_SOURCE_SEEK, ZIP_SOURCE_TELL, ZIP_SOURCE_SUPPORTS, -1); + return bitmap; + + case ZIP_SOURCE_SEEK: + zip_source_args_seek argsSeek; + argsSeek = * ((zip_source_args_seek *)data); + if (argsSeek.whence == SEEK_SET) + pImportStream->seekPosition(argsSeek.offset, true); + else if (argsSeek.whence == SEEK_CUR) { + pImportStream->seekPosition(pImportStream->getPosition() + argsSeek.offset, true); + } + else if (argsSeek.whence == SEEK_END) { + if (argsSeek.offset > 0) + throw CNMRException(NMR_ERROR_ZIPCALLBACK); + pImportStream->seekFromEnd(-argsSeek.offset, true); + } + else + throw CNMRException(NMR_ERROR_ZIPCALLBACK); + return 0; + + case ZIP_SOURCE_OPEN: + return 0; + + case ZIP_SOURCE_READ: + return pImportStream->readIntoBuffer((nfByte*)data, len, true); + + case ZIP_SOURCE_CLOSE: + return 0; + + case ZIP_SOURCE_TELL: + return pImportStream->getPosition(); + + case ZIP_SOURCE_STAT: + zip_stat_t* zipStat; + zipStat = (zip_stat_t*)data; + zip_stat_init(zipStat); + zipStat->size = pImportStream->retrieveSize(); + zipStat->valid |= ZIP_STAT_SIZE; + return sizeof(zip_stat_t); + + case ZIP_SOURCE_FREE: + return 0; + + default: + throw CNMRException(NMR_ERROR_ZIPCALLBACK); + } + return -1; + } + + COpcPackageReader::COpcPackageReader(_In_ PImportStream pImportStream, _In_ PModelWarnings pWarnings, _In_ PProgressMonitor pProgressMonitor) + : m_pWarnings(pWarnings), m_pProgressMonitor(pProgressMonitor) + { + if (!pImportStream) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + if (!pProgressMonitor) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + m_ZIPError.str = nullptr; + m_ZIPError.sys_err = 0; + m_ZIPError.zip_err = 0; + m_ZIParchive = nullptr; + zip_source_t* pZIPsource = nullptr; + + try { + // determine stream size + nfUint64 nStreamSize = pImportStream->retrieveSize(); + pImportStream->seekPosition(0, true); + + if (nStreamSize == 0) + throw CNMRException(NMR_ERROR_COULDNOTGETSTREAMPOSITION); + + // create ZIP objects + zip_error_init(&m_ZIPError); + + bool bUseCallback = true; + if (bUseCallback) { + // read ZIP from callback: faster and requires less memory + pZIPsource = zip_source_function_create(custom_zip_source_callback, pImportStream.get(), &m_ZIPError); + } + else { + // read ZIP into memory + m_Buffer.resize((size_t)nStreamSize); + pImportStream->readIntoBuffer(&m_Buffer[0], nStreamSize, true); + pZIPsource = zip_source_buffer_create(&m_Buffer[0], (size_t)nStreamSize, 0, &m_ZIPError); + } + if (pZIPsource == nullptr) + throw CNMRException(NMR_ERROR_COULDNOTREADZIPFILE); + + m_ZIParchive = zip_open_from_source(pZIPsource, ZIP_RDONLY | ZIP_CHECKCONS, &m_ZIPError); + if (m_ZIParchive == nullptr) { + m_ZIParchive = zip_open_from_source(pZIPsource, ZIP_RDONLY, &m_ZIPError); + if (m_ZIParchive == nullptr) + throw CNMRException(NMR_ERROR_COULDNOTREADZIPFILE); + else + m_pWarnings->addException(CNMRException(NMR_ERROR_ZIPCONTAINSINCONSISTENCIES), mrwInvalidMandatoryValue); + } + + // Get ZIP Content + nfInt64 nEntryCount = zip_get_num_entries(m_ZIParchive, ZIP_FL_UNCHANGED); + if (nEntryCount < 0) + throw CNMRException(NMR_ERROR_COULDNOTREADZIPFILE); + + // List and stat Entries + nfUint64 nUnzippedFileSize = 0; + for (nfInt64 nIndex = 0; nIndex < nEntryCount; nIndex++) { + const char * pszName = zip_get_name(m_ZIParchive, (nfUint64) nIndex, ZIP_FL_ENC_GUESS); + m_ZIPEntries.insert(std::make_pair(pszName, nIndex)); + + zip_stat_t Stat; + nfInt32 nResult = zip_stat_index(m_ZIParchive, nIndex, ZIP_FL_UNCHANGED, &Stat); + if (nResult != 0) + throw CNMRException(NMR_ERROR_COULDNOTSTATZIPENTRY); + + nUnzippedFileSize += Stat.size; + } + + m_pProgressMonitor->SetMaxProgress(double(nUnzippedFileSize)); + m_pProgressMonitor->ReportProgressAndQueryCancelled(true); + + readContentTypes(); + readRootRelationships(); + } + catch (...) + { + releaseZIP(); + throw; + } + } + + COpcPackageReader::~COpcPackageReader() + { + releaseZIP(); + } + + _Ret_maybenull_ COpcPackageRelationship * COpcPackageReader::findRootRelation(_In_ std::string sRelationType, _In_ nfBool bMustBeUnique) + { + COpcPackageRelationship * pResultRelationship = nullptr; + auto iIterator = m_RootRelationships.begin(); + while (iIterator != m_RootRelationships.end()) { + POpcPackageRelationship pRelationship = *iIterator; + + std::string sType = pRelationship->getType(); + if (sType == sRelationType) { + if (pResultRelationship == nullptr) { + pResultRelationship = pRelationship.get(); + } + else { + if (bMustBeUnique) + m_pWarnings->addException(CNMRException(NMR_ERROR_OPCRELATIONSHIPNOTUNIQUE), eModelWarningLevel::mrwInvalidOptionalValue); + } + + } + iIterator++; + } + + return pResultRelationship; + } + + void COpcPackageReader::releaseZIP() + { + if (m_ZIParchive != nullptr) + zip_close(m_ZIParchive); + + zip_error_fini(&m_ZIPError); + m_Buffer.resize(0); + + m_ZIParchive = nullptr; + } + + PImportStream COpcPackageReader::openZIPEntry(_In_ std::string sName) + { + auto iIterator = m_ZIPEntries.find(sName); + if (iIterator == m_ZIPEntries.end()) { + return nullptr; + } + + return openZIPEntryIndexed(iIterator->second); + } + + PImportStream COpcPackageReader::openZIPEntryIndexed(_In_ nfUint64 nIndex) + { + zip_stat_t Stat; + nfInt32 nResult = zip_stat_index(m_ZIParchive, nIndex, ZIP_FL_UNCHANGED, &Stat); + if (nResult != 0) + throw CNMRException(NMR_ERROR_COULDNOTSTATZIPENTRY); + + nfUint64 nSize = Stat.size; + + zip_file_t * pFile = zip_fopen_index(m_ZIParchive, nIndex, ZIP_FL_UNCHANGED); + if (pFile == nullptr) + throw CNMRException(NMR_ERROR_COULDNOTOPENZIPENTRY); + + return std::make_shared(pFile, nSize); + } + + + void COpcPackageReader::readContentTypes() + { + PImportStream pContentStream = openZIPEntry(OPCPACKAGE_PATH_CONTENTTYPES); + + POpcPackageContentTypesReader pReader = std::make_shared(pContentStream, m_pProgressMonitor); + + nfUint32 nCount = pReader->getCount(); + nfUint32 nIndex; + + std::string modelExtension = ""; + std::string modelPart = ""; + m_relationShipExtension = ""; + for (nIndex = 0; nIndex < nCount; nIndex++) { + POpcPackageContentType pContentType = pReader->getContentType(nIndex); + if (pContentType->m_contentType == PACKAGE_3D_RELS_CONTENT_TYPE) { + m_relationShipExtension = pContentType->m_extension; + } + if (pContentType->m_contentType == PACKAGE_3D_MODEL_CONTENT_TYPE) { + modelExtension = pContentType->m_extension; + } + } + if (m_relationShipExtension.empty()) + throw CNMRException(NMR_ERROR_OPC_MISSING_EXTENSION_FOR_RELATIONSHIP); + + nCount = pReader->getOverrideCount(); + for (nIndex = 0; nIndex < nCount; nIndex++) { + POpcPackageContentType_Override pOverrideContentType = pReader->getOverrideContentType(nIndex); + if (pOverrideContentType->m_contentType == PACKAGE_3D_MODEL_CONTENT_TYPE) { + modelPart = pOverrideContentType->m_partName; + } + } + + if (modelExtension.empty() && modelPart.empty()) + throw CNMRException(NMR_ERROR_OPC_MISSING_EXTENSION_FOR_MODEL); + } + + void COpcPackageReader::readRootRelationships() + { + PImportStream pRelStream = openZIPEntry(OPCPACKAGE_PATH_ROOTRELATIONSHIPS); + + POpcPackageRelationshipReader pReader = std::make_shared(pRelStream, m_pProgressMonitor); + + nfUint32 nCount = pReader->getCount(); + nfUint32 nIndex; + + for (nIndex = 0; nIndex < nCount; nIndex++) { + m_RootRelationships.push_back(pReader->getRelationShip(nIndex)); + } + } + + nfUint64 COpcPackageReader::getPartSize(_In_ std::string sPath) + { + std::string sRealPath = fnRemoveLeadingPathDelimiter(sPath); + auto iIterator = m_ZIPEntries.find(sRealPath); + if (iIterator == m_ZIPEntries.end()) { + return 0; + } + + zip_stat_t Stat; + nfInt32 nResult = zip_stat_index(m_ZIParchive, iIterator->second, ZIP_FL_UNCHANGED, &Stat); + if (nResult != 0) + throw CNMRException(NMR_ERROR_COULDNOTSTATZIPENTRY); + + return Stat.size; + } + + POpcPackagePart COpcPackageReader::createPart(_In_ std::string sPath) + { + std::string sRealPath = fnRemoveLeadingPathDelimiter (sPath); + auto iPartIterator = m_Parts.find(sRealPath); + if (iPartIterator != m_Parts.end()) { + return iPartIterator->second; + } + + PImportStream pStream = openZIPEntry(sRealPath); + if (pStream.get() == nullptr) + throw CNMRException(NMR_ERROR_COULDNOTCREATEOPCPART); + + POpcPackagePart pPart = std::make_shared(sRealPath, pStream); + m_Parts.insert(std::make_pair(sRealPath, pPart)); + + std::string sRelationShipName = fnExtractFileName(sRealPath); + std::string sRelationShipPath = sRealPath.substr(0, sRealPath.length() - sRelationShipName.length()); + sRelationShipPath += "_rels/"; + sRelationShipPath += sRelationShipName; + sRelationShipPath += "."+m_relationShipExtension; + + PImportStream pRelStream = openZIPEntry(sRelationShipPath); + + if (pRelStream.get() != nullptr) { + POpcPackageRelationshipReader pReader = std::make_shared(pRelStream, m_pProgressMonitor); + + nfUint32 nCount = pReader->getCount(); + nfUint32 nIndex; + + for (nIndex = 0; nIndex < nCount; nIndex++) { + POpcPackageRelationship pRelationShip = pReader->getRelationShip(nIndex); + pPart->addRelationship(pRelationShip->getID(), pRelationShip->getType(), pRelationShip->getTargetPartURI()); + } + } + + return pPart; + } + + +} diff --git a/Source/Common/OPC/NMR_OpcPackageRelationship.cpp b/Source/Common/OPC/NMR_OpcPackageRelationship.cpp new file mode 100644 index 0000000..283ab12 --- /dev/null +++ b/Source/Common/OPC/NMR_OpcPackageRelationship.cpp @@ -0,0 +1,86 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_OpcPackageRelationship.cpp implements an OPC Package Relationship Object. + +--*/ + +#include "Common/OPC/NMR_OpcPackageRelationship.h" +#include "Common/OPC/NMR_OpcPackageTypes.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_StringUtils.h" + +namespace NMR { + + COpcPackageRelationship::COpcPackageRelationship(_In_ std::string sID, _In_ std::string sType, _In_ std::string sTargetPartURI) + { + m_sID = sID; + m_sType = sType; + if ( sTargetPartURI.empty()) { // || (sTargetPartURI[0] != L'/') + // must not be emtpy + throw CNMRException(NMR_ERROR_INVALIDOPCPARTURI); + } + std::string sName = fnExtractFileName(sTargetPartURI); + if ( sName.empty() || (sName[0] == '.') ) { + // must not be emtpy or start with a '.' + throw CNMRException(NMR_ERROR_INVALIDOPCPARTURI); + } + m_sTargetPartURI = sTargetPartURI; + } + + std::string COpcPackageRelationship::getID() + { + return m_sID; + } + + std::string COpcPackageRelationship::getType() + { + return m_sType; + } + + std::string COpcPackageRelationship::getTargetPartURI() + { + return m_sTargetPartURI; + } + + void COpcPackageRelationship::writeToXML(_In_ CXmlWriter * pXMLWriter) + { + if (pXMLWriter == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + std::string sTarget = fnIncludeLeadingPathDelimiter(m_sTargetPartURI); + + pXMLWriter->WriteStartElement(nullptr, OPC_RELS_RELATIONSHIP_NODE, nullptr); + pXMLWriter->WriteAttributeString(nullptr, OPC_RELS_ATTRIB_TYPE, nullptr, m_sType.c_str()); + pXMLWriter->WriteAttributeString(nullptr, OPC_RELS_ATTRIB_TARGET, nullptr, sTarget.c_str()); + pXMLWriter->WriteAttributeString(nullptr, OPC_RELS_ATTRIB_ID, nullptr, m_sID.c_str()); + pXMLWriter->WriteEndElement(); + } + + +} diff --git a/Source/Common/OPC/NMR_OpcPackageRelationshipReader.cpp b/Source/Common/OPC/NMR_OpcPackageRelationshipReader.cpp new file mode 100644 index 0000000..eac4a41 --- /dev/null +++ b/Source/Common/OPC/NMR_OpcPackageRelationshipReader.cpp @@ -0,0 +1,266 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_OpcPackageReader.cpp defines an OPC Package reader of .rels files in a portable way. + +--*/ + +#include "Common/OPC/NMR_OpcPackageRelationshipReader.h" +#include "Common/OPC/NMR_OpcPackageTypes.h" +#include "Common/Platform/NMR_Platform.h" +#include "Common/Platform/NMR_WinTypes.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_StringUtils.h" + +#include "Model/Classes/NMR_ModelConstants.h" + +namespace NMR { + + COpcPackageRelationshipReader::COpcPackageRelationshipReader(_In_ PImportStream pImportStream, _In_ PProgressMonitor pProgressMonitor) + { + if (pImportStream.get() == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + if (pProgressMonitor) { + pProgressMonitor->ReportProgressAndQueryCancelled(true); + } + PXmlReader pXMLReader = fnCreateXMLReaderInstance(pImportStream, pProgressMonitor); + + eXmlReaderNodeType NodeType; + // Read all XML Root Nodes + while (!pXMLReader->IsEOF()) { + if (!pXMLReader->Read(NodeType)) + break; + + // Get Node Name + LPCSTR pszLocalName = nullptr; + pXMLReader->GetLocalName(&pszLocalName, nullptr); + if (!pszLocalName) + throw CNMRException(NMR_ERROR_COULDNOTGETLOCALXMLNAME); + + // Compare with Model Node Name + if (strcmp(pszLocalName, OPC_RELS_RELATIONSHIP_CONTAINER) == 0) { + parseRootNode(pXMLReader.get()); + } + } + } + + + COpcPackageRelationshipReader::~COpcPackageRelationshipReader() + { + + } + + void COpcPackageRelationshipReader::parseRootNode(_In_ CXmlReader * pXMLReader) + { + if (pXMLReader == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + parseAttributes(pXMLReader); + + while (!pXMLReader->IsEOF()) { + LPCSTR pszLocalName = nullptr; + LPCSTR pszNameSpaceURI = nullptr; + UINT nCount = 0; + UINT nNameSpaceCount = 0; + + eXmlReaderNodeType NodeType; + pXMLReader->Read(NodeType); + + switch (NodeType) { + case XMLREADERNODETYPE_STARTELEMENT: + pXMLReader->GetLocalName(&pszLocalName, &nCount); + if (!pszLocalName) + throw CNMRException(NMR_ERROR_COULDNOTGETLOCALXMLNAME); + + pXMLReader->GetNamespaceURI(&pszNameSpaceURI, &nNameSpaceCount); + if (!pszNameSpaceURI) + throw CNMRException(NMR_ERROR_COULDNOTGETNAMESPACE); + + if (nCount > 0) { + if (strcmp(pszNameSpaceURI, OPCPACKAGE_SCHEMA_RELATIONSHIPS) == 0) { + if (strcmp(pszLocalName, OPC_RELS_RELATIONSHIP_NODE) == 0) { + parseChildNode(pXMLReader); + } + else + throw CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT); + } + } + break; + + case XMLREADERNODETYPE_ENDELEMENT: + pXMLReader->GetLocalName(&pszLocalName, &nCount); + if (!pszLocalName) + throw CNMRException(NMR_ERROR_COULDNOTGETLOCALXMLNAME); + + if (strcmp(pszLocalName, OPC_RELS_RELATIONSHIP_CONTAINER) == 0) { + return; + } + pXMLReader->CloseElement(); + break; + + case XMLREADERNODETYPE_UNKNOWN: + break; + + case XMLREADERNODETYPE_TEXT: + break; + } + } + } + + + void COpcPackageRelationshipReader::parseChildNode(_In_ CXmlReader * pXMLReader) + { + if (pXMLReader == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + if (!pXMLReader->MoveToFirstAttribute()) + return; + + std::string sTarget; + std::string sID; + std::string sType; + + nfBool bContinue = true; + while (bContinue) { + + if (!pXMLReader->IsDefault()) { + LPCSTR pszLocalName = nullptr; + LPCSTR pszNameSpaceURI = nullptr; + LPCSTR pszValue = nullptr; + UINT nNameCount = 0; + UINT nValueCount = 0; + UINT nNameSpaceCount = 0; + + // Get Attribute Name + pXMLReader->GetNamespaceURI(&pszNameSpaceURI, &nNameSpaceCount); + if (!pszNameSpaceURI) + throw CNMRException(NMR_ERROR_COULDNOTGETNAMESPACE); + + pXMLReader->GetLocalName(&pszLocalName, &nNameCount); + if (!pszLocalName) + throw CNMRException(NMR_ERROR_COULDNOTGETLOCALXMLNAME); + + // Get Attribute Value + pXMLReader->GetValue(&pszValue, &nValueCount); + if (!pszValue) + throw CNMRException(NMR_ERROR_COULDNOTGETXMLVALUE); + + if (nNameSpaceCount == 0) { + if (strcmp(pszLocalName, OPC_RELS_ATTRIB_TARGET) == 0) + sTarget = pszValue; + if (strcmp(pszLocalName, OPC_RELS_ATTRIB_TYPE) == 0) + sType = pszValue; + if (strcmp(pszLocalName, OPC_RELS_ATTRIB_ID) == 0) + sID = pszValue; + } + + } + + bContinue = pXMLReader->MoveToNextAttribute(); + } + + // must be non-empty and absolute getPath + if (sTarget.empty()) // || (sTarget[0] != L'/') ) + throw CNMRException(NMR_ERROR_INVALIDOPCPARTURI); + + if (sType == PACKAGE_PRINT_TICKET_RELATIONSHIP_TYPE) { + for (auto itRel : m_IDToRelationShips) { + if (itRel.second->getType() == sType) { + throw CNMRException(NMR_ERROR_DUPLICATE_PRINTTICKET); + } + } + } + + auto found = m_IDToRelationShips.find(sID); + if (found != m_IDToRelationShips.end()) { + throw CNMRException(NMR_ERROR_OPC_DUPLICATE_RELATIONSHIP_ID); + } + POpcPackageRelationship pRelationShip = std::make_shared (sID, sType, sTarget); + m_IDToRelationShips.insert(std::make_pair(sID, pRelationShip)); + + pXMLReader->CloseElement(); + } + + nfUint32 COpcPackageRelationshipReader::getCount() + { + return (nfUint32)m_IDToRelationShips.size(); + } + + POpcPackageRelationship COpcPackageRelationshipReader::getRelationShip(_In_ nfUint32 nIndex) + { + nfUint32 nCount = (nfUint32)m_IDToRelationShips.size(); + if (nIndex >= nCount) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + + auto it = m_IDToRelationShips.begin(); + std::advance(it, nIndex); + return it->second; + } + + void COpcPackageRelationshipReader::parseAttributes(_In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pXMLReader); + + if (!pXMLReader->MoveToFirstAttribute()) + return; + + nfBool bContinue = true; + while (bContinue) { + + if (!pXMLReader->IsDefault()) { + LPCSTR pszLocalName = nullptr; + LPCSTR pszNameSpaceURI = nullptr; + LPCSTR pszValue = nullptr; + UINT nNameCount = 0; + UINT nValueCount = 0; + UINT nNameSpaceCount = 0; + + // Get Attribute Name + pXMLReader->GetNamespaceURI(&pszNameSpaceURI, &nNameSpaceCount); + if (!pszNameSpaceURI) + throw CNMRException(NMR_ERROR_COULDNOTGETNAMESPACE); + + pXMLReader->GetLocalName(&pszLocalName, &nNameCount); + if (!pszLocalName) + throw CNMRException(NMR_ERROR_COULDNOTGETLOCALXMLNAME); + + // Get Attribute Value + pXMLReader->GetValue(&pszValue, &nValueCount); + if (!pszValue) + throw CNMRException(NMR_ERROR_COULDNOTGETXMLVALUE); + } + + bContinue = pXMLReader->MoveToNextAttribute(); + } + } + + +} + + diff --git a/Source/Common/OPC/NMR_OpcPackageWriter.cpp b/Source/Common/OPC/NMR_OpcPackageWriter.cpp new file mode 100644 index 0000000..c0112f9 --- /dev/null +++ b/Source/Common/OPC/NMR_OpcPackageWriter.cpp @@ -0,0 +1,219 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_OpcPackageWriter.cpp defines an OPC Package writer in a portable way. + +--*/ + +#include "Common/OPC/NMR_OpcPackageWriter.h" +#include "Common/Platform/NMR_Time.h" +#include "Common/Platform/NMR_XmlWriter_Native.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_StringUtils.h" + +#include "Model/Classes/NMR_ModelConstants.h" + +#include + +namespace NMR { + + + COpcPackageWriter::COpcPackageWriter(_In_ PExportStream pExportStream) + { + if (pExportStream.get() == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + m_pExportStream = pExportStream; + m_pZIPWriter = std::make_shared(m_pExportStream, true); + + m_nRelationIDCounter = 0; + } + + COpcPackageWriter::~COpcPackageWriter() + { + finishPackage(); + } + + POpcPackagePart COpcPackageWriter::addPart(_In_ std::string sPath) + { + sPath = fnRemoveLeadingPathDelimiter(sPath); + + PExportStream pStream = m_pZIPWriter->createEntry(sPath, fnGetUnixTime()); + POpcPackagePart pPart = std::make_shared(sPath, pStream); + m_Parts.push_back(pPart); + + return pPart; + } + + void COpcPackageWriter::addContentType(_In_ std::string sExtension, _In_ std::string sContentType) + { + m_DefaultContentTypes.insert(std::make_pair(sExtension, sContentType)); + } + + void COpcPackageWriter::addContentType(POpcPackagePart pOpcPackagePart, std::string sContentType) + { + // Follows section 10.1.2.3 of "Ecma Office Open XML Part 2 - Open Packaging Conventions" + nfBool isOverride = false; + + // Step 1 - Get extension + std::size_t extensionPosition = pOpcPackagePart->getURI().find_last_of('.'); + if (std::string::npos == extensionPosition) // Step 2 - No extension available, use Override Content Type + isOverride = true; + else { + // Step 3 - Compare extensions with Default Content Types + std::string extension = pOpcPackagePart->getURI().substr(extensionPosition + 1); + std::map::iterator defaultSameExtension = m_DefaultContentTypes.find(extension); + if (m_DefaultContentTypes.end() != defaultSameExtension) { + // Step 4 - An extension assigned to a Default Content Type matches + if (defaultSameExtension->second.compare(sContentType) == 0) { + // Step 4.a - Content Types match, nothing else to do + isOverride = false; + addContentType(extension, sContentType); + } + else // Step 4.b - Content Types do not match, use Override Content Type + isOverride = true; + } + else // Step 5 - No Default Content Type that matches, use Override Content Type + isOverride = true; + } + + if (isOverride) + m_OverrideContentTypes.insert(std::make_pair(pOpcPackagePart->getURI(), sContentType)); + } + + POpcPackageRelationship COpcPackageWriter::addRootRelationship(_In_ std::string sType, _In_ COpcPackagePart * pTargetPart) + { + if (pTargetPart == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + POpcPackageRelationship pRelationship = std::make_shared(generateRelationShipID(), sType, pTargetPart->getURI()); + m_RootRelationships.push_back(pRelationship); + return pRelationship; + } + + POpcPackageRelationship COpcPackageWriter::addPartRelationship(POpcPackagePart pOpcPackagePart, std::string sType, COpcPackagePart * pTargetPart) + { + return pOpcPackagePart->addRelationship(generateRelationShipID(), sType, pTargetPart->getURI()); + } + + std::list COpcPackageWriter::addWriterSpecificRelationships(_In_ POpcPackagePart pOpcPackagePart, _In_ COpcPackagePart* pTargetPart) + { + return std::list(); + } + + void COpcPackageWriter::finishPackage() + { + writeContentTypes(); + writeRootRelationships(); + auto iIterator = m_Parts.begin(); + while (iIterator != m_Parts.end()) { + POpcPackagePart pPart = *iIterator; + if (pPart->hasRelationships()) { + std::string sURI = pPart->getURI(); + std::string sName = fnExtractFileName(sURI); + std::string sPath = sURI.substr(0, sURI.length() - sName.length()); + sPath += "_rels/"; + sPath += sName; + sPath += std::string(".")+PACKAGE_3D_RELS_EXTENSION; + + PExportStream pStream = m_pZIPWriter->createEntry(sPath, fnGetUnixTime()); + pPart->writeRelationships(pStream); + } + iIterator++; + } + + } + + void COpcPackageWriter::writeContentTypes() + { + PExportStream pStream = m_pZIPWriter->createEntry(OPCPACKAGE_PATH_CONTENTTYPES, fnGetUnixTime()); + PXmlWriter_Native pXMLWriter = std::make_shared(pStream); + + pXMLWriter->WriteStartDocument(); + pXMLWriter->WriteStartElement(nullptr, OPC_CONTENTTYPES_CONTAINER, nullptr); + pXMLWriter->WriteAttributeString(nullptr, "xmlns", nullptr, OPCPACKAGE_SCHEMA_CONTENTTYPES); + + auto iDefaultIterator = m_DefaultContentTypes.begin(); + while (iDefaultIterator != m_DefaultContentTypes.end()) { + pXMLWriter->WriteStartElement(nullptr, OPC_CONTENTTYPES_NODE, nullptr); + pXMLWriter->WriteAttributeString(nullptr, OPC_CONTENTTYPES_ATTRIB_EXTENSION, nullptr, iDefaultIterator->first.c_str()); + pXMLWriter->WriteAttributeString(nullptr, OPC_CONTENTTYPES_ATTRIB_CONTENTTYPE, nullptr, iDefaultIterator->second.c_str()); + pXMLWriter->WriteEndElement(); + + iDefaultIterator++; + } + + auto iOverrideIterator = m_OverrideContentTypes.begin(); + while (iOverrideIterator != m_OverrideContentTypes.end()) { + pXMLWriter->WriteStartElement(nullptr, OPC_CONTENTTYPES_NODE_OVERRIDE, nullptr); + pXMLWriter->WriteAttributeString(nullptr, OPC_CONTENTTYPES_ATTRIB_PARTNAME, nullptr, iOverrideIterator->first.c_str()); + pXMLWriter->WriteAttributeString(nullptr, OPC_CONTENTTYPES_ATTRIB_CONTENTTYPE, nullptr, iOverrideIterator->second.c_str()); + pXMLWriter->WriteEndElement(); + + iOverrideIterator++; + } + + pXMLWriter->WriteFullEndElement(); + pXMLWriter->WriteEndDocument(); + + } + + void COpcPackageWriter::writeRootRelationships() + { + if (m_RootRelationships.size() == 0) + return; + + PExportStream pStream = m_pZIPWriter->createEntry(OPCPACKAGE_PATH_ROOTRELATIONSHIPS, fnGetUnixTime()); + PXmlWriter_Native pXMLWriter = std::make_shared(pStream); + + pXMLWriter->WriteStartDocument(); + pXMLWriter->WriteStartElement(nullptr, "Relationships", nullptr); + pXMLWriter->WriteAttributeString(nullptr, "xmlns", nullptr, OPCPACKAGE_SCHEMA_RELATIONSHIPS); + + auto iIterator = m_RootRelationships.begin(); + + while (iIterator != m_RootRelationships.end()) { + POpcPackageRelationship pRelationShip = *iIterator; + pRelationShip->writeToXML(pXMLWriter.get()); + iIterator++; + } + + pXMLWriter->WriteFullEndElement(); + pXMLWriter->WriteEndDocument(); + + } + + std::string COpcPackageWriter::generateRelationShipID() + { + // Create Unique ID String + std::stringstream sStream; + sStream << "rel" << m_nRelationIDCounter; + m_nRelationIDCounter++; + return sStream.str(); + } +} diff --git a/Source/Common/Platform/NMR_EncryptionHeader.cpp b/Source/Common/Platform/NMR_EncryptionHeader.cpp new file mode 100644 index 0000000..add3566 --- /dev/null +++ b/Source/Common/Platform/NMR_EncryptionHeader.cpp @@ -0,0 +1,58 @@ + + +#include "Common/Platform/NMR_EncryptionHeader.h" +#include "Common/NMR_ErrorConst.h" +#include "Common/NMR_Exception.h" + +#include "Common/Platform/NMR_ImportStream.h" +#include "Common/Platform/NMR_ExportStream.h" + +#include "Common/NMR_Architecture_Utils.h" +#include +namespace NMR { + + CEncryptionHeader::CEncryptionHeader(std::vector const & additionalData) + :m_rgAdditionalData(additionalData) + { + } + + size_t CEncryptionHeader::readFrom(PImportStream from) { + uEncryptedFileHeader header = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; + from->readIntoBuffer(header.bytes, sizeof(header), true); + if (isBigEndian()) { + header.Header.Length.length = swapBytes(header.Header.Length.length); + } + size_t sigSize = sizeof(header.Header.Signature.bytes); + if (strncmp((char *)header.Header.Signature.bytes, "%3McF", sigSize) != 0) + throw CNMRException(NMR_ERROR_COULDNOTREADENCRYPTEDSTREAM); + if (header.Header.majorVersion != 0 || header.Header.minorVersion != 0) + throw CNMRException(NMR_ERROR_ENCRYPTEDCONTENTVERSIONUNSUPPORTED); + size_t headerSize = sizeof(header); + nfUint32 remainingBytes = header.Header.Length.length - headerSize; + if (remainingBytes > 0) { + m_rgAdditionalData.resize(remainingBytes, 0); + from->readIntoBuffer(m_rgAdditionalData.data(), remainingBytes, true); + } + m_nfHeaderSize = header.Header.Length.length; + return m_nfHeaderSize; + } + size_t CEncryptionHeader::writeTo(PExportStream to) { + uEncryptedFileHeader header = { { '%', '3', 'M', 'c', 'F', 0, 0, 0, 0, 0, 0, 0 } }; + size_t headerSize = sizeof(header); + m_nfHeaderSize = (nfUint32)(headerSize + m_rgAdditionalData.size()); + header.Header.Length.length = (nfUint32)m_nfHeaderSize; + if (isBigEndian()) { + header.Header.Length.length = swapBytes(header.Header.Length.length); + } + to->writeBuffer(header.bytes, headerSize); + if (m_rgAdditionalData.size() > 0) + to->writeBuffer(m_rgAdditionalData.data(), m_rgAdditionalData.size()); + return m_nfHeaderSize; + } + std::vector const & CEncryptionHeader::additionalData() const { + return m_rgAdditionalData; + } + nfUint64 CEncryptionHeader::headerSize() const { + return m_nfHeaderSize; + } +} \ No newline at end of file diff --git a/Source/Common/Platform/NMR_ExportStream.cpp b/Source/Common/Platform/NMR_ExportStream.cpp new file mode 100644 index 0000000..0bbf956 --- /dev/null +++ b/Source/Common/Platform/NMR_ExportStream.cpp @@ -0,0 +1,77 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ExportStream.h implements the ExportStream Class. +This is an abstract base stream class for exporting from various data sources. + + +--*/ + +#include "Common/Platform/NMR_ExportStream.h" +#include "Common/NMR_Exception.h" +#include + +namespace NMR { + + void CExportStream::close() + { + // do nothing + } + + void CExportStream::copyFrom(_In_ CImportStream * pImportStream, _In_ nfUint64 cbCount, _In_ nfUint32 cbBufferSize) + { + if (pImportStream == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + if (cbBufferSize == 0) + throw CNMRException(NMR_ERROR_INVALIDBUFFERSIZE); + + if (cbCount == 0) + return; + + std::vector Buffer; + Buffer.resize(cbBufferSize); + + nfUint32 cbBytesToCopy; + while (cbCount > 0) { + + if (cbCount > cbBufferSize) + cbBytesToCopy = cbBufferSize; + else + cbBytesToCopy = (nfUint32)cbCount; + + pImportStream->readIntoBuffer(&Buffer[0], cbBytesToCopy, true); + writeBuffer(&Buffer[0], cbBytesToCopy); + + cbCount -= cbBytesToCopy; + } + + close(); + } + + +} diff --git a/Source/Common/Platform/NMR_ExportStream_Callback.cpp b/Source/Common/Platform/NMR_ExportStream_Callback.cpp new file mode 100644 index 0000000..57d7cbc --- /dev/null +++ b/Source/Common/Platform/NMR_ExportStream_Callback.cpp @@ -0,0 +1,157 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ExportStream_Callback.cpp implements the CExportStream_Callback Class. +This is a stream class for exporting via a callback to custom data writer. + +--*/ + +#include "Common/Platform/NMR_ExportStream_Callback.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_StringUtils.h" + +#include + +namespace NMR { + + CExportStream_Callback::CExportStream_Callback() + :CExportStream () + { + // empty on purpose + m_pWriteCallback = nullptr; + m_pUserData = nullptr; + m_pSeekCallback = nullptr; + m_nPosition = 0; + m_nSize = 0; + } + + CExportStream_Callback::CExportStream_Callback(_In_ ExportStream_WriteCallbackType pWriteCallback, _In_ ExportStream_SeekCallbackType pSeekCallback, void * pUserData) + : CExportStream() + { + m_pWriteCallback = pWriteCallback; + m_pSeekCallback = pSeekCallback; + m_pUserData = pUserData; + m_nPosition = 0; + m_nSize = 0; + } + + nfBool CExportStream_Callback::seekPosition(_In_ nfUint64 position, _In_ nfBool bHasToSucceed) + { + if (m_pSeekCallback == nullptr) { + if (bHasToSucceed) + throw CNMRException(NMR_ERROR_CALLBACKSTREAMCANNOTSEEK); + return false; + } + else { + if (position > m_nSize) + throw CNMRException(NMR_ERROR_COULDNOTSEEKSTREAM); + + nfUint64 nNewPosition = position; + nfUint32 nErrorCode = m_pSeekCallback(nNewPosition, m_pUserData); + if (nErrorCode != 0) + throw CNMRException(NMR_ERROR_COULDNOTSEEKSTREAM); + m_nPosition = nNewPosition; + return true; + } + } + + nfBool CExportStream_Callback::seekForward(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed) + { + if (m_pSeekCallback == nullptr) { + if (bHasToSucceed) + throw CNMRException(NMR_ERROR_CALLBACKSTREAMCANNOTSEEK); + return false; + } + else { + nfUint64 nNewPosition = m_nPosition + bytes; + if (nNewPosition > m_nSize) + throw CNMRException(NMR_ERROR_COULDNOTSEEKSTREAM); + + nfUint32 nErrorCode = m_pSeekCallback(nNewPosition, m_pUserData); + if (nErrorCode != 0) + throw CNMRException(NMR_ERROR_COULDNOTSEEKSTREAM); + m_nPosition = nNewPosition; + return true; + } + } + + nfBool CExportStream_Callback::seekFromEnd(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed) + { + if (m_pSeekCallback == nullptr) { + if (bHasToSucceed) + throw CNMRException(NMR_ERROR_CALLBACKSTREAMCANNOTSEEK); + return false; + } + else { + if (bytes > m_nSize) + throw CNMRException(NMR_ERROR_COULDNOTSEEKSTREAM); + + nfUint64 nNewPosition = m_nSize - bytes; + nfUint32 nErrorCode = m_pSeekCallback(nNewPosition, m_pUserData); + if (nErrorCode != 0) + throw CNMRException(NMR_ERROR_COULDNOTSEEKSTREAM); + m_nPosition = nNewPosition; + return true; + } + } + + nfUint64 CExportStream_Callback::getPosition() + { + return m_nPosition; + } + + nfUint64 CExportStream_Callback::writeBuffer(_In_ const void * pBuffer, _In_ nfUint64 cbTotalBytesToWrite) + { + if (m_pWriteCallback == nullptr) + throw CNMRException(NMR_ERROR_COULDNOTWRITETOCALLBACKSTREAM); + + nfByte * pByte = (nfByte *)pBuffer; + nfUint64 cbBytesLeft = cbTotalBytesToWrite; + while (cbBytesLeft > 0) { + nfUint64 cbBytes = cbBytesLeft; + if (cbBytes > EXPORTSTREAM_CALLBACK_BUFFERSIZE) + cbBytes = EXPORTSTREAM_CALLBACK_BUFFERSIZE; + + nfUint32 nError = m_pWriteCallback(pByte, (nfUint32) cbBytes, m_pUserData); + if (nError != 0) + throw CNMRException(NMR_ERROR_COULDNOTWRITETOCALLBACKSTREAM); + + pByte += cbBytes; + cbBytesLeft -= cbBytes; + } + + m_nPosition += cbTotalBytesToWrite; + if (m_nPosition > m_nSize) + m_nSize = m_nPosition; + + return cbTotalBytesToWrite; + } + + +} diff --git a/Source/Common/Platform/NMR_ExportStream_Compressed.cpp b/Source/Common/Platform/NMR_ExportStream_Compressed.cpp new file mode 100644 index 0000000..e4b7453 --- /dev/null +++ b/Source/Common/Platform/NMR_ExportStream_Compressed.cpp @@ -0,0 +1,114 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ExportStream_Compressed.h defines a stream to write compressed files + +--*/ + +#include "Common/Platform/NMR_ExportStream_Compressed.h" +#include "Common/NMR_Exception.h" + +namespace NMR { + + CExportStream_Compressed::CExportStream_Compressed(PExportStream pUncompressedStream) + { + if (nullptr == pUncompressedStream) + throw CNMRException(NMR_ERROR_INVALIDPOINTER); + m_pUncompressedStream = pUncompressedStream; + + m_strm.zalloc = Z_NULL; + m_strm.zfree = Z_NULL; + m_strm.opaque = Z_NULL; + if (deflateInit(&m_strm, Z_DEFAULT_COMPRESSION) != Z_OK) + throw CNMRException(NMR_ERROR_COULDNOTINITDEFLATE); + } + + CExportStream_Compressed::~CExportStream_Compressed() + { + (void)deflateEnd(&m_strm); + } + + nfBool CExportStream_Compressed::seekPosition(_In_ nfUint64 position, _In_ nfBool bHasToSucceed) + { + throw CNMRException(NMR_ERROR_NOTIMPLEMENTED); + } + + nfBool CExportStream_Compressed::seekForward(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed) + { + throw CNMRException(NMR_ERROR_NOTIMPLEMENTED); + } + + nfBool CExportStream_Compressed::seekFromEnd(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed) + { + throw CNMRException(NMR_ERROR_NOTIMPLEMENTED); + } + + nfUint64 CExportStream_Compressed::getPosition() + { + throw CNMRException(NMR_ERROR_NOTIMPLEMENTED); + } + + nfInt32 CExportStream_Compressed::compress(nfInt32 flush) { + nfInt32 ret; + do { + m_strm.avail_out = (nfUint32) EXPORTSTREAM_WRITE_BUFFER_CHUNKSIZE; + m_strm.next_out = out; + ret = deflate(&m_strm, flush); + switch (ret) { + case Z_NEED_DICT: + case Z_DATA_ERROR: + case Z_MEM_ERROR: + (void)deflateEnd(&m_strm); + throw CNMRException(NMR_ERROR_COULDNOTDEFLATE); + } + int toWrite = EXPORTSTREAM_WRITE_BUFFER_CHUNKSIZE - m_strm.avail_out; + m_pUncompressedStream->writeBuffer(out, toWrite); + } while (m_strm.avail_out == 0); + return ret; + } + + nfUint64 CExportStream_Compressed::writeBuffer(_In_ const void * pBuffer, _In_ nfUint64 cbTotalBytesToWrite) + { + if (nullptr == pBuffer) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + m_strm.avail_in = (nfUint32) cbTotalBytesToWrite; + m_strm.next_in = (Bytef *) pBuffer; + compress(Z_NO_FLUSH); + + return cbTotalBytesToWrite; + } + + void CExportStream_Compressed::close() + { + if (compress(Z_FINISH) != Z_STREAM_END) { + throw CNMRException(NMR_ERROR_COULDNOTDEFLATE); + } + } + +} diff --git a/Source/Common/Platform/NMR_ExportStream_Dummy.cpp b/Source/Common/Platform/NMR_ExportStream_Dummy.cpp new file mode 100644 index 0000000..f6f968d --- /dev/null +++ b/Source/Common/Platform/NMR_ExportStream_Dummy.cpp @@ -0,0 +1,85 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ExportStream_Dummy.cpp implementa the ExportStream Dummy class. It will not +store any data written to it, but it will correctly track the seek position and +size of the data. It is designed to be used for measuring the size of the stream. + +--*/ + +#include "Common/Platform/NMR_ExportStream_Dummy.h" +#include "Common/NMR_Exception.h" + +namespace NMR { + + CExportStreamDummy::CExportStreamDummy() { + m_Size = 0; + m_Position = 0; + } + + nfBool CExportStreamDummy::seekPosition(_In_ nfUint64 position, _In_ nfBool bHasToSucceed) { + if (position >= m_Size && bHasToSucceed) { + throw CNMRException(NMR_ERROR_COULDNOTSEEKSTREAM); + } + m_Position = position; + return true; + } + + nfBool CExportStreamDummy::seekForward(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed) { + if (bytes + m_Position >= m_Size && bHasToSucceed) { + throw CNMRException(NMR_ERROR_COULDNOTSEEKSTREAM); + } + m_Position = bytes + m_Position; + return true; + } + + nfBool CExportStreamDummy::seekFromEnd(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed) { + if (bytes >= m_Size && bHasToSucceed) { + throw CNMRException(NMR_ERROR_COULDNOTSEEKSTREAM); + } + m_Position = m_Size - bytes; + return true; + } + + nfUint64 CExportStreamDummy::getPosition() { + return m_Position; + } + + nfUint64 CExportStreamDummy::writeBuffer(_In_ const void * pBuffer, _In_ nfUint64 cbTotalBytesToWrite) { + if ((m_Position + cbTotalBytesToWrite) > m_Size) { + m_Size = m_Position + cbTotalBytesToWrite; + } + m_Position += cbTotalBytesToWrite; + return cbTotalBytesToWrite; + } + + nfUint64 CExportStreamDummy::getDataSize() { + return m_Size; + } + +} diff --git a/Source/Common/Platform/NMR_ExportStream_Encrypted.cpp b/Source/Common/Platform/NMR_ExportStream_Encrypted.cpp new file mode 100644 index 0000000..16c28be --- /dev/null +++ b/Source/Common/Platform/NMR_ExportStream_Encrypted.cpp @@ -0,0 +1,53 @@ +#include "Common/Platform/NMR_ExportStream_Encrypted.h" +#include "Common/NMR_Exception.h" + +namespace NMR { + CExportStream_Encrypted::CExportStream_Encrypted(PExportStream pEncryptedStream, ContentEncryptionDescriptor context) + :m_pEncryptedStream(pEncryptedStream), m_pDecryptContext(context) + { + if (nullptr == pEncryptedStream) + throw CNMRException(NMR_ERROR_INVALIDPOINTER); + m_header.writeTo(m_pEncryptedStream); + } + + nfBool CExportStream_Encrypted::seekPosition(nfUint64 position, nfBool bHasToSucceed) + { + return m_pEncryptedStream->seekPosition(position + m_header.headerSize(), bHasToSucceed); + } + + nfBool CExportStream_Encrypted::seekForward(nfUint64 bytes, nfBool bHasToSucceed) + { + return m_pEncryptedStream->seekForward(bytes, bHasToSucceed); + } + + nfBool CExportStream_Encrypted::seekFromEnd(nfUint64 bytes, nfBool bHasToSucceed) + { + if (m_pEncryptedStream->getPosition() + m_header.headerSize() >= bytes) { + return m_pEncryptedStream->seekFromEnd(bytes, bHasToSucceed); + } else if (bHasToSucceed) { + throw CNMRException(NMR_ERROR_COULDNOTSEEKSTREAM); + } + return false; + } + + nfUint64 CExportStream_Encrypted::getPosition() + { + return m_pEncryptedStream->getPosition() - m_header.headerSize(); + } + + nfUint64 CExportStream_Encrypted::writeBuffer(const void * pBuffer, nfUint64 cbTotalBytesToWrite) + { + nfUint64 encryptedBytes = 0; + if (cbTotalBytesToWrite > 0) { + std::vector encryptBuffer(cbTotalBytesToWrite, 0); + encryptedBytes = m_pDecryptContext.m_fnCrypt(cbTotalBytesToWrite, (const nfByte *)pBuffer, encryptBuffer.data(), m_pDecryptContext.m_sDekDecryptData); + if (encryptedBytes > 0) { + auto writtenBytes = m_pEncryptedStream->writeBuffer(encryptBuffer.data(), encryptedBytes); + if (encryptedBytes != writtenBytes) + throw CNMRException(NMR_ERROR_CALCULATIONTERMINATED); + } + } + return encryptedBytes; + } + +} \ No newline at end of file diff --git a/Source/Common/Platform/NMR_ExportStream_Memory.cpp b/Source/Common/Platform/NMR_ExportStream_Memory.cpp new file mode 100644 index 0000000..9de19e0 --- /dev/null +++ b/Source/Common/Platform/NMR_ExportStream_Memory.cpp @@ -0,0 +1,90 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ExportStream_Memory.cpp implements the ExportStream to Memory Class. + +--*/ + +#include "Common/Platform/NMR_ExportStream_Memory.h" +#include "Common/NMR_Exception.h" + +namespace NMR { + + CExportStreamMemory::CExportStreamMemory() { + m_Position = 0; + } + + nfBool CExportStreamMemory::seekPosition(_In_ nfUint64 position, _In_ nfBool bHasToSucceed) { + if (position >= m_Buffer.size() && bHasToSucceed) { + throw CNMRException(NMR_ERROR_COULDNOTSEEKSTREAM); + } + m_Position = position; + return true; + } + + nfBool CExportStreamMemory::seekForward(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed) { + if (bytes + m_Position >= m_Buffer.size() && bHasToSucceed) { + throw CNMRException(NMR_ERROR_COULDNOTSEEKSTREAM); + } + m_Position = bytes + m_Position; + return true; + } + + nfBool CExportStreamMemory::seekFromEnd(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed) { + if (bytes >= m_Buffer.size() && bHasToSucceed) { + throw CNMRException(NMR_ERROR_COULDNOTSEEKSTREAM); + } + m_Position = m_Buffer.size() - bytes; + return true; + } + + nfUint64 CExportStreamMemory::getPosition() { + return m_Position; + } + + nfUint64 CExportStreamMemory::writeBuffer(_In_ const void * pBuffer, _In_ nfUint64 cbTotalBytesToWrite) { + nfByte *pByteBuffer = (nfByte *)pBuffer; + if ((m_Position + cbTotalBytesToWrite) > m_Buffer.size()) { + m_Buffer.resize(static_cast(m_Position + cbTotalBytesToWrite)); + } + for (nfUint64 i = 0; i < cbTotalBytesToWrite; i++) { + m_Buffer[static_cast(m_Position + i)] = pByteBuffer[i]; + } + m_Position += cbTotalBytesToWrite; + return cbTotalBytesToWrite; + } + + nfUint64 CExportStreamMemory::getDataSize() { + return m_Buffer.size(); + } + + const nfByte *CExportStreamMemory::getData() { + return m_Buffer.data(); + } + +} \ No newline at end of file diff --git a/Source/Common/Platform/NMR_ExportStream_Native.cpp b/Source/Common/Platform/NMR_ExportStream_Native.cpp new file mode 100644 index 0000000..84f03b9 --- /dev/null +++ b/Source/Common/Platform/NMR_ExportStream_Native.cpp @@ -0,0 +1,137 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ExportStream_Native.cpp implements the CExportStream_Native Class. +This is an abstract base stream class for exporting with std::streams + +--*/ + +#include "Common/Platform/NMR_ExportStream_Native.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_StringUtils.h" + +#include + +namespace NMR { + + + CExportStream_Native::CExportStream_Native(_In_ const nfWChar * pwszFileName) + { + if (pwszFileName == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + std::wstring sFileName(pwszFileName); +#if defined(_WIN32) && !defined(__MINGW32__) + m_Stream.open(sFileName.c_str(), std::ios::out | std::ios::binary); +#else + std::string sUTF8Name = fnUTF16toUTF8(sFileName); + m_Stream.open(sUTF8Name.c_str(), std::ios::out | std::ios::binary); +#endif + if (m_Stream.fail()) + throw CNMRException(NMR_ERROR_COULDNOTCREATEFILE); + + } + + CExportStream_Native::~CExportStream_Native() + { + if (m_Stream.is_open()) { + m_Stream.close(); + } + } + + + nfBool CExportStream_Native::seekPosition(_In_ nfUint64 position, _In_ nfBool bHasToSucceed) + { + std::streampos nStreamPos = position; + m_Stream.seekp(nStreamPos, std::ios_base::beg); + + if (m_Stream.fail()) { + if (bHasToSucceed) + throw CNMRException(NMR_ERROR_COULDNOTSEEKSTREAM); + + return false; + } + + return true; + } + + nfBool CExportStream_Native::seekForward(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed) + { + std::streampos nStreamOffset = bytes; + m_Stream.seekp(nStreamOffset, std::ios_base::cur); + + if (m_Stream.fail()) { + if (bHasToSucceed) + throw CNMRException(NMR_ERROR_COULDNOTSEEKSTREAM); + + return false; + } + + return true; + } + + nfBool CExportStream_Native::seekFromEnd(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed) + { + std::streampos nStreamOffset = 0-bytes; + m_Stream.seekp(nStreamOffset, std::ios_base::end); + + if (m_Stream.fail()) { + if (bHasToSucceed) + throw CNMRException(NMR_ERROR_COULDNOTSEEKSTREAM); + + return false; + } + + return true; + } + + nfUint64 CExportStream_Native::getPosition() + { + std::streampos nStreamPosition = m_Stream.tellp(); + if (nStreamPosition < 0) + throw CNMRException(NMR_ERROR_COULDNOTGETSTREAMPOSITION); + + return nStreamPosition; + } + + nfUint64 CExportStream_Native::writeBuffer(_In_ const void * pBuffer, _In_ nfUint64 cbTotalBytesToWrite) + { + if (pBuffer == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + const char * pChar = (const char*)pBuffer; + std::streamsize nSize = cbTotalBytesToWrite; + m_Stream.write(pChar, nSize); + if (m_Stream.fail()) + throw CNMRException(NMR_ERROR_COULDNOTWRITESTREAM); + + return nSize; + } + +} diff --git a/Source/Common/Platform/NMR_ExportStream_ZIP.cpp b/Source/Common/Platform/NMR_ExportStream_ZIP.cpp new file mode 100644 index 0000000..3992a1e --- /dev/null +++ b/Source/Common/Platform/NMR_ExportStream_ZIP.cpp @@ -0,0 +1,198 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_PortableZIPWriter.cpp implements a portable stream to write into ZIP files + +--*/ + +#include "Common/Platform/NMR_ExportStream_ZIP.h" +#include "Common/NMR_Exception.h" + +namespace NMR { + + CExportStream_ZIP::CExportStream_ZIP(_In_ CPortableZIPWriter * pZIPWriter, nfUint32 nEntryKey) + { + m_bIsInitialized = false; + + if (pZIPWriter == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + if (nEntryKey == 0) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + m_pZIPWriter = pZIPWriter; + m_nEntryKey = nEntryKey; + + m_pStream.next_in = nullptr; + m_pStream.avail_in = 0; + m_pStream.total_in = 0; + + m_pStream.msg = nullptr; + m_pStream.state = nullptr; + + m_pStream.zalloc = nullptr; + m_pStream.zfree = nullptr; + m_pStream.opaque = nullptr; + + m_pStream.data_type = 0; + m_pStream.adler = 0; + m_pStream.reserved = 0; + + m_pStream.next_out = &m_nOutBuffer[0]; + m_pStream.avail_out = ZIPEXPORTBUFFERSIZE; + m_pStream.total_out = 0; + + nfInt32 nResult = deflateInit2(&m_pStream, Z_BEST_SPEED, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY); + if (nResult < 0) + throw CNMRException(NMR_ERROR_DEFLATEINITFAILED); + + m_bIsInitialized = true; + } + + CExportStream_ZIP::~CExportStream_ZIP() + { + if (m_bIsInitialized) { + finishDeflate(); + } + } + + nfBool CExportStream_ZIP::seekPosition(_In_ nfUint64 position, _In_ nfBool bHasToSucceed) + { + if (bHasToSucceed) + throw CNMRException(NMR_ERROR_ZIPSTREAMCANNOTSEEK); + return false; + } + + nfBool CExportStream_ZIP::seekForward(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed) + { + if (bHasToSucceed) + throw CNMRException(NMR_ERROR_ZIPSTREAMCANNOTSEEK); + return false; + } + + nfBool CExportStream_ZIP::seekFromEnd(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed) + { + if (bHasToSucceed) + throw CNMRException(NMR_ERROR_ZIPSTREAMCANNOTSEEK); + return false; + } + + nfUint64 CExportStream_ZIP::getPosition() + { + return m_pZIPWriter->getCurrentSize(m_nEntryKey); + } + + nfUint64 CExportStream_ZIP::writeBuffer(_In_ const void * pBuffer, _In_ nfUint64 cbTotalBytesToWrite) + { + if (!m_bIsInitialized) + throw CNMRException(NMR_ERROR_ZIPALREADYFINISHED); + + nfUint64 cbCount = cbTotalBytesToWrite; + const nfByte * pByte = (const nfByte *)pBuffer; + + while (cbCount > 0) { + nfUint32 cbBytesWritten; + if (cbCount < ZIPEXPORTWRITECHUNKSIZE) + cbBytesWritten = writeChunk(pByte, (nfUint32)cbCount); + else + cbBytesWritten = writeChunk(pByte, ZIPEXPORTWRITECHUNKSIZE); + + if (cbBytesWritten == 0) + throw CNMRException(NMR_ERROR_COULDNOTDEFLATE); + + cbCount -= cbBytesWritten; + } + + return cbTotalBytesToWrite; + } + + nfUint32 CExportStream_ZIP::writeChunk(_In_ const nfByte * pData, nfUint32 cbCount) + { + if ((pData == nullptr) || (cbCount == 0) || (cbCount > ZIPEXPORTWRITECHUNKSIZE)) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + m_pStream.next_in = (Bytef *) pData; + m_pStream.avail_in = cbCount; + + m_pZIPWriter->calculateChecksum(m_nEntryKey, pData, cbCount); + + while (m_pStream.avail_in > 0) { + nfInt32 nResult = deflate(&m_pStream, 0); + if (nResult < 0) + throw CNMRException(NMR_ERROR_COULDNOTDEFLATE); + + if (m_pStream.avail_out == 0) { + m_pZIPWriter->writeDeflatedBuffer(m_nEntryKey, &m_nOutBuffer[0], ZIPEXPORTBUFFERSIZE); + + m_pStream.next_out = &m_nOutBuffer[0]; + m_pStream.avail_out = ZIPEXPORTBUFFERSIZE; + } + } + + return cbCount; + + } + + + void CExportStream_ZIP::finishDeflate() + { + if (!m_bIsInitialized) + throw CNMRException(NMR_ERROR_ZIPALREADYFINISHED); + + m_pStream.next_in = nullptr; + m_pStream.avail_in = 0; + + nfBool bContinue = true; + while (bContinue) { + nfInt32 nResult = deflate(&m_pStream, Z_FINISH); + if (nResult < 0) + throw CNMRException(NMR_ERROR_COULDNOTDEFLATE); + + if ((nResult != Z_STREAM_END) && (m_pStream.avail_out == 0)) { + m_pZIPWriter->writeDeflatedBuffer(m_nEntryKey, &m_nOutBuffer[0], ZIPEXPORTBUFFERSIZE); + + m_pStream.next_out = &m_nOutBuffer[0]; + m_pStream.avail_out = ZIPEXPORTBUFFERSIZE; + } + else + bContinue = false; + } + + if (m_pStream.avail_out < ZIPEXPORTBUFFERSIZE) { + m_pZIPWriter->writeDeflatedBuffer(m_nEntryKey, &m_nOutBuffer[0], ZIPEXPORTBUFFERSIZE - m_pStream.avail_out); + } + + deflateEnd(&m_pStream); + m_bIsInitialized = false; + } + + void CExportStream_ZIP::flushZIPStream() + { + finishDeflate(); + } + +} diff --git a/Source/Common/Platform/NMR_ImportStream_Callback.cpp b/Source/Common/Platform/NMR_ImportStream_Callback.cpp new file mode 100644 index 0000000..ee0e4c2 --- /dev/null +++ b/Source/Common/Platform/NMR_ImportStream_Callback.cpp @@ -0,0 +1,169 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ImportStream_Callback.cpp implements the CExportStream_Callback Class. +This is a stream class for importing with a callback to custom data reader. + +--*/ + +#include "Common/Platform/NMR_ImportStream_Callback.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_StringUtils.h" + +#include + +namespace NMR { + + CImportStream_Callback::CImportStream_Callback() + :CImportStream () + { + // empty on purpose + m_pReadCallback = nullptr; + m_pUserData = nullptr; + m_pSeekCallback = nullptr; + m_nPosition = 0; + m_nSize = 0; + } + + CImportStream_Callback::CImportStream_Callback(_In_ ImportStream_ReadCallbackType pReadCallback, _In_ ImportStream_SeekCallbackType pSeekCallback, void * pUserData, _In_ nfUint64 nStreamSize) + : CImportStream() + { + m_pReadCallback = pReadCallback; + m_pSeekCallback = pSeekCallback; + m_pUserData = pUserData; + m_nPosition = 0; + m_nSize = nStreamSize; + } + + nfBool CImportStream_Callback::seekPosition(_In_ nfUint64 position, _In_ nfBool bHasToSucceed) + { + if (m_pSeekCallback == nullptr) { + if (bHasToSucceed) + throw CNMRException(NMR_ERROR_CALLBACKSTREAMCANNOTSEEK); + return false; + } + else { + if (position > m_nSize) + throw CNMRException(NMR_ERROR_COULDNOTSEEKSTREAM); + + nfUint64 nNewPosition = position; + nfUint32 nErrorCode = m_pSeekCallback(nNewPosition, m_pUserData); + if (nErrorCode != 0) + throw CNMRException(NMR_ERROR_COULDNOTSEEKSTREAM); + m_nPosition = nNewPosition; + return true; + } + } + + nfBool CImportStream_Callback::seekForward(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed) + { + if (m_pSeekCallback == nullptr) { + if (bHasToSucceed) + throw CNMRException(NMR_ERROR_CALLBACKSTREAMCANNOTSEEK); + return false; + } + else { + nfUint64 nNewPosition = m_nPosition + bytes; + if (nNewPosition > m_nSize) + throw CNMRException(NMR_ERROR_COULDNOTSEEKSTREAM); + + nfUint32 nErrorCode = m_pSeekCallback(nNewPosition, m_pUserData); + if (nErrorCode != 0) + throw CNMRException(NMR_ERROR_COULDNOTSEEKSTREAM); + m_nPosition = nNewPosition; + return true; + } + } + + nfBool CImportStream_Callback::seekFromEnd(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed) + { + if (m_pSeekCallback == nullptr) { + if (bHasToSucceed) + throw CNMRException(NMR_ERROR_CALLBACKSTREAMCANNOTSEEK); + return false; + } + else { + if (bytes > m_nSize) + throw CNMRException(NMR_ERROR_COULDNOTSEEKSTREAM); + + nfUint64 nNewPosition = m_nSize - bytes; + nfUint32 nErrorCode = m_pSeekCallback(nNewPosition, m_pUserData); + if (nErrorCode != 0) + throw CNMRException(NMR_ERROR_COULDNOTSEEKSTREAM); + m_nPosition = nNewPosition; + return true; + } + } + + nfUint64 CImportStream_Callback::getPosition() + { + return m_nPosition; + } + + nfUint64 CImportStream_Callback::readIntoBuffer(_In_ nfByte * pBuffer, _In_ nfUint64 cbTotalBytesToRead, nfBool bNeedsToReadAll) + { + if (m_pReadCallback == nullptr) + throw CNMRException(NMR_ERROR_COULDNOTREADFROMCALLBACKSTREAM); + + nfByte * pByte = (nfByte *)pBuffer; + nfUint64 cbBytesLeft = cbTotalBytesToRead; + while (cbBytesLeft > 0) { + nfUint64 cbBytes = cbBytesLeft; + if (cbBytes > IMPORTSTREAM_CALLBACK_BUFFERSIZE) + cbBytes = IMPORTSTREAM_CALLBACK_BUFFERSIZE; + + nfUint32 nError = m_pReadCallback(pByte, (nfUint32) cbBytes, m_pUserData); + if (nError != 0) + throw CNMRException(NMR_ERROR_COULDNOTREADFROMCALLBACKSTREAM); + + pByte += cbBytes; + cbBytesLeft -= cbBytes; + } + + m_nPosition += cbTotalBytesToRead; + if (m_nPosition > m_nSize) + m_nSize = m_nPosition; + + return cbTotalBytesToRead; + } + + + + nfUint64 CImportStream_Callback::retrieveSize() { + return m_nSize; + } + + void CImportStream_Callback::writeToFile(_In_ const nfWChar * pwszFileName) { + throw CNMRException(NMR_ERROR_NOTIMPLEMENTED); + } + + PImportStream CImportStream_Callback::copyToMemory() { + throw CNMRException(NMR_ERROR_NOTIMPLEMENTED); + } +} diff --git a/Source/Common/Platform/NMR_ImportStream_Compressed.cpp b/Source/Common/Platform/NMR_ImportStream_Compressed.cpp new file mode 100644 index 0000000..53cbbf8 --- /dev/null +++ b/Source/Common/Platform/NMR_ImportStream_Compressed.cpp @@ -0,0 +1,139 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ImportStream_Compressed.h defines the CImportStream_Compressed Class. +This is a stream class for importing from a compressed object. + +--*/ + +#include "Common/Platform/NMR_ImportStream_Shared_Memory.h" +#include "Common/Platform/NMR_ImportStream_Compressed.h" +#include "Common/NMR_Exception.h" + +namespace NMR { + + CImportStream_Compressed::CImportStream_Compressed(PImportStream pCompressedStream) + { + if (nullptr == pCompressedStream) + throw CNMRException(NMR_ERROR_INVALIDPOINTER); + m_pCompressedStream = pCompressedStream; + + // Source: http://zlib.net/zpipe.c + m_strm.zalloc = Z_NULL; + m_strm.zfree = Z_NULL; + m_strm.opaque = Z_NULL; + m_strm.avail_in = 0; + m_strm.next_in = Z_NULL; + + if (inflateInit(&m_strm) != Z_OK) + throw CNMRException(NMR_ERROR_COULDNOTINITINFLATE); + } + + CImportStream_Compressed::~CImportStream_Compressed() + { + (void)inflateEnd(&m_strm); + } + + nfBool CImportStream_Compressed::seekPosition(_In_ nfUint64 position, _In_ nfBool bHasToSucceed) + { + return m_pCompressedStream->seekPosition(position, bHasToSucceed); + } + + nfBool CImportStream_Compressed::seekForward(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed) + { + return m_pCompressedStream->seekForward(bytes, bHasToSucceed); + } + + nfBool CImportStream_Compressed::seekFromEnd(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed) + { + return m_pCompressedStream->seekFromEnd(bytes, bHasToSucceed); + } + + nfUint64 CImportStream_Compressed::getPosition() + { + return m_pCompressedStream->getPosition(); + } + + nfUint64 CImportStream_Compressed::readIntoBuffer(nfByte * pBuffer, nfUint64 cbTotalBytesToRead, nfBool bNeedsToReadAll) + { + nfBool firstRead = m_strm.next_in == Z_NULL; + nfBool hasDecompressLeftovers = m_strm.avail_out == 0; + if (firstRead || !hasDecompressLeftovers) { + m_strm.avail_in = (nfUint32) m_pCompressedStream->readIntoBuffer(in, IMPORTSTREAM_COMPRESSED_CHUNKSIZE, bNeedsToReadAll); + if (m_strm.avail_in == 0) + return 0; + m_strm.next_in = in; + } + + m_strm.avail_out = (nfUint32) cbTotalBytesToRead; + m_strm.next_out = pBuffer; + nfInt32 ret = inflate(&m_strm, Z_NO_FLUSH); + switch (ret) { + case Z_NEED_DICT: + case Z_DATA_ERROR: + case Z_MEM_ERROR: + (void)inflateEnd(&m_strm); + throw CNMRException(NMR_ERROR_COULDNOTINFLATE); + } + if (m_strm.avail_out == 0) { + nfBool reachedEndOfBuffer = m_strm.avail_in == 0; + if (reachedEndOfBuffer && ret != Z_STREAM_END) { + throw CNMRException(NMR_ERROR_COULDNOTINFLATE); + } + return cbTotalBytesToRead; + } + + nfUint64 bytesDecompressed = cbTotalBytesToRead - m_strm.avail_out; + return readIntoBuffer(pBuffer + bytesDecompressed, m_strm.avail_out, bNeedsToReadAll) + bytesDecompressed; + } + + nfUint64 CImportStream_Compressed::retrieveSize() + { + return m_decompressedBuffer.size(); + } + + void CImportStream_Compressed::writeToFile(_In_ const nfWChar * pwszFileName) + { + throw CNMRException(NMR_ERROR_NOTIMPLEMENTED); + } + + PImportStream CImportStream_Compressed::copyToMemory() + { + nfUint64 bytesRead; + nfUint64 currentPosition = 0; + nfUint64 chunkSize = IMPORTSTREAM_READ_BUFFER_CHUNKSIZE; + do { + m_decompressedBuffer.resize(m_decompressedBuffer.size() + chunkSize); + bytesRead = readIntoBuffer(&m_decompressedBuffer[currentPosition], chunkSize, false); + currentPosition += bytesRead; + } while (chunkSize == bytesRead); + return std::make_shared(m_decompressedBuffer.data(), m_decompressedBuffer.size()); + } + + +} diff --git a/Source/Common/Platform/NMR_ImportStream_Encrypted.cpp b/Source/Common/Platform/NMR_ImportStream_Encrypted.cpp new file mode 100644 index 0000000..bdb46be --- /dev/null +++ b/Source/Common/Platform/NMR_ImportStream_Encrypted.cpp @@ -0,0 +1,91 @@ +/*++ + +Copyright (C) 2020 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +Abstract: This is a stub class implementation of CImportStream_Encrypted + +*/ + +#include "Common/Platform/NMR_ImportStream_Encrypted.h" +#include "Common/Platform/NMR_ImportStream_Unique_Memory.h" +#include "Common/NMR_Exception.h" +#include +#include +namespace NMR { + CImportStream_Encrypted::CImportStream_Encrypted(PImportStream pEncryptedStream, ContentEncryptionDescriptor pDecryptContext) + :m_pEncryptedStream(pEncryptedStream), m_pDecryptContext(pDecryptContext) + { + if (nullptr == pEncryptedStream) + throw CNMRException(NMR_ERROR_INVALIDPOINTER); + m_header.readFrom(pEncryptedStream); + } + + nfBool CImportStream_Encrypted::seekPosition(nfUint64 position, nfBool bHasToSucceed) { + return m_pEncryptedStream->seekPosition(position + m_header.headerSize(), bHasToSucceed); + } + + nfBool CImportStream_Encrypted::seekForward(nfUint64 bytes, nfBool bHasToSucceed) { + return m_pEncryptedStream->seekForward(bytes, bHasToSucceed); + } + + nfBool CImportStream_Encrypted::seekFromEnd(nfUint64 bytes, nfBool bHasToSucceed) { + if (m_pEncryptedStream->getPosition() + m_header.headerSize() >= bytes) { + return m_pEncryptedStream->seekFromEnd(bytes, bHasToSucceed); + } else if (bHasToSucceed) { + throw CNMRException(NMR_ERROR_COULDNOTSEEKSTREAM); + } + return false; + } + + nfUint64 CImportStream_Encrypted::readIntoBuffer(nfByte * pBuffer, nfUint64 cbTotalBytesToRead, nfBool bNeedsToReadAll) { + std::vector decBuffer(cbTotalBytesToRead, 0); + nfUint64 bytesRead = m_pEncryptedStream->readIntoBuffer(decBuffer.data(), cbTotalBytesToRead, bNeedsToReadAll); + if (bytesRead > 0) { + nfUint64 decryted = m_pDecryptContext.m_fnCrypt(bytesRead, decBuffer.data(), pBuffer, m_pDecryptContext.m_sDekDecryptData); + if (decryted != bytesRead) + throw CNMRException(NMR_ERROR_CALCULATIONTERMINATED); + } + return bytesRead; + } + + nfUint64 CImportStream_Encrypted::retrieveSize() { + return m_pEncryptedStream->retrieveSize() - m_header.headerSize(); + } + + void CImportStream_Encrypted::writeToFile(const nfWChar * pwszFileName) { + m_pEncryptedStream->writeToFile(pwszFileName); + } + + PImportStream CImportStream_Encrypted::copyToMemory() { + nfUint64 cbStreamSize = retrieveSize(); + return std::make_shared(this, cbStreamSize, false); + } + + nfUint64 CImportStream_Encrypted::getPosition() { + return m_pEncryptedStream->getPosition() - m_header.headerSize(); + } + + +} \ No newline at end of file diff --git a/Source/Common/Platform/NMR_ImportStream_Memory.cpp b/Source/Common/Platform/NMR_ImportStream_Memory.cpp new file mode 100644 index 0000000..0aecd47 --- /dev/null +++ b/Source/Common/Platform/NMR_ImportStream_Memory.cpp @@ -0,0 +1,139 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ImportStream_Memory.cpp implements the CImportStream_Memory Class. +This is an abstract platform independent class for keeping data in a memory stream. + +--*/ + +#include "Common/Platform/NMR_ImportStream_Memory.h" +#include "Common/Platform/NMR_Platform.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_StringUtils.h" + +#include + +namespace NMR { + + CImportStream_Memory::~CImportStream_Memory() + { + } + + nfBool CImportStream_Memory::seekPosition(_In_ nfUint64 nPosition, _In_ nfBool bHasToSucceed) + { + if (nPosition > m_cbSize) { + if (bHasToSucceed) + throw CNMRException(NMR_ERROR_COULDNOTSEEKSTREAM); + return false; + } + + m_nPosition = nPosition; + + return true; + } + + nfBool CImportStream_Memory::seekForward(_In_ nfUint64 cbBytes, _In_ nfBool bHasToSucceed) + { + nfUint64 nPosition = m_nPosition + cbBytes; + + if (nPosition > m_cbSize) { + if (bHasToSucceed) + throw CNMRException(NMR_ERROR_COULDNOTSEEKSTREAM); + return false; + } + + m_nPosition = nPosition; + return true; + } + + nfBool CImportStream_Memory::seekFromEnd(_In_ nfUint64 cbBytes, _In_ nfBool bHasToSucceed) + { + if (cbBytes > m_cbSize) { + if (bHasToSucceed) + throw CNMRException(NMR_ERROR_COULDNOTSEEKSTREAM); + return false; + } + + m_nPosition = m_cbSize - cbBytes; + return true; + } + + nfUint64 CImportStream_Memory::getPosition() + { + return m_nPosition; + } + + nfUint64 CImportStream_Memory::readIntoBuffer(_In_ nfByte * pBuffer, _In_ nfUint64 cbTotalBytesToRead, nfBool bNeedsToReadAll) + { + __NMRASSERT(m_nPosition <= m_cbSize); + nfUint64 cbBytesLeft = (m_cbSize - m_nPosition); + nfUint64 cbBytesToRead = cbTotalBytesToRead; + + if (cbBytesToRead > cbBytesLeft) + cbBytesToRead = cbBytesLeft; + + if (cbBytesToRead > 0) { + nfUint64 nIndex = cbBytesToRead; + const nfByte * pSource = getAt(m_nPosition); + nfByte * pTarget = pBuffer; + + while (nIndex > 0) { + *pTarget = *pSource; + nIndex--; + pSource++; + pTarget++; + } + + m_nPosition += cbBytesToRead; + } + + if ((cbBytesToRead != cbTotalBytesToRead) && bNeedsToReadAll) + throw CNMRException(NMR_ERROR_COULDNOTREADFULLDATA); + + return cbBytesToRead; + + } + + nfUint64 CImportStream_Memory::retrieveSize() + { + return m_cbSize; + } + + void CImportStream_Memory::writeToFile(_In_ const nfWChar * pwszFileName) + { + if (pwszFileName == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + std::string sUTF8FileName = fnUTF16toUTF8(pwszFileName); + PExportStream pExportStream = fnCreateExportStreamInstance(sUTF8FileName.c_str()); + if (m_cbSize > 0) { + pExportStream->writeBuffer(getAt(0), m_cbSize); + } + } +} diff --git a/Source/Common/Platform/NMR_ImportStream_Native.cpp b/Source/Common/Platform/NMR_ImportStream_Native.cpp new file mode 100644 index 0000000..878ffb2 --- /dev/null +++ b/Source/Common/Platform/NMR_ImportStream_Native.cpp @@ -0,0 +1,161 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ImportStream_Native.cpp implements the CImportStream_Native Class. +This is a stream class for importing from streams with with std::streams. + +--*/ + +#include "Common/Platform/NMR_ImportStream_Native.h" +#include "Common/Platform/NMR_ImportStream_Unique_Memory.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_StringUtils.h" + +#include + +namespace NMR { + + CImportStream_Native::CImportStream_Native(_In_ const nfWChar * pwszFileName) + { + if (pwszFileName == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + std::wstring sFileName(pwszFileName); +#if defined(_WIN32) && !defined(__MINGW32__) + m_Stream.open(sFileName.c_str(), std::ios::in | std::ios::binary); +#else + std::string sUTF8Name = fnUTF16toUTF8(sFileName); + m_Stream.open(sUTF8Name.c_str(), std::ios::in | std::ios::binary); +#endif + if (m_Stream.fail()) + throw CNMRException(NMR_ERROR_COULDNOTOPENFILE); + } + + CImportStream_Native::~CImportStream_Native() + { + if (m_Stream.is_open()) { + m_Stream.close(); + } + } + + nfBool CImportStream_Native::seekPosition(_In_ nfUint64 position, _In_ nfBool bHasToSucceed) + { + std::streampos nStreamPos = position; + m_Stream.seekg(nStreamPos, std::ios_base::beg); + + if (m_Stream.fail()) { + if (bHasToSucceed) + throw CNMRException(NMR_ERROR_COULDNOTSEEKSTREAM); + + return false; + } + + return true; + } + + nfBool CImportStream_Native::seekForward(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed) + { + std::streampos nStreamOffset = bytes; + m_Stream.seekg(nStreamOffset, std::ios_base::cur); + + if (m_Stream.fail()) { + if (bHasToSucceed) + throw CNMRException(NMR_ERROR_COULDNOTSEEKSTREAM); + + return false; + } + + return true; + } + + nfBool CImportStream_Native::seekFromEnd(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed) + { + std::streampos nStreamOffset = 0-bytes; + m_Stream.seekg(nStreamOffset, std::ios_base::end); + + if (m_Stream.fail()) { + if (bHasToSucceed) + throw CNMRException(NMR_ERROR_COULDNOTSEEKSTREAM); + + return false; + } + + return true; + } + + nfUint64 CImportStream_Native::getPosition() + { + std::streampos nStreamPosition = m_Stream.tellg(); + if (nStreamPosition < 0) + throw CNMRException(NMR_ERROR_COULDNOTGETSTREAMPOSITION); + + return nStreamPosition; + } + + nfUint64 CImportStream_Native::readIntoBuffer(_In_ nfByte * pBuffer, _In_ nfUint64 cbTotalBytesToRead, nfBool bNeedsToReadAll) + { + if (pBuffer == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + char * pChar = (char*)pBuffer; + std::streamsize nSize = cbTotalBytesToRead; + m_Stream.read(pChar, nSize); + if (m_Stream.fail()) + throw CNMRException(NMR_ERROR_COULDNOTREADSTREAM); + + std::streamsize nReadBytes = m_Stream.gcount(); + if (nReadBytes != nSize) { + if (bNeedsToReadAll) + throw CNMRException(NMR_ERROR_COULDNOTREADFULLDATA); + } + + return nReadBytes; + } + + nfUint64 CImportStream_Native::retrieveSize() + { + nfUint64 nOrigPosition = getPosition(); + seekFromEnd(0, true); + nfUint64 nSize = getPosition(); + seekPosition(nOrigPosition, true); + return nSize; + } + + void CImportStream_Native::writeToFile(_In_ const nfWChar * pwszFileName) + { + throw CNMRException(NMR_ERROR_NOTIMPLEMENTED); + } + + PImportStream CImportStream_Native::copyToMemory() + { + nfUint64 cbStreamSize = retrieveSize(); + return std::make_shared(this, cbStreamSize, false); + } + +} diff --git a/Source/Common/Platform/NMR_ImportStream_Shared_Memory.cpp b/Source/Common/Platform/NMR_ImportStream_Shared_Memory.cpp new file mode 100644 index 0000000..aa12d3e --- /dev/null +++ b/Source/Common/Platform/NMR_ImportStream_Shared_Memory.cpp @@ -0,0 +1,66 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ImportStream_Shared_Memory.cpp implements the CImportStream_Memory Class. +This is a platform independent class for keeping data in a memory stream that doesn't own the wrapped buffer. + +--*/ + +#include "Common/Platform/NMR_ImportStream_Shared_Memory.h" +#include "Common/Platform/NMR_ImportStream_Unique_Memory.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CImportStream_Shared_Memory::CImportStream_Shared_Memory(_In_ const nfByte * pBuffer, _In_ nfUint64 cbBytes) + { + if (pBuffer == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + if (cbBytes > NMR_IMPORTSTREAM_MAXMEMSTREAMSIZE) + throw CNMRException(NMR_ERROR_INVALIDBUFFERSIZE); + + m_cbSize = cbBytes; + m_nPosition = 0; + + m_Buffer = pBuffer; + } + + PImportStream CImportStream_Shared_Memory::copyToMemory() + { + __NMRASSERT(m_nPosition <= m_cbSize); + + return std::make_shared(this, m_cbSize - m_nPosition, true); + } + + __NMR_INLINE const nfByte * CImportStream_Shared_Memory::getAt(nfUint64 nPosition) { + return &m_Buffer[nPosition]; + } + +} \ No newline at end of file diff --git a/Source/Common/Platform/NMR_ImportStream_Unique_Memory.cpp b/Source/Common/Platform/NMR_ImportStream_Unique_Memory.cpp new file mode 100644 index 0000000..43fd428 --- /dev/null +++ b/Source/Common/Platform/NMR_ImportStream_Unique_Memory.cpp @@ -0,0 +1,135 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ImportStream_Unique_Memory.cpp implements the CImportStream_Memory Class. +This is a platform independent class for keeping data in a memory stream that owns the wrapped buffer. + +--*/ + +#include "Common/Platform/NMR_ImportStream_Unique_Memory.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CImportStream_Unique_Memory::CImportStream_Unique_Memory() + { + m_cbSize = 0; + m_nPosition = 0; + } + + + CImportStream_Unique_Memory::CImportStream_Unique_Memory(_In_ CImportStream * pStream, _In_ nfUint64 cbBytesToCopy, _In_ nfBool bNeedsToCopyAllBytes) + { + if (pStream == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + if (cbBytesToCopy > NMR_IMPORTSTREAM_MAXMEMSTREAMSIZE) + throw CNMRException(NMR_ERROR_INVALIDBUFFERSIZE); + + + // Retrieve Capacity and allocate buffer. + nfUint64 cbCapacity = cbBytesToCopy; + try { + m_Buffer.resize((size_t)cbCapacity); + } + catch (std::bad_alloc&) { + throw CNMRException(NMR_ERROR_INVALIDBUFFERSIZE); + } + + m_cbSize = 0; + m_nPosition = 0; + + while (m_cbSize < cbCapacity) { + + // Only read in chunks + nfUint64 cbBytesToRead = cbCapacity - m_cbSize; + if (cbBytesToRead > NMR_IMPORTSTREAM_READCHUNKSIZE) + cbBytesToRead = NMR_IMPORTSTREAM_READCHUNKSIZE; + + // Read bytes into memory + nfUint64 cbBytesRead; + cbBytesRead = pStream->readIntoBuffer(&m_Buffer[(size_t) m_cbSize], cbBytesToRead, false); + + // increase size + m_cbSize += cbBytesRead; + + if (cbBytesRead != cbBytesToRead) + break; + } + + if ((m_cbSize != cbCapacity) && (bNeedsToCopyAllBytes)) + throw CNMRException(NMR_ERROR_COULDNOTREADFULLDATA); + + + } + + CImportStream_Unique_Memory::CImportStream_Unique_Memory(_In_ const nfByte * pBuffer, _In_ nfUint64 cbBytes) + { + if (pBuffer == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + if (cbBytes > NMR_IMPORTSTREAM_MAXMEMSTREAMSIZE) + throw CNMRException(NMR_ERROR_INVALIDBUFFERSIZE); + + // Retrieve Capacity and allocate buffer. + m_Buffer.resize((size_t) cbBytes); + + m_cbSize = cbBytes; + m_nPosition = 0; + + const nfByte * pSource = pBuffer; + nfByte * pTarget = &m_Buffer[0]; + + nfUint64 nIndex = cbBytes; + while (nIndex > 0) { + *pTarget = *pSource; + + pSource++; + pTarget++; + nIndex--; + } + } + + PImportStream CImportStream_Unique_Memory::copyToMemory() + { + __NMRASSERT(m_nPosition <= m_cbSize); + + return std::make_shared(this, m_cbSize - m_nPosition, true); + } + + __NMR_INLINE const nfByte * CImportStream_Unique_Memory::getAt(nfUint64 nPosition) { + + if (nPosition >= (uint64_t) m_Buffer.size()) + throw CNMRException(NMR_ERROR_COULDNOTREADSTREAM); + + // On 32 bit system, nPosition is definitely a 32bit value, because m_Buffer.size () is a size_t + return &m_Buffer[(size_t) nPosition]; + } + +} \ No newline at end of file diff --git a/Source/Common/Platform/NMR_ImportStream_ZIP.cpp b/Source/Common/Platform/NMR_ImportStream_ZIP.cpp new file mode 100644 index 0000000..2ef6ba2 --- /dev/null +++ b/Source/Common/Platform/NMR_ImportStream_ZIP.cpp @@ -0,0 +1,133 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ImportStream_ZIP.cpp implements the CImportStream_ZIP Class. +This is a stream class for importing from a libZIP object. + +--*/ + +#include "Common/Platform/NMR_ImportStream_ZIP.h" +#include "Common/Platform/NMR_ImportStream_Unique_Memory.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include +#include + +namespace NMR { + + CImportStream_ZIP::CImportStream_ZIP(_In_ zip_file_t * pFile, _In_ nfUint64 nSize) + { + if (pFile == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + m_pFile = pFile; + m_nSize = nSize; + } + + CImportStream_ZIP::~CImportStream_ZIP() + { + if (m_pFile != nullptr) { + zip_fclose(m_pFile); + } + m_pFile = nullptr; + } + + nfBool CImportStream_ZIP::seekPosition(_In_ nfUint64 position, _In_ nfBool bHasToSucceed) + { + throw CNMRException(NMR_ERROR_COULDNOTSEEKINZIP); + } + + nfBool CImportStream_ZIP::seekForward(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed) + { + throw CNMRException(NMR_ERROR_COULDNOTSEEKINZIP); + } + + nfBool CImportStream_ZIP::seekFromEnd(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed) + { + throw CNMRException(NMR_ERROR_COULDNOTSEEKINZIP); + } + + nfUint64 CImportStream_ZIP::getPosition() { + throw CNMRException(NMR_ERROR_COULDNOTSEEKINZIP); + } + + nfUint64 CImportStream_ZIP::readIntoBuffer(_In_ nfByte * pBuffer, _In_ nfUint64 cbTotalBytesToRead, nfBool bNeedsToReadAll) + { + nfUint64 cbBytesLeft = cbTotalBytesToRead; + nfUint64 cbBytesRead = 0; + + _In_ nfByte * pData = pBuffer; + while (cbBytesLeft > 0) { + nfUint32 cbBytesToRead; + if (cbBytesLeft > IMPORTSTREAM_ZIP_CHUNKSIZE) + cbBytesToRead = IMPORTSTREAM_ZIP_CHUNKSIZE; + else + cbBytesToRead = (nfUint32)cbBytesLeft; + cbBytesLeft -= cbBytesToRead; + + nfInt64 nfSize = zip_fread(m_pFile, pData, cbBytesToRead); + if (nfSize < 0) + throw CNMRException(NMR_ERROR_COULDNOTREADSTREAM); + cbBytesRead += nfSize; + + if (nfSize != (nfInt64)cbBytesToRead) + break; + + pData += nfSize; + + + } + + + if ((nfUint64)cbBytesRead != cbTotalBytesToRead) { + if (bNeedsToReadAll) + throw CNMRException(NMR_ERROR_COULDNOTREADFULLDATA); + } + + return (nfUint64)cbBytesRead; + } + + nfUint64 CImportStream_ZIP::retrieveSize() + { + return m_nSize; + } + + void CImportStream_ZIP::writeToFile(_In_ const nfWChar * pwszFileName) + { + throw CNMRException(NMR_ERROR_NOTIMPLEMENTED); + } + + PImportStream CImportStream_ZIP::copyToMemory() + { + nfUint64 cbStreamSize = retrieveSize(); + + return std::make_shared(this, cbStreamSize, false); + } + + +} diff --git a/Source/Common/Platform/NMR_Platform.cpp b/Source/Common/Platform/NMR_Platform.cpp new file mode 100644 index 0000000..c32991f --- /dev/null +++ b/Source/Common/Platform/NMR_Platform.cpp @@ -0,0 +1,65 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_Platform.cpp implements several factory functions which create platform +specific classes. + +--*/ + +#include "Common/Platform/NMR_Platform.h" +#include "Common/NMR_Exception.h" + + +#define NMR_PLATFORM_XMLREADER_BUFFERSIZE 65536 + +#include "Common/Platform/NMR_ImportStream_Native.h" +#include "Common/Platform/NMR_ExportStream_Native.h" +#include "Common/Platform/NMR_XmlReader_Native.h" +#include "Common/NMR_StringUtils.h" + + +namespace NMR { + + PImportStream fnCreateImportStreamInstance (_In_ const nfChar * pszFileName) + { + std::wstring sFileName = fnUTF8toUTF16(pszFileName); + return std::make_shared (sFileName.c_str()); + } + + PExportStream fnCreateExportStreamInstance (_In_ const nfChar * pszFileName) + { + std::wstring sFileName = fnUTF8toUTF16(pszFileName); + return std::make_shared (sFileName.c_str()); + } + + PXmlReader fnCreateXMLReaderInstance (_In_ PImportStream pImportStream, PProgressMonitor pProgressMonitor) + { + return std::make_shared (pImportStream, NMR_PLATFORM_XMLREADER_BUFFERSIZE, pProgressMonitor); + } + +} diff --git a/Source/Common/Platform/NMR_PortableZIPWriter.cpp b/Source/Common/Platform/NMR_PortableZIPWriter.cpp new file mode 100644 index 0000000..c20cacc --- /dev/null +++ b/Source/Common/Platform/NMR_PortableZIPWriter.cpp @@ -0,0 +1,381 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_PortableZIPWriter.cpp implements a portable and fast writer of ZIP files + +--*/ + +#include "Common/Platform/NMR_PortableZIPWriter.h" +#include "Common/Platform/NMR_ExportStream_ZIP.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_StringUtils.h" + +namespace NMR { + + CPortableZIPWriter::CPortableZIPWriter(_In_ PExportStream pExportStream, _In_ nfBool bWriteZIP64) + { + if (pExportStream.get() == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + m_pExportStream = pExportStream; + m_nCurrentEntryKey = 0; + m_nNextEntryKey = 1; + m_pCurrentEntry = nullptr; + m_bIsFinished = false; + m_bWriteZIP64 = bWriteZIP64; + + if (m_bWriteZIP64) { + m_nVersionMade = ZIPFILEVERSIONNEEDEDZIP64; + m_nVersionNeeded = ZIPFILEVERSIONNEEDEDZIP64; + } + else { + m_nVersionMade = ZIPFILEVERSIONNEEDED; + m_nVersionNeeded = ZIPFILEVERSIONNEEDED; + } + + if (m_pExportStream->getPosition() != 0) + throw CNMRException(NMR_ERROR_EXPORTSTREAMNOTEMPTY); + + } + + CPortableZIPWriter::~CPortableZIPWriter() + { + if (!m_bIsFinished) + writeDirectory(); + } + + PExportStream CPortableZIPWriter::createEntry(_In_ const std::string sName, _In_ nfTimeStamp nUnixTimeStamp) + { + if (m_bIsFinished) + throw CNMRException(NMR_ERROR_ZIPALREADYFINISHED); + // Finish old entry state + closeEntry(); + + // Initialize new entry state + m_nCurrentEntryKey = m_nNextEntryKey; + m_nNextEntryKey++; + if (m_nNextEntryKey >= ZIPFILEMAXENTRIES) + throw CNMRException(NMR_ERROR_ZIPENTRYOVERFLOW); + + // Convert Name to UTF8 + std::string sFilteredName = fnRemoveLeadingPathDelimiter(sName); + std::string sUTF8Name = sFilteredName; + if (sUTF8Name.length() > ZIPFILEMAXFILENAMELENGTH) + throw CNMRException(NMR_ERRORINVALIDZIPNAME); + nfUint32 nNameLength = (nfUint32)sUTF8Name.length(); + + // Convert Timestamp to File Date + nfUint32 nFileDate = 0; + nfUint16 nLastModTime = nFileDate % 65536; + nfUint16 nLastModDate = nFileDate / 65536; + + // Write local file header + ZIPLOCALFILEHEADER LocalHeader; + LocalHeader.m_nSignature = ZIPFILEHEADERSIGNATURE; + LocalHeader.m_nVersion = m_nVersionNeeded; + LocalHeader.m_nGeneralPurposeFlags = 0; + LocalHeader.m_nCompressionMethod = ZIPFILECOMPRESSION_DEFLATED; + LocalHeader.m_nLastModTime = nLastModTime; + LocalHeader.m_nLastModDate = nLastModDate; + LocalHeader.m_nCRC32 = 0; + LocalHeader.m_nCompressedSize = 0; + LocalHeader.m_nUnCompressedSize = 0; + LocalHeader.m_nFileNameLength = nNameLength; + LocalHeader.m_nExtraFieldLength = 0;// sizeof(ZIPLOCALFILEADDITIONALHEADER) + sizeof(ZIPLOCALFILEEXTENDEDINFORMATIONFIELD); + + if (m_bWriteZIP64) { + LocalHeader.m_nExtraFieldLength += sizeof(ZIP64EXTRAINFORMATIONFIELD); + } + + ZIP64EXTRAINFORMATIONFIELD zip64ExtraInformation; + zip64ExtraInformation.m_nTag = ZIPFILEDATAZIP64EXTENDEDINFORMATIONEXTRAFIELD; + zip64ExtraInformation.m_nFieldSize = sizeof(ZIP64EXTRAINFORMATIONFIELD) - 4; + zip64ExtraInformation.m_nCompressedSize = 0; + zip64ExtraInformation.m_nUncompressedSize = 0; + + // Write data to ZIP stream + nfUint64 nFilePosition = m_pExportStream->getPosition(); + + // prepare byte-buffer for big-endian machines + if (isBigEndian()) { + LocalHeader.swapByteOrder(); + } + m_pExportStream->writeBuffer(&LocalHeader, sizeof(LocalHeader)); + m_pExportStream->writeBuffer(sUTF8Name.c_str(), nNameLength); + nfUint64 nExtInfoPosition = m_pExportStream->getPosition(); + if (m_bWriteZIP64) { + // prepare byte-buffer for big-endian machines + if (isBigEndian()) { + zip64ExtraInformation.swapByteOrder(); + } + m_pExportStream->writeBuffer(&zip64ExtraInformation, sizeof(zip64ExtraInformation)); + } + + nfUint64 nDataPosition = m_pExportStream->getPosition(); + + // create list entry + m_pCurrentEntry = std::make_shared(sUTF8Name, nLastModTime, nLastModDate, nFilePosition, nExtInfoPosition, nDataPosition); + m_Entries.push_back(m_pCurrentEntry); + + // Return new ZIP Entry stream + m_pCurrentStream = std::make_shared(this, m_nCurrentEntryKey); + return m_pCurrentStream; + } + + void CPortableZIPWriter::closeEntry() + { + if (m_bIsFinished) + throw CNMRException(NMR_ERROR_ZIPALREADYFINISHED); + + if (m_pCurrentEntry.get() != nullptr) { + // finish current stream writing + CExportStream_ZIP * pZipStream = dynamic_cast(m_pCurrentStream.get()); + if (pZipStream == nullptr) + throw CNMRException(NMR_ERROR_NOEXPORTSTREAM); + pZipStream->flushZIPStream(); + + // Write CRC and Size + ZIPLOCALFILEDESCRIPTOR FileDescriptor; + FileDescriptor.m_nCRC32 = m_pCurrentEntry->getCRC32(); + if (m_bWriteZIP64) { + FileDescriptor.m_nCompressedSize =0xFFFFFFFF; + FileDescriptor.m_nUnCompressedSize = 0xFFFFFFFF; + } + else { + if ((m_pCurrentEntry->getCompressedSize() > ZIPFILEMAXIMUMSIZENON64) || + (m_pCurrentEntry->getUncompressedSize() > ZIPFILEMAXIMUMSIZENON64)) + throw CNMRException(NMR_ERROR_ZIPENTRYNON64_TOOLARGE); + FileDescriptor.m_nCompressedSize = (nfUint32)m_pCurrentEntry->getCompressedSize(); + FileDescriptor.m_nUnCompressedSize = (nfUint32)m_pCurrentEntry->getUncompressedSize(); + } + + ZIP64EXTRAINFORMATIONFIELD zip64ExtraInformation; + zip64ExtraInformation.m_nTag = ZIPFILEDATAZIP64EXTENDEDINFORMATIONEXTRAFIELD; + zip64ExtraInformation.m_nFieldSize = sizeof(ZIP64EXTRAINFORMATIONFIELD) - 4; + zip64ExtraInformation.m_nCompressedSize = m_pCurrentEntry->getCompressedSize(); + zip64ExtraInformation.m_nUncompressedSize = m_pCurrentEntry->getUncompressedSize(); + + // Write File Descriptor to file + m_pExportStream->seekPosition(m_pCurrentEntry->getFilePosition() + ZIPFILEDESCRIPTOROFFSET, true); + + // prepare byte-buffer for big-endian machines + if (isBigEndian()) { + FileDescriptor.swapByteOrder(); + } + m_pExportStream->writeBuffer(&FileDescriptor, sizeof(FileDescriptor)); + + if (m_bWriteZIP64) { + // Write Extra Information to file + m_pExportStream->seekPosition(m_pCurrentEntry->getExtInfoPosition(), true); + + // prepare byte-buffer for big-endian machines + if (isBigEndian()) { + zip64ExtraInformation.swapByteOrder(); + } + m_pExportStream->writeBuffer(&zip64ExtraInformation, sizeof(zip64ExtraInformation)); + } + + // Reset file pointer + m_pExportStream->seekFromEnd(0, true); + } + + m_pCurrentStream = nullptr; + m_pCurrentEntry = nullptr; + m_nCurrentEntryKey = 0; + } + + void CPortableZIPWriter::calculateChecksum(_In_ nfUint32 nEntryKey, _In_ const void * pBuffer, _In_ nfUint32 cbUncompressedBytes) + { + if (m_pCurrentEntry.get() == nullptr) + throw CNMRException(NMR_ERROR_INVALIDZIPENTRY); + + if (pBuffer == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + if (nEntryKey != m_nCurrentEntryKey) + throw CNMRException(NMR_ERROR_INVALIDZIPENTRYKEY); + + if (cbUncompressedBytes > 0) { + m_pCurrentEntry->calculateChecksum(pBuffer, cbUncompressedBytes); + m_pCurrentEntry->increaseUncompressedSize(cbUncompressedBytes); + } + } + + + void CPortableZIPWriter::writeDeflatedBuffer(_In_ nfUint32 nEntryKey, _In_ const void * pBuffer, _In_ nfUint32 cbCompressedBytes) + { + if (m_pCurrentEntry.get() == nullptr) + throw CNMRException(NMR_ERROR_INVALIDZIPENTRY); + + if (pBuffer == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + if (nEntryKey != m_nCurrentEntryKey) + throw CNMRException(NMR_ERROR_INVALIDZIPENTRYKEY); + + if (cbCompressedBytes > 0) { + m_pExportStream->writeBuffer(pBuffer, cbCompressedBytes); + m_pCurrentEntry->increaseCompressedSize(cbCompressedBytes); + } + } + + nfUint64 CPortableZIPWriter::getCurrentSize(_In_ nfUint32 nEntryKey) + { + if (m_pCurrentEntry.get() == nullptr) + throw CNMRException(NMR_ERROR_INVALIDZIPENTRY); + + if (nEntryKey != m_nCurrentEntryKey) + throw CNMRException(NMR_ERROR_INVALIDZIPENTRYKEY); + return m_pCurrentEntry->getUncompressedSize(); + } + + + void CPortableZIPWriter::writeDirectory() + { + closeEntry(); + + nfUint64 nCentralDirStartPos = m_pExportStream->getPosition(); + auto iIterator = m_Entries.begin(); + while (iIterator != m_Entries.end()) { + PPortableZIPWriterEntry pEntry = *iIterator; + std::string sUTF8Name = pEntry->getUTF8Name(); + nfUint32 nNameLength = (nfUint32)sUTF8Name.length(); + + ZIPCENTRALDIRECTORYFILEHEADER DirectoryHeader; + DirectoryHeader.m_nSignature = ZIPFILECENTRALHEADERSIGNATURE; + DirectoryHeader.m_nVersionMade = m_nVersionMade; + DirectoryHeader.m_nVersionNeeded = m_nVersionNeeded; + DirectoryHeader.m_nGeneralPurposeFlags = 0; + DirectoryHeader.m_nCompressionMethod = ZIPFILECOMPRESSION_DEFLATED; + DirectoryHeader.m_nLastModTime = pEntry->getLastModTime(); + DirectoryHeader.m_nLastModDate = pEntry->getLastModDate(); + DirectoryHeader.m_nCRC32 = pEntry->getCRC32(); + DirectoryHeader.m_nCompressedSize = 0; + DirectoryHeader.m_nUnCompressedSize = 0; + DirectoryHeader.m_nFileNameLength = nNameLength; + DirectoryHeader.m_nExtraFieldLength = 0; + DirectoryHeader.m_nFileCommentLength = 0; + DirectoryHeader.m_nDiskNumberStart = 0; + DirectoryHeader.m_nInternalFileAttributes = 0; + DirectoryHeader.m_nExternalFileAttributes = ZIPFILEEXTERNALFILEATTRIBUTES; + DirectoryHeader.m_nRelativeOffsetOfLocalHeader = (nfUint32) pEntry->getFilePosition(); + + nfUint64 nRelativeOffsetOfLocalHeader = pEntry->getFilePosition(); + if (m_bWriteZIP64) { + DirectoryHeader.m_nCompressedSize = 0xFFFFFFFF; + DirectoryHeader.m_nUnCompressedSize = 0xFFFFFFFF; + DirectoryHeader.m_nExtraFieldLength += sizeof(ZIP64EXTRAINFORMATIONFIELD) + sizeof(nRelativeOffsetOfLocalHeader); + DirectoryHeader.m_nRelativeOffsetOfLocalHeader = 0xFFFFFFFF; + } + else { + if ((m_pCurrentEntry->getCompressedSize() > ZIPFILEMAXIMUMSIZENON64) || + (m_pCurrentEntry->getUncompressedSize() > ZIPFILEMAXIMUMSIZENON64)) + throw CNMRException(NMR_ERROR_ZIPENTRYNON64_TOOLARGE); + DirectoryHeader.m_nCompressedSize = (nfUint32)pEntry->getCompressedSize(); + DirectoryHeader.m_nUnCompressedSize = (nfUint32)pEntry->getUncompressedSize(); + } + + // prepare byte-buffer for big-endian machines + if (isBigEndian()) { + DirectoryHeader.swapByteOrder(); + } + m_pExportStream->writeBuffer(&DirectoryHeader, (nfUint64) sizeof(DirectoryHeader)); + m_pExportStream->writeBuffer(sUTF8Name.c_str(), nNameLength); + + if (m_bWriteZIP64) { + ZIP64EXTRAINFORMATIONFIELD zip64ExtraInformation; + zip64ExtraInformation.m_nTag = ZIPFILEDATAZIP64EXTENDEDINFORMATIONEXTRAFIELD; + zip64ExtraInformation.m_nFieldSize = sizeof(ZIP64EXTRAINFORMATIONFIELD) - 4 + sizeof(nRelativeOffsetOfLocalHeader); + zip64ExtraInformation.m_nCompressedSize = pEntry->getCompressedSize(); + zip64ExtraInformation.m_nUncompressedSize = pEntry->getUncompressedSize(); + + // prepare byte-buffer for big-endian machines + if (isBigEndian()) { + zip64ExtraInformation.swapByteOrder(); + nRelativeOffsetOfLocalHeader = swapBytes(nRelativeOffsetOfLocalHeader); + } + m_pExportStream->writeBuffer(&zip64ExtraInformation, sizeof(zip64ExtraInformation)); + m_pExportStream->writeBuffer(&nRelativeOffsetOfLocalHeader, sizeof(nRelativeOffsetOfLocalHeader)); + } + + iIterator++; + } + + nfUint64 nEndOfCentralDir64StartPos = m_pExportStream->getPosition(); + + // [ZIP64 end of central directory record] + ZIP64ENDOFCENTRALDIRHEADER EndHeader64; + EndHeader64.m_nSignature = ZIP64FILEENDOFCENTRALDIRRECORDSIGNATURE; + EndHeader64.m_nEndOfCentralDirHeaderRecord = (nfUint64)(sizeof(ZIP64ENDOFCENTRALDIRHEADER) - 12); + EndHeader64.m_nVersionMade = m_nVersionMade; + EndHeader64.m_nVersionNeeded = m_nVersionNeeded; + EndHeader64.m_nNumberOfDisk = 0; + EndHeader64.m_nNumberOfDiskOfCentralDirectory = 0; + EndHeader64.m_nTotalNumberOfEntriesOnThisDisk = m_Entries.size(); + EndHeader64.m_nTotalNumberOfEntriesInCentralDirectory = m_Entries.size(); + EndHeader64.m_nSizeOfCentralDirectory = (nfUint64)(m_pExportStream->getPosition() - nCentralDirStartPos); + EndHeader64.m_nOffsetOfCentralDirectoryWithRespectToDisk = nCentralDirStartPos; + + // [ZIP64 end of central directory locator] + ZIP64ENDOFCENTRALDIRLOCATOR EndLocator64; + EndLocator64.m_nSignature = ZIP64FILEENDOFCENTRALDIRLOCATORSIGNATURE; + EndLocator64.m_nNumberOfDiskWithStartOfZIP64EOCentralDir = 0; + EndLocator64.m_nTotalNumberOfDisk = 1; + EndLocator64.m_nRelativeOffset = nEndOfCentralDir64StartPos; + + ZIPENDOFCENTRALDIRHEADER EndHeader; + EndHeader.m_nSignature = ZIPFILEENDOFCENTRALDIRSIGNATURE; + EndHeader.m_nNumberOfDisk = 0; + EndHeader.m_nRelativeNumberOfDisk = 0; + EndHeader.m_nNumberOfEntriesOfDisk = (nfUint16) m_Entries.size(); + EndHeader.m_nNumberOfEntriesOfDirectory = (nfUint16)m_Entries.size(); + EndHeader.m_nSizeOfCentralDirectory = (nfUint32)(m_pExportStream->getPosition() - nCentralDirStartPos); + EndHeader.m_nOffsetOfCentralDirectory = (nfUint32)nCentralDirStartPos; + EndHeader.m_nCommentLength = 0; + + if (m_bWriteZIP64) { + EndHeader.m_nOffsetOfCentralDirectory = 0xFFFFFFFF; + // prepare byte-buffer for big-endian machines + if (isBigEndian()) { + EndHeader64.swapByteOrder(); + EndLocator64.swapByteOrder(); + } + m_pExportStream->writeBuffer(&EndHeader64, sizeof(EndHeader64)); + m_pExportStream->writeBuffer(&EndLocator64, sizeof(EndLocator64)); + } + // prepare byte-buffer for big-endian machines + if (isBigEndian()) { + EndHeader.swapByteOrder(); + } + m_pExportStream->writeBuffer(&EndHeader, (nfUint64) sizeof(EndHeader)); + + m_bIsFinished = true; + } + + +} diff --git a/Source/Common/Platform/NMR_PortableZIPWriterEntry.cpp b/Source/Common/Platform/NMR_PortableZIPWriterEntry.cpp new file mode 100644 index 0000000..3e07fc8 --- /dev/null +++ b/Source/Common/Platform/NMR_PortableZIPWriterEntry.cpp @@ -0,0 +1,114 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_PortableZIPWriterEntry.cpp implements a portable and fast writer of ZIP files + +--*/ + +#include "Common/Platform/NMR_PortableZIPWriterEntry.h" +#include "Common/Platform/NMR_ExportStream_ZIP.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_StringUtils.h" +#include "Libraries/zlib/zlib.h" + +namespace NMR { + + CPortableZIPWriterEntry::CPortableZIPWriterEntry(_In_ const std::string sUTF8Name, _In_ nfUint16 nLastModTime, _In_ nfUint16 nLastModDate, _In_ nfUint64 nFilePosition, _In_ nfUint64 nExtInfoPosition, _In_ nfUint64 nDataPosition) + { + m_sUTF8Name = sUTF8Name; + m_nCRC32 = 0; + m_nCompressedSize = 0; + m_nUncompressedSize = 0; + m_nLastModTime = nLastModTime; + m_nLastModDate = nLastModDate; + m_nFilePosition = nFilePosition; + m_nExtInfoPosition = nExtInfoPosition; + m_nDataPosition = nDataPosition; + } + + std::string CPortableZIPWriterEntry::getUTF8Name() + { + return m_sUTF8Name; + } + + nfUint32 CPortableZIPWriterEntry::getCRC32() + { + return m_nCRC32; + } + + nfUint64 CPortableZIPWriterEntry::getCompressedSize() + { + return m_nCompressedSize; + } + + nfUint64 CPortableZIPWriterEntry::getUncompressedSize() + { + return m_nUncompressedSize; + } + + nfUint16 CPortableZIPWriterEntry::getLastModTime() + { + return m_nLastModTime; + } + + nfUint16 CPortableZIPWriterEntry::getLastModDate() + { + return m_nLastModDate; + } + + nfUint64 CPortableZIPWriterEntry::getFilePosition() + { + return m_nFilePosition; + } + + nfUint64 CPortableZIPWriterEntry::getExtInfoPosition() + { + return m_nExtInfoPosition; + } + + nfUint64 CPortableZIPWriterEntry::getDataPosition() + { + return m_nDataPosition; + } + + void CPortableZIPWriterEntry::increaseCompressedSize(_In_ nfUint32 nCompressedSize) + { + m_nCompressedSize += nCompressedSize; + } + + void CPortableZIPWriterEntry::increaseUncompressedSize(_In_ nfUint32 nUncompressedSize) + { + m_nUncompressedSize += nUncompressedSize; + } + + void CPortableZIPWriterEntry::calculateChecksum(_In_ const void * pBuffer, _In_ nfUint32 cbCount) + { + m_nCRC32 = crc32(m_nCRC32, (Bytef*) pBuffer, cbCount); + } + +} diff --git a/Source/Common/Platform/NMR_Time.cpp b/Source/Common/Platform/NMR_Time.cpp new file mode 100644 index 0000000..2a815cf --- /dev/null +++ b/Source/Common/Platform/NMR_Time.cpp @@ -0,0 +1,51 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_Time.cpp implements platform dependent time functions + +--*/ + +#include "Common/Platform/NMR_Time.h" +#include "Common/NMR_Exception.h" + +#ifdef _WIN32 +#include +#endif // _WIN32 + +namespace NMR { + + nfTimeStamp fnGetUnixTime() + { + #if defined(_WIN32) && !defined(__MINGW32__) + return _time64(nullptr); + #else + return time(nullptr); + #endif + } + +} diff --git a/Source/Common/Platform/NMR_XmlReader.cpp b/Source/Common/Platform/NMR_XmlReader.cpp new file mode 100644 index 0000000..33aa706 --- /dev/null +++ b/Source/Common/Platform/NMR_XmlReader.cpp @@ -0,0 +1,49 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_XMLReader.cpp implements a XML reader class in a portable way. + +--*/ + +#include "Common/Platform/NMR_XmlReader.h" +#include "Common/NMR_Exception.h" + +namespace NMR { + + CXmlReader::CXmlReader(_In_ PImportStream pImportStream) + { + if (!pImportStream.get()) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + m_pImportStream = pImportStream; + } + + void CXmlReader::CloseElement() + { + } + +} diff --git a/Source/Common/Platform/NMR_XmlReader_Native.cpp b/Source/Common/Platform/NMR_XmlReader_Native.cpp new file mode 100644 index 0000000..c80a52f --- /dev/null +++ b/Source/Common/Platform/NMR_XmlReader_Native.cpp @@ -0,0 +1,970 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_XMLReader_Native.cpp implements a XML reader class with a native XML parsing implementation. + +--*/ + +#include "Common/Platform/NMR_XmlReader_Native.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_StringUtils.h" + +#include "Common/3MF_ProgressMonitor.h" + +#include + +namespace NMR { + + inline void decodeXMLEscapeXMLStrings(nfChar* pChar) { + if (strpbrk(pChar, "&") == nullptr) { + return; + } + nfChar *pIterChar = pChar; + nfChar *pWriteChar = pChar; + + nfChar *pAmp = nullptr; + nfChar *pColon = nullptr; + while (*pIterChar != 0) { + if (*pIterChar == '&') { + pAmp = pIterChar; + pColon = nullptr; + } + else if (pAmp == nullptr) { + *pWriteChar = *pIterChar; + pWriteChar++; + } + else if (*pIterChar == ';') { + if (pAmp != nullptr) { + pColon = pIterChar; + long long compareLen = pColon - pAmp + 1; + if (strncmp(pAmp, """, static_cast(std::min((long long)(6), compareLen))) == 0) { + *pWriteChar = '\"'; + pWriteChar++; + } + else if (strncmp(pAmp, "'", static_cast(std::min((long long)(6), compareLen))) == 0) { + *pWriteChar = '\''; + pWriteChar++; + } + else if (strncmp(pAmp, "<", static_cast(std::min((long long)(4), compareLen))) == 0) { + *pWriteChar = '<'; + pWriteChar++; + } + else if (strncmp(pAmp, ">", static_cast(std::min((long long)(4), compareLen))) == 0) { + *pWriteChar = '>'; + pWriteChar++; + } + else if (strncmp(pAmp, "&", static_cast(std::min((long long)(5), compareLen))) == 0) { + *pWriteChar = '&'; + pWriteChar++; + } + else { + throw CNMRException(NMR_ERROR_XMLPARSER_INVALID_ESCAPESTRING); + } + pAmp = nullptr; + } + } + pIterChar++; + }; + if (pAmp != nullptr) + throw CNMRException(NMR_ERROR_XMLPARSER_INVALID_ESCAPESTRING); + *pWriteChar = 0; + } + + nfUint32 nfStrLen(_In_ const nfChar * pszString) + { + nfUint32 nResult = 0; + const nfChar * pChar = pszString; + while (*pChar) { + pChar++; + nResult++; + if (nResult > NMR_MAXXMLSTRINGLENGTH) + throw CNMRException(NMR_ERROR_INVALIDBUFFERSIZE); + } + return nResult; + } + + CXmlReader_Native::CXmlReader_Native(_In_ PImportStream pImportStream, _In_ nfUint32 cbBufferCapacity, _In_ PProgressMonitor pProgressMonitor) + : CXmlReader(pImportStream), m_progressCounter(0), m_pProgressMonitor(pProgressMonitor) + { + if ((cbBufferCapacity < NMR_NATIVEXMLREADER_MINBUFFERCAPACITY) || + (cbBufferCapacity > NMR_NATIVEXMLREADER_MAXBUFFERCAPACITY)) + throw CNMRException(NMR_ERROR_INVALIDBUFFERSIZE); + + if (!pProgressMonitor) { + throw CNMRException(NMR_ERROR_INVALIDPARAM); + } + + m_cbBufferCapacity = cbBufferCapacity; + m_UTF8Buffer1.resize(cbBufferCapacity); + m_UTF8Buffer2.resize(cbBufferCapacity); + m_CurrentEntityList.resize(cbBufferCapacity); + m_CurrentEntityTypes.resize(cbBufferCapacity); + m_CurrentEntityPrefixes.resize(cbBufferCapacity); + m_ZeroInsertArray.resize(cbBufferCapacity); + + m_pNextBuffer = &m_UTF8Buffer1; + m_pCurrentBuffer = &m_UTF8Buffer2; + + m_nCurrentBufferSize = 0; + m_cbCurrentOverflowSize = 0; + m_nCurrentEntityIndex = 0; + m_nCurrentFullEntityCount = 0; + m_nCurrentEntityCount = 0; + m_nCurrentVerifiedEntityCount = 0; + m_cNullString = 0; + + // Initialise Status Values + m_pCurrentName = &m_cNullString; + m_pCurrentPrefix = &m_cNullString; + m_pCurrentValue = &m_cNullString; + m_pCurrentElementName = &m_cNullString; + m_pCurrentElementPrefix = &m_cNullString; + + m_cbDefaultNameSpaceLength = 0; + m_bNameSpaceIsAttribute = false; + + m_nZeroInsertIndex = 0; + + m_bIsEOF = false; + + registerNameSpace(NMR_NATIVEXMLNS_XML_PREFIX, NMR_NATIVEXMLNS_XML_URI); + registerNameSpace(NMR_NATIVEXMLNS_XMLNS_PREFIX, NMR_NATIVEXMLNS_XMLNS_URI); + + } + + CXmlReader_Native::~CXmlReader_Native() + { + + } + + void CXmlReader_Native::GetValue(_Outptr_result_buffer_maybenull_(*pcchValue + 1) const nfChar ** ppszValue, _Out_opt_ nfUint32 *pcchValue) + { + if (ppszValue == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + *ppszValue = m_pCurrentValue; + + if (pcchValue != nullptr) + *pcchValue = nfStrLen(m_pCurrentValue); + + } + + void CXmlReader_Native::GetLocalName(_Outptr_result_buffer_maybenull_(*pcchLocalName + 1) const nfChar ** ppszLocalName, _Out_opt_ nfUint32 *pcchLocalName) + { + if (ppszLocalName == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + *ppszLocalName = m_pCurrentName; + if (pcchLocalName != nullptr) + *pcchLocalName = nfStrLen(m_pCurrentName); + + } + + void CXmlReader_Native::GetNamespaceURI(_Outptr_result_buffer_maybenull_(*pcchValue + 1) const nfChar ** ppszValue, _Out_opt_ nfUint32 *pcchValue) + { + if (ppszValue == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + nfUint32 cbLength = 0; + if (*m_pCurrentPrefix == 0) { + if (m_bNameSpaceIsAttribute) { + cbLength = 0; + *ppszValue = &m_cNullString; + } + else { + cbLength = m_cbDefaultNameSpaceLength; + *ppszValue = m_sDefaultNameSpace.c_str(); + } + } + else { + auto iIterator = m_sNameSpaces.find(m_pCurrentPrefix); + if (iIterator != m_sNameSpaces.end()) { + cbLength = (nfUint32)iIterator->second.length(); + *ppszValue = iIterator->second.c_str(); + } + else { + cbLength = 0; + *ppszValue = nullptr; + } + } + + if (pcchValue != nullptr) + *pcchValue = cbLength; + + } + + bool CXmlReader_Native::GetNamespaceURI(const std::string &sNameSpacePrefix, std::string &sNameSpaceURI) + { + auto iIterator = m_sNameSpaces.find(sNameSpacePrefix); + if (iIterator != m_sNameSpaces.end()) { + sNameSpaceURI = iIterator->second.c_str(); + return true; + } + else { + return false; + } + } + + bool CXmlReader_Native::NamespaceRegistered(const std::string &sNameSpaceURI) + { + for (auto it : m_sNameSpaces) { + if (it.second == sNameSpaceURI) { + return true; + } + } + return false; + } + + nfBool CXmlReader_Native::ensureFilledBuffer() + { + if (m_nCurrentEntityIndex >= m_nCurrentFullEntityCount) { + readNextBufferFromStream(); + __NMRASSERT(m_nCurrentEntityIndex == 0); + if (m_nCurrentFullEntityCount == 0) { + m_bIsEOF = true; + return false; + } + } + return true; + } + + nfBool CXmlReader_Native::Read(_Out_ eXmlReaderNodeType & NodeType) + { + if (!ensureFilledBuffer()) { + // Here we reached eof! + NodeType = XMLREADERNODETYPE_UNKNOWN; + return false; + } + + __NMRASSERT(m_nCurrentEntityIndex < m_nCurrentFullEntityCount); + nfByte nType = m_CurrentEntityTypes[m_nCurrentEntityIndex]; + switch (nType) { + case NMR_NATIVEXMLTYPE_TEXT: + NodeType = XMLREADERNODETYPE_TEXT; + m_pCurrentValue = m_CurrentEntityList[m_nCurrentEntityIndex]; + decodeXMLEscapeXMLStrings(m_pCurrentValue); + m_pCurrentPrefix = &m_cNullString; + m_pCurrentName = &m_cNullString; + m_bNameSpaceIsAttribute = false; + break; + case NMR_NATIVEXMLTYPE_ELEMENT: + NodeType = XMLREADERNODETYPE_STARTELEMENT; + m_pCurrentValue = &m_cNullString; + m_pCurrentPrefix = m_CurrentEntityPrefixes[m_nCurrentEntityIndex]; + m_pCurrentName = m_CurrentEntityList[m_nCurrentEntityIndex]; + m_pCurrentElementName = m_pCurrentName; + m_pCurrentElementPrefix = m_pCurrentPrefix; + m_bNameSpaceIsAttribute = false; + break; + case NMR_NATIVEXMLTYPE_ELEMENTEND: + NodeType = XMLREADERNODETYPE_ENDELEMENT; + m_pCurrentValue = &m_cNullString; + m_pCurrentPrefix = m_CurrentEntityPrefixes[m_nCurrentEntityIndex]; + m_pCurrentName = m_CurrentEntityList[m_nCurrentEntityIndex]; + m_pCurrentElementName = m_pCurrentName; + m_pCurrentElementPrefix = m_pCurrentPrefix; + m_bNameSpaceIsAttribute = false; + break; + case NMR_NATIVEXMLTYPE_CLOSEELEMENT: + NodeType = XMLREADERNODETYPE_ENDELEMENT; + m_pCurrentValue = &m_cNullString; + m_pCurrentPrefix = m_pCurrentElementPrefix; + m_pCurrentName = m_pCurrentElementName; + m_pCurrentElementName = &m_cNullString; + m_pCurrentElementPrefix = &m_cNullString; + break; + + + case NMR_NATIVEXMLTYPE_PROCESSINGINSTRUCTION: + NodeType = XMLREADERNODETYPE_STARTELEMENT; + m_pCurrentValue = &m_cNullString; + m_pCurrentPrefix = m_CurrentEntityPrefixes[m_nCurrentEntityIndex]; + m_pCurrentName = m_CurrentEntityList[m_nCurrentEntityIndex]; + m_pCurrentElementName = m_pCurrentName; + m_pCurrentElementPrefix = m_pCurrentPrefix; + m_bNameSpaceIsAttribute = false; + break; + + case NMR_NATIVEXMLTYPE_PROCESSINGINSTRUCTIONEND: + NodeType = XMLREADERNODETYPE_ENDELEMENT; + m_pCurrentValue = &m_cNullString; + m_pCurrentPrefix = m_CurrentEntityPrefixes[m_nCurrentEntityIndex]; + m_pCurrentName = m_CurrentEntityList[m_nCurrentEntityIndex]; + m_pCurrentElementName = m_pCurrentName; + m_pCurrentElementPrefix = m_pCurrentPrefix; + m_bNameSpaceIsAttribute = false; + break; + + default: + NodeType = XMLREADERNODETYPE_UNKNOWN; + } + + m_nCurrentEntityIndex++; + + return true; + } + + nfBool CXmlReader_Native::IsEOF() + { + return m_bIsEOF; + } + + nfBool CXmlReader_Native::IsEmptyElement() + { + return false; + } + + nfBool CXmlReader_Native::MoveToFirstAttribute() + { + return MoveToNextAttribute(); + } + + nfBool CXmlReader_Native::MoveToNextAttribute() + { + if (!ensureFilledBuffer()) + return false; + + m_bNameSpaceIsAttribute = true; + + __NMRASSERT(m_nCurrentEntityIndex < m_nCurrentFullEntityCount); + nfByte nNameType = m_CurrentEntityTypes[m_nCurrentEntityIndex]; + + if (nNameType == NMR_NATIVEXMLTYPE_ATTRIBNAME) { + // Read Attribute Name + m_pCurrentPrefix = m_CurrentEntityPrefixes[m_nCurrentEntityIndex]; + m_pCurrentName = m_CurrentEntityList[m_nCurrentEntityIndex]; + m_nCurrentEntityIndex++; + + if (!ensureFilledBuffer()) + return false; + + // Read Attribute Value + __NMRASSERT(m_nCurrentEntityIndex < m_nCurrentFullEntityCount); + nfByte nValueType = m_CurrentEntityTypes[m_nCurrentEntityIndex]; + if (nValueType != NMR_NATIVEXMLTYPE_ATTRIBVALUE) + throw CNMRException(NMR_ERROR_XMLPARSER_INVALIDATTRIBVALUE); + + m_pCurrentValue = m_CurrentEntityList[m_nCurrentEntityIndex]; + m_nCurrentEntityIndex++; + + // register Namespaces + if ((*m_pCurrentPrefix == 0) && (strcmp(m_pCurrentName, NMR_NATIVEXMLNS_XMLNS_PREFIX) == 0)) { + m_sDefaultNameSpace = m_pCurrentValue; + m_cbDefaultNameSpaceLength = (nfUint32)m_sDefaultNameSpace.length(); + } + if (strcmp(m_pCurrentPrefix, NMR_NATIVEXMLNS_XMLNS_PREFIX) == 0) + registerNameSpace(m_pCurrentName, m_pCurrentValue); + + return true; + } + + return false; + } + + nfBool CXmlReader_Native::IsDefault() + { + return false; + } + + void CXmlReader_Native::CloseElement() + { + // Empty by purpose + } + + void CXmlReader_Native::readNextBufferFromStream() + { + if (m_progressCounter++ > PROGRESS_READBUFFERUPDATE) { + m_pProgressMonitor->QueryCancelled(true); + m_progressCounter = 0; + } + + nfUint64 cbBytesRead; + nfUint32 j; + + clearZeroInserts(); + + // Read buffer (minus safety margin for overread/overwrite) + nfUint32 cbReadSize = m_cbBufferCapacity - NMR_NATIVEXMLREADER_BUFFERMARGIN; + if (cbReadSize < m_cbCurrentOverflowSize) + throw CNMRException(NMR_ERROR_INVALIDBUFFERSIZE); + if (m_nCurrentBufferSize < m_cbCurrentOverflowSize) + throw CNMRException(NMR_ERROR_INVALIDBUFFERSIZE); + + // Copy over unfinished elements of current buffer into new buffer + if (m_cbCurrentOverflowSize > 0) { + nfUint32 nDeltaIndex = m_nCurrentBufferSize - m_cbCurrentOverflowSize; + nfChar * pSrc = &(*m_pCurrentBuffer)[nDeltaIndex]; + nfChar * pDst = &(*m_pNextBuffer)[0]; + for (j = 0; j < m_cbCurrentOverflowSize; j++) + pDst[j] = pSrc[j]; + + m_nCurrentBufferSize = m_cbCurrentOverflowSize; + cbReadSize -= m_cbCurrentOverflowSize; + m_cbCurrentOverflowSize = 0; + } + else { + m_nCurrentBufferSize = 0; + m_cbCurrentOverflowSize = 0; + } + + // Read buffer into memory + cbBytesRead = m_pImportStream->readIntoBuffer((nfByte*)(&((*m_pNextBuffer)[m_nCurrentBufferSize])), cbReadSize, false); + m_nCurrentBufferSize += (nfUint32)cbBytesRead; + + // Update Progress + m_pProgressMonitor->IncrementProgress(double(cbBytesRead)); + + // Reset Entity parser + m_nCurrentEntityCount = 0; + m_nCurrentVerifiedEntityCount = 0; + m_nCurrentFullEntityCount = 0; + m_nCurrentEntityIndex = 0; + + // Swap Buffers + std::vector * pDummy = m_pCurrentBuffer; + m_pCurrentBuffer = m_pNextBuffer; + m_pNextBuffer = pDummy; + + // parse Content + m_pCurrentEntityPointer = nullptr; + parseUnknown(&(*m_pCurrentBuffer)[0], &(*m_pCurrentBuffer)[m_nCurrentBufferSize]); + + if (m_pCurrentEntityPointer != nullptr) { + + // Calculate Overflow buffer + nfUint64 nEndPtr = (nfUint64)m_pCurrentEntityPointer; + nfUint64 nStartPtr = (nfUint64)&(*m_pCurrentBuffer)[0]; + + if (nStartPtr > nEndPtr) + throw CNMRException(NMR_ERROR_XMLPARSER_INVALIDPARSERESULT); + + nfUint64 nUsedChars = ((nEndPtr - nStartPtr) / sizeof (nfChar)); + if (nUsedChars > (nfUint64)m_nCurrentBufferSize) + throw CNMRException(NMR_ERROR_XMLPARSER_TOOMANYUSEDCHARS); + + m_cbCurrentOverflowSize = m_nCurrentBufferSize - ((nfUint32)nUsedChars); + } + else { + m_cbCurrentOverflowSize = 0; + } + } + + void CXmlReader_Native::pushEntity(_In_ nfChar * pszEntityStartChar, _In_ nfChar * pszEntityEndDelimiter, _In_ nfChar * pszNextEntityChar, _In_ nfByte nType, _In_ nfBool bParseForNamespaces, _In_ nfBool bEntityIsFinished) + { + if (bParseForNamespaces) { + nfChar * pChar = pszEntityStartChar; + nfChar * pColon = nullptr; + while (pChar != pszEntityEndDelimiter) { + if (*pChar == 0) + throw CNMRException(NMR_ERROR_XMLPARSER_INVALIDENDDELIMITER); + + if (*pChar == L':') { + if (pColon != nullptr) + throw CNMRException(NMR_ERROR_XMLPARSER_INVALIDNAMESPACEPREFIX); + + pColon = pChar; + } + + pChar++; + } + + if (pColon != nullptr) { + pushZeroInsert (pColon); + pColon++; + + m_CurrentEntityList[m_nCurrentEntityCount] = pColon; + m_CurrentEntityPrefixes[m_nCurrentEntityCount] = pszEntityStartChar; + } + else { + m_CurrentEntityList[m_nCurrentEntityCount] = pszEntityStartChar; + m_CurrentEntityPrefixes[m_nCurrentEntityCount] = &m_cNullString; + } + + } + else { + m_CurrentEntityList[m_nCurrentEntityCount] = pszEntityStartChar; + m_CurrentEntityPrefixes[m_nCurrentEntityCount] = &m_cNullString; + } + + m_CurrentEntityTypes[m_nCurrentEntityCount] = nType; + m_nCurrentEntityCount++; + + if (bEntityIsFinished) { + // We have closed a full entity + m_pCurrentEntityPointer = pszNextEntityChar; + m_nCurrentFullEntityCount = m_nCurrentEntityCount; + + // Insert all zeros of the entity, as we do not need to rollback. + performZeroInserts(); + + performEscapeStringDecoding(); + } + } + + + nfChar * CXmlReader_Native::parseUnknown(_In_ nfChar * pszStart, _In_ nfChar * pszEnd) + { + nfChar * pChar = pszStart; + while (pChar != pszEnd) { + nfChar * pLastChar = pChar; + pChar = parseText(pChar, pszEnd); + + if (pChar == pLastChar) + throw CNMRException(NMR_ERROR_XMLPARSER_COULDNOTPARSEENTITY); + } + + return pChar; + } + + nfChar * CXmlReader_Native::parseText(_In_ nfChar * pszStart, _In_ nfChar * pszEnd) + { + nfChar * pChar = pszStart; + while (pChar != pszEnd) { + switch (*pChar) { + case '<': + if (pChar+1 != pszEnd && *(pChar+1) == '!' && + pChar+2 != pszEnd && *(pChar+2) == '-' && + pChar+3 != pszEnd && *(pChar+3) == '-'){ + pChar += 4; + return parseComment(pChar, pszEnd); + } else { + if (pChar != pszStart) + pushEntity(pszStart, pChar, pChar, NMR_NATIVEXMLTYPE_TEXT, false, true); + pushZeroInsert(pChar); + pChar++; + + return parseElement(pChar, pszEnd); + } + default: + pChar++; + } + + } + + return pChar; + } + + + nfChar * CXmlReader_Native::parseElement(_In_ nfChar * pszStart, _In_ nfChar * pszEnd) + { + nfChar * pChar = pszStart; + while (pChar != pszEnd) { + switch (*pChar) { + case 9: // Tab + case 10: // LF + case 13: // CR + case 32: // Space + if (pszStart == pChar) + throw CNMRException(NMR_ERROR_XMLPARSER_EMPTYELEMENTNAME); + pushEntity(pszStart, pChar, pChar, NMR_NATIVEXMLTYPE_ELEMENT, true, false); + pushZeroInsert(pChar); + pChar++; + + return parseAttributes(pChar, pszEnd); + + case '?': + if (pszStart != pChar) + throw CNMRException(NMR_ERROR_XMLPARSER_INVALIDCHARACTERINELEMENTNAME); + pChar++; + return parseProcessingInstruction(pChar, pszEnd); + + case '>': + pushZeroInsert(pChar); + pushEntity(pszStart, pChar, pChar + 1, NMR_NATIVEXMLTYPE_ELEMENT, true, true); + pChar++; + return pChar; + + case '/': + if (pszStart == pChar) { + pChar++; + return parseEndElement(pChar, pszEnd); + } + else { + pushEntity(pszStart, pChar, pChar + 1, NMR_NATIVEXMLTYPE_ELEMENT, true, false); + pushZeroInsert(pChar); + pChar++; + + return parseCloseElement(pChar, pszEnd); + } + + default: + pChar++; + } + + } + + return pChar; + + } + + nfChar * CXmlReader_Native::parseComment(_In_ nfChar * pszStart, _In_ nfChar * pszEnd) + { + nfChar * pChar = pszStart; + static nfChar commentEnd [3] = {'-', '-', '>'}; + nfInt32 endPosition = 0; + while (pChar != pszEnd) { + if (*pChar == commentEnd[endPosition]){ + if (endPosition == 2) + return pChar; + endPosition++; + } else { + if (*pChar != '-') + endPosition = 0; + } + pChar++; + } + return pChar; + } + + nfChar * CXmlReader_Native::parseProcessingInstruction(_In_ nfChar * pszStart, _In_ nfChar * pszEnd) + { + nfChar * pChar = pszStart; + while (pChar != pszEnd) { + switch (*pChar) { + case 9: + case 10: + case 13: + case 32: + if (pszStart == pChar) + throw CNMRException(NMR_ERROR_XMLPARSER_EMPTYINSTRUCTIONNAME); + pushEntity(pszStart, pChar, pChar, NMR_NATIVEXMLTYPE_PROCESSINGINSTRUCTION, true, false); + pushZeroInsert(pChar); + pChar++; + + return parseAttributes(pChar, pszEnd); + + break; + + case '/': + throw CNMRException(NMR_ERROR_XMLPARSER_INVALIDINSTRUCTIONNAME); + + case '?': + if (pszStart == pChar) + throw CNMRException(NMR_ERROR_XMLPARSER_EMPTYINSTRUCTIONNAME); + pushEntity(pszStart, pChar, pChar, NMR_NATIVEXMLTYPE_PROCESSINGINSTRUCTION, true, false); + pushZeroInsert(pChar); + pChar++; + + return parseCloseProcessingInstruction(pChar, pszEnd); + + default: + pChar++; + } + + } + + return pChar; + + } + + nfChar * CXmlReader_Native::parseCloseProcessingInstruction(_In_ nfChar * pszStart, _In_ nfChar * pszEnd) + { + if (pszStart != pszEnd) { + if (*pszStart != '>') + throw CNMRException(NMR_ERROR_XMLPARSER_COULDNOTCLOSEINSTRUCTION); + + pushZeroInsert(pszStart); + pushEntity(pszStart, pszStart, pszStart + 1, NMR_NATIVEXMLTYPE_PROCESSINGINSTRUCTIONEND, false, true); + + pszStart++; + return pszStart; + } + + return pszStart; + } + + + nfChar * CXmlReader_Native::parseEndElement(_In_ nfChar * pszStart, _In_ nfChar * pszEnd) + { + nfChar * pChar = pszStart; + while (pChar != pszEnd) { + switch (*pChar) { + case 9: + case 10: + case 13: + case 32: + pChar++; + break; + + case '/': + case '?': + throw CNMRException(NMR_ERROR_XMLPARSER_COULDNOTENDELEMENT); + + case '>': + if (pszStart == pChar) + throw CNMRException(NMR_ERROR_XMLPARSER_EMPTYENDELEMENT); + pushZeroInsert(pChar); + pushEntity(pszStart, pChar, pChar + 1, NMR_NATIVEXMLTYPE_ELEMENTEND, true, true); + pChar++; + + return pChar; + + default: + pChar++; + } + + } + + return pChar; + + } + + nfChar * CXmlReader_Native::parseCloseElement(_In_ nfChar * pszStart, _In_ nfChar * pszEnd) + { + if (pszStart != pszEnd) { + if (*pszStart != '>') + throw CNMRException(NMR_ERROR_XMLPARSER_COULDNOTCLOSEELEMENT); + + pushZeroInsert (pszStart); + pushEntity(pszStart, pszStart, pszStart + 1, NMR_NATIVEXMLTYPE_CLOSEELEMENT, false, true); + + pszStart++; + return pszStart; + } + + return pszStart; + } + + nfChar * CXmlReader_Native::parseAttributes(_In_ nfChar * pszStart, _In_ nfChar * pszEnd) + { + nfChar * pChar = pszStart; + while (pChar != pszEnd) { + switch (*pChar) { + case 9: + case 10: + case 13: + case 32: + pChar = skipSpaces(++pChar, pszEnd); + break; + + case '>': + pChar++; + return pChar; + + case '/': + pChar++; + return parseCloseElement(pChar, pszEnd); + + case '?': + pChar++; + return parseCloseProcessingInstruction(pChar, pszEnd); + + default: + pChar = parseAttributeName(pChar, pszEnd); + pChar = parseAttributeValue(pChar, pszEnd); + } + + } + + return pChar; + } + + + nfChar * CXmlReader_Native::skipSpaces(_In_ nfChar * pszStart, _In_ nfChar * pszEnd) + { + nfChar * pChar = pszStart; + while (pChar != pszEnd) { + switch (*pChar) { + case 9: + case 10: + case 13: + case 32: + pChar++; + + default: + return pChar; + + } + } + + + return pChar; + } + + nfChar * CXmlReader_Native::parseAttributeName(_In_ nfChar * pszStart, _In_ nfChar * pszEnd) + { + nfBool bHadSpacing = false; + nfChar * pChar = skipSpaces(pszStart, pszEnd); + while (pChar != pszEnd) { + switch (*pChar) { + // name-ending characters + case 9: + case 10: + case 13: + case 32: + // push the entity at one of the n name-ending characters + // but continue to run through the string unti L'=' is reached + // if another name-constituting character appears, throw exception + bHadSpacing = true; + pushEntity(pszStart, pChar, pChar + 1, NMR_NATIVEXMLTYPE_ATTRIBNAME, true, false); + pushZeroInsert(pChar); + pChar++; + break; + + case 34: + case 39: + throw CNMRException(NMR_ERROR_XMLPARSER_INVALIDATTRIBUTENAME); + + case '=': + if (!bHadSpacing) { + pushEntity(pszStart, pChar, pChar + 1, NMR_NATIVEXMLTYPE_ATTRIBNAME, true, false); + pushZeroInsert(pChar); + pChar++; + } + return pChar; + + // name-constituting characters + default: + if (bHadSpacing) + throw CNMRException(NMR_ERROR_XMLPARSER_SPACEINATTRIBUTENAME); + pChar++; + } + } + + + return pChar; + } + + nfChar * CXmlReader_Native::parseAttributeValue(_In_ nfChar * pszStart, _In_ nfChar * pszEnd) + { + nfBool bHadSpacing = false; + nfChar * pChar = skipSpaces(pszStart, pszEnd); + while (pChar != pszEnd) { + switch (*pChar) { + case 9: + case 10: + case 13: + case 32: + bHadSpacing = true; + pChar++; + + break; + + case 34: + pChar++; + return parseAttributeValueDoubleQuote(pChar, pszEnd); + + case 39: + pChar++; + return parseAttributeValueSingleQuote(pChar, pszEnd); + + default: + if (bHadSpacing) + throw CNMRException(NMR_ERROR_XMLPARSER_NOQUOTESAROUNDATTRIBUTE); + pChar++; + } + } + + + return pChar; + } + + nfChar * CXmlReader_Native::parseAttributeValueDoubleQuote(_In_ nfChar * pszStart, _In_ nfChar * pszEnd) + { + nfChar * pChar = pszStart; + while (pChar != pszEnd) { + switch (*pChar) { + + case 34: + pushZeroInsert(pChar); + pushEntity(pszStart, pChar, pChar + 1, NMR_NATIVEXMLTYPE_ATTRIBVALUE, false, false); + pChar++; + return pChar; + + default: + pChar++; + } + } + + + return pChar; + } + + nfChar * CXmlReader_Native::parseAttributeValueSingleQuote(_In_ nfChar * pszStart, _In_ nfChar * pszEnd) + { + nfChar * pChar = pszStart; + while (pChar != pszEnd) { + switch (*pChar) { + + case 39: + pushZeroInsert(pChar); + pushEntity(pszStart, pChar, pChar + 1, NMR_NATIVEXMLTYPE_ATTRIBVALUE, false, false); + pChar++; + return pChar; + + default: + pChar++; + } + } + + + return pChar; + } + + + void CXmlReader_Native::registerNameSpace(_In_ std::string sPrefix, _In_ std::string sURI) + { + m_sNameSpaces.insert(std::make_pair(sPrefix, sURI)); + } + + + void CXmlReader_Native::pushZeroInsert(_In_ nfChar * pChar) + { + __NMRASSERT(pChar != nullptr); + m_ZeroInsertArray[m_nZeroInsertIndex] = pChar; + m_nZeroInsertIndex++; + } + + void CXmlReader_Native::performEscapeStringDecoding() + { + for (nfUint32 nIndex = m_nCurrentVerifiedEntityCount; nIndex < m_nCurrentEntityCount-1; nIndex++) { + if (m_CurrentEntityTypes[nIndex] != NMR_NATIVEXMLTYPE_COMMENT) { + decodeXMLEscapeXMLStrings(m_CurrentEntityList[nIndex]); + } + } + m_nCurrentVerifiedEntityCount = m_nCurrentEntityCount; + } + + void CXmlReader_Native::performZeroInserts() + { + nfUint32 nIndex; + for (nIndex = 0; nIndex < m_nZeroInsertIndex; nIndex++) { + nfChar * pChar = m_ZeroInsertArray[nIndex]; + *pChar = 0; + } + + m_nZeroInsertIndex = 0; + } + + void CXmlReader_Native::clearZeroInserts() + { + m_nZeroInsertIndex = 0; + } + + +} diff --git a/Source/Common/Platform/NMR_XmlWriter.cpp b/Source/Common/Platform/NMR_XmlWriter.cpp new file mode 100644 index 0000000..8819a2e --- /dev/null +++ b/Source/Common/Platform/NMR_XmlWriter.cpp @@ -0,0 +1,44 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_XMLWriter.cpp implements a XML writer class in a portable way. + +--*/ + +#include "Common/Platform/NMR_XmlWriter.h" +#include "Common/NMR_Exception.h" + +namespace NMR { + + CXmlWriter::CXmlWriter(_In_ PExportStream pExportStream) + { + if (!pExportStream.get()) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + m_pExportStream = pExportStream; + } +} diff --git a/Source/Common/Platform/NMR_XmlWriter_Native.cpp b/Source/Common/Platform/NMR_XmlWriter_Native.cpp new file mode 100644 index 0000000..e0d55d6 --- /dev/null +++ b/Source/Common/Platform/NMR_XmlWriter_Native.cpp @@ -0,0 +1,381 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_XmlWriter_Native.cpp implements an XML Writer Class without dependencies. + +--*/ + +#include "Common/Platform/NMR_XmlWriter_Native.h" +#include "Common/Platform/NMR_ExportStream.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_StringUtils.h" + +#include +#include + +namespace NMR { + + CXmlWriter_Native::CXmlWriter_Native(_In_ PExportStream pExportStream) + : CXmlWriter(pExportStream) + { + m_bIsFreshLine = true; + +#ifndef __GNUC__ + m_nLineEndingBuffer[0] = 0x0d; + m_nLineEndingBuffer[1] = 0x0a; + m_nLineEndingCharCount = 2; +#else + m_nLineEndingBuffer[0] = 0x0a; + m_nLineEndingBuffer[1] = 0x0a; + m_nLineEndingCharCount = 1; +#endif // __GNUC__ + + m_nSpacesPerLayer = 1; + m_nLayer = 0; + + m_SpacingBuffer.fill(NATIVEXMLSPACING); + m_bElementIsOpen = false; + } + + void CXmlWriter_Native::WriteStartDocument() + { + writeUTF8(NATIVEXMLENCODING, true); + } + + void CXmlWriter_Native::WriteEndDocument() + { + } + + void CXmlWriter_Native::Flush() + { + } + + void CXmlWriter_Native::WriteAttributeString(_In_opt_ LPCSTR pszPrefix, _In_opt_ LPCSTR pszLocalName, _In_opt_ LPCSTR pszNamespaceUri, _In_opt_ LPCSTR pszValue) + { + if (m_bElementIsOpen) { + writeUTF8(" ", false); + + if (pszPrefix != nullptr) { + if (*pszPrefix != 0) { + writeUTF8(pszPrefix, false); + writeUTF8(":", false); + } + } + + writeUTF8(pszLocalName, false); + writeUTF8("=\"", false); + + size_t nLength = strlen(pszValue); + if (nLength < NATIVEXMLFIXEDENCODINGLENGTH) { + // for small attribute lengths, use fixed size buffer + nfChar * pszAttribBuffer = &m_FixedEncodingBuffer[0]; + escapeXMLString(pszValue, pszAttribBuffer); + writeUTF8(pszAttribBuffer, false); + } + else { + if (nLength > NATIVEXMLMAXSTRINGLENGTH) + throw CNMRException(NMR_ERROR_INVALIDBUFFERSIZE); + + // for large attribute lengths, use dynamic buffer + std::vector Buffer; + Buffer.resize((nLength + 1) * 6); + nfChar * pszAttribBuffer = &Buffer[0]; + escapeXMLString(pszValue, pszAttribBuffer); + writeUTF8(pszAttribBuffer, false); + } + + writeUTF8("\"", false); + } + } + + void CXmlWriter_Native::WriteStartElement(_In_opt_ LPCSTR pszPrefix, _In_ LPCSTR pszLocalName, _In_opt_ LPCSTR pszNamespaceUri) + { + closeCurrentElement(true); + + writeSpaces(m_nLayer * m_nSpacesPerLayer); + writeUTF8("<", false); + + m_bElementIsOpen = true; + + std::string sNodePrefix; + if (pszPrefix != nullptr) { + if (*pszPrefix != 0) { + sNodePrefix = pszPrefix; + sNodePrefix += ":"; + + writeUTF8(sNodePrefix.c_str(), false); + } + } + + writeUTF8(pszLocalName, false); + + std::string sNodeName(pszLocalName); + m_NodeStack.push_back(sNodePrefix + sNodeName); + m_nLayer++; + + if (pszNamespaceUri != nullptr) { + if (*pszNamespaceUri != 0) { + writeUTF8(" xmlns=\"", false); + writeUTF8(pszNamespaceUri, false); + writeUTF8("\"", false); + } + } + } + + void CXmlWriter_Native::WriteEndElement() + { + if (m_bElementIsOpen) { + writeUTF8("/>", true); + m_bElementIsOpen = false; + + if ((m_NodeStack.size() == 0) || (m_nLayer == 0)) + throw CNMRException(NMR_ERROR_XMLWRITER_CLOSENODEERROR); + m_NodeStack.pop_back(); + m_nLayer--; + } + else + WriteFullEndElement(); + } + + void CXmlWriter_Native::WriteFullEndElement() + { + closeCurrentElement(false); + if ((m_NodeStack.size() == 0) || (m_nLayer == 0)) + throw CNMRException(NMR_ERROR_XMLWRITER_CLOSENODEERROR); + + std::string sNodeName = m_NodeStack.back(); + m_NodeStack.pop_back(); + m_nLayer--; + + if (m_bIsFreshLine) + writeSpaces(m_nLayer * m_nSpacesPerLayer); + + writeUTF8("", true); + } + + void CXmlWriter_Native::WriteText(_In_ const nfChar * pszContent, _In_ const nfUint32 cbLength) + { + if (pszContent == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + closeCurrentElement(false); + + size_t nLength = strlen(pszContent); + if (nLength < NATIVEXMLFIXEDENCODINGLENGTH) { + // for small attribute lengths, use fixed size buffer + nfChar * pszAttribBuffer = &m_FixedEncodingBuffer[0]; + escapeXMLString(pszContent, pszAttribBuffer); + writeUTF8(pszAttribBuffer, false); + } + else { + if (nLength > NATIVEXMLMAXSTRINGLENGTH) + throw CNMRException(NMR_ERROR_INVALIDBUFFERSIZE); + + // for large attribute lengths, use dynamic buffer + std::vector Buffer; + Buffer.resize((nLength + 1) * 6); + nfChar * pszAttribBuffer = &Buffer[0]; + escapeXMLString(pszContent, pszAttribBuffer); + writeUTF8(pszAttribBuffer, false); + } + } + + void CXmlWriter_Native::writeData(_In_ const void * pData, _In_ nfUint32 cbLength) + { + if (pData == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + m_pExportStream->writeBuffer(pData, cbLength); + } + + void CXmlWriter_Native::writeUTF8(_In_ const nfChar * pszString, _In_ nfBool bNewLine) + { + if (pszString == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + +#ifdef __GNUC__ + size_t cbSize = strlen(pszString); +#else + size_t cbSize = strnlen_s(pszString, NATIVEXMLMAXSTRINGLENGTH); +#endif // __GNUC__ + if (cbSize > NATIVEXMLMAXSTRINGLENGTH) + throw CNMRException(NMR_ERROR_INSUFFICIENTBUFFERSIZE); + + if (cbSize > 0) { + writeData((nfByte *)pszString, (nfUint32)cbSize); + m_bIsFreshLine = false; + } + + if (bNewLine) { + writeData(m_nLineEndingBuffer, m_nLineEndingCharCount); + m_bIsFreshLine = true; + } + } + + void CXmlWriter_Native::writeSpaces(_In_ nfUint32 cbCount) + { + while (cbCount > 0) { + if (cbCount > NATIVEXMLSPACINGBUFFERSIZE) { + writeData(&m_SpacingBuffer[0], NATIVEXMLSPACINGBUFFERSIZE); + cbCount -= NATIVEXMLSPACINGBUFFERSIZE; + } + else { + writeData(&m_SpacingBuffer[0], cbCount); + break; + } + } + } + + void CXmlWriter_Native::writeUTF16(_In_ const nfWChar * pszString, _In_ nfBool bNewLine) + { + std::wstring sString(pszString); + std::string sUTF8String = fnUTF16toUTF8(sString); + + writeUTF8(sUTF8String.c_str(), bNewLine); + } + + void CXmlWriter_Native::closeCurrentElement(_In_ nfBool bNewLine) + { + if (m_bElementIsOpen) { + writeUTF8(">", bNewLine); + m_bElementIsOpen = false; + } + } + + void CXmlWriter_Native::WriteRawLine(_In_ const nfChar * pszRawData, _In_ nfUint32 cbCount) + { + if (m_bElementIsOpen) { + closeCurrentElement(true); + } + + writeSpaces(m_nLayer * m_nSpacesPerLayer); + writeData(pszRawData, cbCount); + writeData(m_nLineEndingBuffer, m_nLineEndingCharCount); + } + + void CXmlWriter_Native::escapeXMLString(_In_z_ const nfChar * pszString, _Out_ nfChar * pszBuffer) + { + __NMRASSERT(pszString); + __NMRASSERT(pszBuffer); + + const nfChar * pSrcChar = pszString; + nfChar * pDstChar = pszBuffer; + while (*pSrcChar) { + nfUint32 nReplaceLength = 0; + const nfChar * pszReplacement = nullptr; + + switch (*pSrcChar) { + case 34: // " + pszReplacement = """; + nReplaceLength = 6; + break; + case 38: // & + pszReplacement = "&"; + nReplaceLength = 5; + break; + case 39: // ' + pszReplacement = "'"; + nReplaceLength = 6; + break; + case 60: // < + pszReplacement = "<"; + nReplaceLength = 4; + break; + case 62: // > + pszReplacement = ">"; + nReplaceLength = 4; + break; + } + + if (nReplaceLength > 0) { + nfUint32 j; + for (j = 0; j < nReplaceLength; j++) { + *pDstChar = *pszReplacement; + pDstChar++; + pszReplacement++; + } + } + else { + *pDstChar = *pSrcChar; + pDstChar++; + } + + pSrcChar++; + + } + + *pDstChar = 0; + } + + bool CXmlWriter_Native::GetNamespacePrefix(const std::string &sNameSpaceURI, std::string &sNameSpacePrefix) + { + auto iIterator = m_sNameSpaces.find(sNameSpaceURI); + if (iIterator != m_sNameSpaces.end()) { + sNameSpacePrefix = iIterator->second.c_str(); + return true; + } + else { + return false; + } + } + + void CXmlWriter_Native::RegisterCustomNameSpace(const std::string &sNameSpace, const std::string &sNameSpacePrefix) + { + std::string sDummy; + if (GetNamespacePrefix(sNameSpace, sDummy)) + { + throw CNMRException(NMR_ERROR_XMLNAMESPACEALREADYREGISTERED); + } + for (auto it = m_sNameSpaces.begin(); it != m_sNameSpaces.end(); ++it) + if (it->second == sNameSpacePrefix) + throw CNMRException(NMR_ERROR_XMLPREFIXALREADYREGISTERED); + + m_sNameSpaces.insert(std::make_pair(sNameSpace, sNameSpacePrefix)); + } + + nfUint32 CXmlWriter_Native::GetNamespaceCount() + { + return nfUint32(m_sNameSpaces.size()); + } + + std::string CXmlWriter_Native::GetNamespacePrefix(nfUint32 nIndex) + { + auto iter = m_sNameSpaces.begin(); + for (nfUint32 i = 0; i < nIndex; i++) + iter++; + return iter->second; + } + + std::string CXmlWriter_Native::GetNamespace(nfUint32 nIndex) + { + auto iter = m_sNameSpaces.begin(); + for (nfUint32 i = 0; i < nIndex; i++) + iter++; + return iter->first; + } +} diff --git a/Source/Libraries/cpp-base64/base64.cpp b/Source/Libraries/cpp-base64/base64.cpp new file mode 100644 index 0000000..82a175a --- /dev/null +++ b/Source/Libraries/cpp-base64/base64.cpp @@ -0,0 +1,125 @@ +/* + base64.cpp and base64.h + + base64 encoding and decoding with C++. + + Version: 1.01.00 + + Copyright (C) 2004-2017 René Nyffenegger + + This source code is provided 'as-is', without any express or implied + warranty. In no event will the author be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this source code must not be misrepresented; you must not + claim that you wrote the original source code. If you use this source code + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original source code. + + 3. This notice may not be removed or altered from any source distribution. + + René Nyffenegger rene.nyffenegger@adp-gmbh.ch + + DISCLAIMER + This is a modified version. +*/ + +#include "Libraries/cpp-base64/base64.h" + +static const std::string base64_chars = + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/"; + + +static inline bool is_base64(unsigned char c) { + return (isalnum(c) || (c == '+') || (c == '/')); +} + +std::string base64_encode(std::vector const & buffer) { + size_t in_len = buffer.size(); + unsigned char const * bytes_to_encode = buffer.data(); + std::string ret; + int i = 0; + int j = 0; + unsigned char char_array_3[3]; + unsigned char char_array_4[4]; + + while (in_len--) { + char_array_3[i++] = *(bytes_to_encode++); + if (i == 3) { + char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; + char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); + char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); + char_array_4[3] = char_array_3[2] & 0x3f; + + for(i = 0; (i <4) ; i++) + ret += base64_chars[char_array_4[i]]; + i = 0; + } + } + + if (i) + { + for(j = i; j < 3; j++) + char_array_3[j] = '\0'; + + char_array_4[0] = ( char_array_3[0] & 0xfc) >> 2; + char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); + char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); + + for (j = 0; (j < i + 1); j++) + ret += base64_chars[char_array_4[j]]; + + while((i++ < 3)) + ret += '='; + + } + + return ret; + +} + +std::vector base64_decode(std::string const& encoded_string) { + size_t in_len = encoded_string.size(); + int i = 0; + int j = 0; + int in_ = 0; + unsigned char char_array_4[4], char_array_3[3]; + std::vector ret; + + while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) { + char_array_4[i++] = encoded_string[in_]; in_++; + if (i ==4) { + for (i = 0; i <4; i++) + char_array_4[i] = base64_chars.find(char_array_4[i]) & 0xff; + + char_array_3[0] = ( char_array_4[0] << 2 ) + ((char_array_4[1] & 0x30) >> 4); + char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); + char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; + + for (i = 0; (i < 3); i++) + ret.push_back(char_array_3[i]); + i = 0; + } + } + + if (i) { + for (j = 0; j < i; j++) + char_array_4[j] = base64_chars.find(char_array_4[j]) & 0xff; + + char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); + char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); + + for (j = 0; (j < i - 1); j++) ret.push_back(char_array_3[j]); + } + + return ret; +} diff --git a/Source/Libraries/libzip/Unix/zip_mkstempm.c b/Source/Libraries/libzip/Unix/zip_mkstempm.c new file mode 100644 index 0000000..41516d2 --- /dev/null +++ b/Source/Libraries/libzip/Unix/zip_mkstempm.c @@ -0,0 +1,93 @@ +/* + zip_mkstempm.c -- mkstemp replacement that accepts a mode argument + Copyright (C) 2019-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include + +#include "zipint.h" + +/* + * create temporary file with same permissions as previous one; + * or default permissions if there is no previous file + */ +int +_zip_mkstempm(char *path, int mode) { + int fd; + char *start, *end, *xs; + + int xcnt = 0; + + end = path + strlen(path); + start = end - 1; + while (start >= path && *start == 'X') { + xcnt++; + start--; + } + + if (xcnt == 0) { + errno = EINVAL; + return -1; + } + + start++; + + for (;;) { + zip_uint32_t value = zip_random_uint32(); + + xs = start; + + while (xs < end) { + char digit = value % 36; + if (digit < 10) { + *(xs++) = digit + '0'; + } + else { + *(xs++) = digit - 10 + 'a'; + } + value /= 36; + } + + if ((fd = open(path, O_CREAT | O_EXCL | O_RDWR | O_CLOEXEC, mode == -1 ? 0666 : (mode_t)mode)) >= 0) { + if (mode != -1) { + /* open() honors umask(), which we don't want in this case */ + (void)chmod(path, (mode_t)mode); + } + return fd; + } + if (errno != EEXIST) { + return -1; + } + } +} diff --git a/Source/Libraries/libzip/Unix/zip_random_unix.c b/Source/Libraries/libzip/Unix/zip_random_unix.c new file mode 100644 index 0000000..4aa9cc2 --- /dev/null +++ b/Source/Libraries/libzip/Unix/zip_random_unix.c @@ -0,0 +1,104 @@ +/* + zip_random_unix.c -- fill the user's buffer with random stuff (Unix version) + Copyright (C) 2016-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +#ifdef HAVE_CRYPTO +#include "zip_crypto.h" +#endif + +#ifdef HAVE_ARC4RANDOM + +#include + +#ifndef HAVE_SECURE_RANDOM +ZIP_EXTERN bool +zip_secure_random(zip_uint8_t *buffer, zip_uint16_t length) { + arc4random_buf(buffer, length); + return true; +} +#endif + +#ifndef HAVE_RANDOM_UINT32 +zip_uint32_t +zip_random_uint32(void) { + return arc4random(); +} +#endif + +#else /* HAVE_ARC4RANDOM */ + +#ifndef HAVE_SECURE_RANDOM +#include +#include + +ZIP_EXTERN bool +zip_secure_random(zip_uint8_t *buffer, zip_uint16_t length) { + int fd; + + if ((fd = open("/dev/urandom", O_RDONLY)) < 0) { + return false; + } + + if (read(fd, buffer, length) != length) { + close(fd); + return false; + } + + close(fd); + return true; +} +#endif + +#ifndef HAVE_RANDOM_UINT32 +#include + +zip_uint32_t +zip_random_uint32(void) { + static bool seeded = false; + + zip_uint32_t value; + + if (zip_secure_random((zip_uint8_t *)&value, sizeof(value))) { + return value; + } + + if (!seeded) { + srandom((unsigned int)time(NULL)); + } + + return (zip_uint32_t)random(); +} +#endif + +#endif /* HAVE_ARC4RANDOM */ diff --git a/Source/Libraries/libzip/Unix/zip_source_file_stdio_named.c b/Source/Libraries/libzip/Unix/zip_source_file_stdio_named.c new file mode 100644 index 0000000..5387c76 --- /dev/null +++ b/Source/Libraries/libzip/Unix/zip_source_file_stdio_named.c @@ -0,0 +1,313 @@ +/* + zip_source_file_stdio_named.c -- source for stdio file opened by name + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +#include "zip_source_file.h" +#include "zip_source_file_stdio.h" + +#include +#include +#ifdef HAVE_UNISTD_H +#include +#endif + +#ifdef HAVE_CLONEFILE +#include +#include +#define CAN_CLONE +#endif +#ifdef HAVE_FICLONERANGE +#include +#include +#define CAN_CLONE +#endif + +static zip_int64_t _zip_stdio_op_commit_write(zip_source_file_context_t *ctx); +static zip_int64_t _zip_stdio_op_create_temp_output(zip_source_file_context_t *ctx); +#ifdef CAN_CLONE +static zip_int64_t _zip_stdio_op_create_temp_output_cloning(zip_source_file_context_t *ctx, zip_uint64_t offset); +#endif +static bool _zip_stdio_op_open(zip_source_file_context_t *ctx); +static zip_int64_t _zip_stdio_op_remove(zip_source_file_context_t *ctx); +static void _zip_stdio_op_rollback_write(zip_source_file_context_t *ctx); +static char *_zip_stdio_op_strdup(zip_source_file_context_t *ctx, const char *string); +static zip_int64_t _zip_stdio_op_write(zip_source_file_context_t *ctx, const void *data, zip_uint64_t len); + +/* clang-format off */ +static zip_source_file_operations_t ops_stdio_named = { + _zip_stdio_op_close, + _zip_stdio_op_commit_write, + _zip_stdio_op_create_temp_output, +#ifdef CAN_CLONE + _zip_stdio_op_create_temp_output_cloning, +#else + NULL, +#endif + _zip_stdio_op_open, + _zip_stdio_op_read, + _zip_stdio_op_remove, + _zip_stdio_op_rollback_write, + _zip_stdio_op_seek, + _zip_stdio_op_stat, + _zip_stdio_op_strdup, + _zip_stdio_op_tell, + _zip_stdio_op_write +}; +/* clang-format on */ + +ZIP_EXTERN zip_source_t * +zip_source_file(zip_t *za, const char *fname, zip_uint64_t start, zip_int64_t len) { + if (za == NULL) + return NULL; + + return zip_source_file_create(fname, start, len, &za->error); +} + + +ZIP_EXTERN zip_source_t * +zip_source_file_create(const char *fname, zip_uint64_t start, zip_int64_t length, zip_error_t *error) { + if (fname == NULL || length < -1) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + return zip_source_file_common_new(fname, NULL, start, length, NULL, &ops_stdio_named, NULL, error); +} + + +static zip_int64_t +_zip_stdio_op_commit_write(zip_source_file_context_t *ctx) { + if (fclose(ctx->fout) < 0) { + zip_error_set(&ctx->error, ZIP_ER_WRITE, errno); + return -1; + } + if (rename(ctx->tmpname, ctx->fname) < 0) { + zip_error_set(&ctx->error, ZIP_ER_RENAME, errno); + return -1; + } + + return 0; +} + + +static zip_int64_t +_zip_stdio_op_create_temp_output(zip_source_file_context_t *ctx) { + char *temp; + int tfd; + int mode; + FILE *tfp; + struct stat st; + + if ((temp = (char *)malloc(strlen(ctx->fname) + 8)) == NULL) { + zip_error_set(&ctx->error, ZIP_ER_MEMORY, 0); + return -1; + } + + if (stat(ctx->fname, &st) == 0) { + mode = st.st_mode; + } + else { + mode = -1; + } + + sprintf(temp, "%s.XXXXXX", ctx->fname); + + if ((tfd = _zip_mkstempm(temp, mode)) == -1) { + zip_error_set(&ctx->error, ZIP_ER_TMPOPEN, errno); + free(temp); + return -1; + } + + if ((tfp = fdopen(tfd, "r+b")) == NULL) { + zip_error_set(&ctx->error, ZIP_ER_TMPOPEN, errno); + close(tfd); + (void)remove(temp); + free(temp); + return -1; + } + + ctx->fout = tfp; + ctx->tmpname = temp; + + return 0; +} + +#ifdef CAN_CLONE +static zip_int64_t +_zip_stdio_op_create_temp_output_cloning(zip_source_file_context_t *ctx, zip_uint64_t offset) { + char *temp; + FILE *tfp; + + if (offset > ZIP_OFF_MAX) { + zip_error_set(&ctx->error, ZIP_ER_SEEK, E2BIG); + return -1; + } + + if ((temp = (char *)malloc(strlen(ctx->fname) + 8)) == NULL) { + zip_error_set(&ctx->error, ZIP_ER_MEMORY, 0); + return -1; + } + sprintf(temp, "%s.XXXXXX", ctx->fname); + +#ifdef HAVE_CLONEFILE +#ifndef __clang_analyzer__ + /* we can't use mkstemp, since clonefile insists on creating the file */ + if (mktemp(temp) == NULL) { + zip_error_set(&ctx->error, ZIP_ER_TMPOPEN, errno); + free(temp); + return -1; + } +#endif + + if (clonefile(ctx->fname, temp, 0) < 0) { + zip_error_set(&ctx->error, ZIP_ER_TMPOPEN, errno); + free(temp); + return -1; + } + if ((tfp = _zip_fopen_close_on_exec(temp, true)) == NULL) { + zip_error_set(&ctx->error, ZIP_ER_TMPOPEN, errno); + (void)remove(temp); + free(temp); + return -1; + } +#else + { + int fd; + struct file_clone_range range; + struct stat st; + + if (fstat(fileno(ctx->f), &st) < 0) { + zip_error_set(&ctx->error, ZIP_ER_TMPOPEN, errno); + free(temp); + return -1; + } + + if ((fd = mkstemp(temp)) < 0) { + zip_error_set(&ctx->error, ZIP_ER_TMPOPEN, errno); + free(temp); + return -1; + } + + range.src_fd = fileno(ctx->f); + range.src_offset = 0; + range.src_length = ((offset + st.st_blksize - 1) / st.st_blksize) * st.st_blksize; + if (range.src_length > st.st_size) { + range.src_length = 0; + } + range.dest_offset = 0; + if (ioctl(fd, FICLONERANGE, &range) < 0) { + zip_error_set(&ctx->error, ZIP_ER_TMPOPEN, errno); + (void)close(fd); + (void)remove(temp); + free(temp); + return -1; + } + + if ((tfp = fdopen(fd, "r+b")) == NULL) { + zip_error_set(&ctx->error, ZIP_ER_TMPOPEN, errno); + (void)close(fd); + (void)remove(temp); + free(temp); + return -1; + } + } +#endif + + if (ftruncate(fileno(tfp), (off_t)offset) < 0) { + (void)fclose(tfp); + (void)remove(temp); + free(temp); + return -1; + } + if (fseeko(tfp, (off_t)offset, SEEK_SET) < 0) { + (void)fclose(tfp); + (void)remove(temp); + free(temp); + zip_error_set(&ctx->error, ZIP_ER_TMPOPEN, errno); + } + + ctx->fout = tfp; + ctx->tmpname = temp; + + return 0; +} +#endif + +static bool +_zip_stdio_op_open(zip_source_file_context_t *ctx) { + if ((ctx->f = _zip_fopen_close_on_exec(ctx->fname, false)) == NULL) { + zip_error_set(&ctx->error, ZIP_ER_OPEN, errno); + return false; + } + return true; +} + + +static zip_int64_t +_zip_stdio_op_remove(zip_source_file_context_t *ctx) { + if (remove(ctx->fname) < 0) { + zip_error_set(&ctx->error, ZIP_ER_REMOVE, errno); + return -1; + } + return 0; +} + + +static void +_zip_stdio_op_rollback_write(zip_source_file_context_t *ctx) { + if (ctx->fout) { + fclose(ctx->fout); + } + (void)remove(ctx->tmpname); +} + +static char * +_zip_stdio_op_strdup(zip_source_file_context_t *ctx, const char *string) { + return strdup(string); +} + + +static zip_int64_t +_zip_stdio_op_write(zip_source_file_context_t *ctx, const void *data, zip_uint64_t len) { + size_t ret; + + clearerr((FILE *)ctx->fout); + ret = fwrite(data, 1, len, (FILE *)ctx->fout); + if (ret != len || ferror((FILE *)ctx->fout)) { + zip_error_set(&ctx->error, ZIP_ER_WRITE, errno); + return -1; + } + + return (zip_int64_t)ret; +} diff --git a/Source/Libraries/libzip/Win/zip_source_file_win32.c b/Source/Libraries/libzip/Win/zip_source_file_win32.c new file mode 100644 index 0000000..6547fc2 --- /dev/null +++ b/Source/Libraries/libzip/Win/zip_source_file_win32.c @@ -0,0 +1,234 @@ +/* + zip_source_file_win32.c -- read-only Windows file source implementation + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zip_source_file_win32.h" + +static bool _zip_win32_op_stat(zip_source_file_context_t *ctx, zip_source_file_stat_t *st); + +static bool _zip_stat_win32(zip_source_file_context_t *ctx, zip_source_file_stat_t *st, HANDLE h); + +/* clang-format off */ + +static zip_source_file_operations_t ops_win32_read = { + _zip_win32_op_close, + NULL, + NULL, + NULL, + NULL, + _zip_win32_op_read, + NULL, + NULL, + _zip_win32_op_seek, + _zip_win32_op_stat, + NULL, + _zip_win32_op_tell, + NULL +}; + +/* clang-format on */ + +ZIP_EXTERN zip_source_t * +zip_source_win32handle(zip_t *za, HANDLE h, zip_uint64_t start, zip_int64_t len) { + if (za == NULL) { + return NULL; + } + + return zip_source_win32handle_create(h, start, len, &za->error); +} + + +ZIP_EXTERN zip_source_t * +zip_source_win32handle_create(HANDLE h, zip_uint64_t start, zip_int64_t length, zip_error_t *error) { + if (h == INVALID_HANDLE_VALUE || length < -1) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + return zip_source_file_common_new(NULL, h, start, length, NULL, &ops_win32_read, NULL, error); +} + + +void +_zip_win32_op_close(zip_source_file_context_t *ctx) { + CloseHandle((HANDLE)ctx->f); +} + + +zip_int64_t +_zip_win32_op_read(zip_source_file_context_t *ctx, void *buf, zip_uint64_t len) { + DWORD i; + + /* TODO: cap len to "DWORD_MAX" */ + if (!ReadFile((HANDLE)ctx->f, buf, (DWORD)len, &i, NULL)) { + zip_error_set(&ctx->error, ZIP_ER_READ, _zip_win32_error_to_errno(GetLastError())); + return -1; + } + + return (zip_int64_t)i; +} + + +bool +_zip_win32_op_seek(zip_source_file_context_t *ctx, void *f, zip_int64_t offset, int whence) { + LARGE_INTEGER li; + DWORD method; + + switch (whence) { + case SEEK_SET: + method = FILE_BEGIN; + break; + case SEEK_END: + method = FILE_END; + break; + case SEEK_CUR: + method = FILE_CURRENT; + break; + default: + zip_error_set(&ctx->error, ZIP_ER_SEEK, EINVAL); + return -1; + } + + li.QuadPart = (LONGLONG)offset; + if (!SetFilePointerEx((HANDLE)f, li, NULL, method)) { + zip_error_set(&ctx->error, ZIP_ER_SEEK, _zip_win32_error_to_errno(GetLastError())); + return false; + } + + return true; +} + + +static bool +_zip_win32_op_stat(zip_source_file_context_t *ctx, zip_source_file_stat_t *st) { + return _zip_stat_win32(ctx, st, (HANDLE)ctx->f); +} + + +zip_int64_t +_zip_win32_op_tell(zip_source_file_context_t *ctx, void *f) { + LARGE_INTEGER zero; + LARGE_INTEGER new_offset; + + zero.QuadPart = 0; + if (!SetFilePointerEx((HANDLE)f, zero, &new_offset, FILE_CURRENT)) { + zip_error_set(&ctx->error, ZIP_ER_SEEK, _zip_win32_error_to_errno(GetLastError())); + return -1; + } + + return (zip_int64_t)new_offset.QuadPart; +} + + +int +_zip_win32_error_to_errno(DWORD win32err) { + /* Note: This list isn't exhaustive, but should cover common cases. */ + switch (win32err) { + case ERROR_INVALID_PARAMETER: + return EINVAL; + case ERROR_FILE_NOT_FOUND: + case ERROR_PATH_NOT_FOUND: + return ENOENT; + case ERROR_INVALID_HANDLE: + return EBADF; + case ERROR_ACCESS_DENIED: + return EACCES; + case ERROR_FILE_EXISTS: + return EEXIST; + case ERROR_TOO_MANY_OPEN_FILES: + return EMFILE; + case ERROR_DISK_FULL: + return ENOSPC; + default: + return 10000 + win32err; + } +} + + +static bool +_zip_stat_win32(zip_source_file_context_t *ctx, zip_source_file_stat_t *st, HANDLE h) { + FILETIME mtimeft; + time_t mtime; + LARGE_INTEGER size; + + if (!GetFileTime(h, NULL, NULL, &mtimeft)) { + zip_error_set(&ctx->error, ZIP_ER_READ, _zip_win32_error_to_errno(GetLastError())); + return false; + } + if (_zip_filetime_to_time_t(mtimeft, &mtime) < 0) { + zip_error_set(&ctx->error, ZIP_ER_READ, ERANGE); + return false; + } + + st->exists = true; + st->mtime = mtime; + + if (GetFileType(h) == FILE_TYPE_DISK) { + st->regular_file = 1; + + if (!GetFileSizeEx(h, &size)) { + zip_error_set(&ctx->error, ZIP_ER_READ, _zip_win32_error_to_errno(GetLastError())); + return false; + } + + st->size = (zip_uint64_t)size.QuadPart; + } + + /* TODO: fill in ctx->attributes */ + + return true; +} + + +bool +_zip_filetime_to_time_t(FILETIME ft, time_t *t) { + /* + Inspired by http://stackoverflow.com/questions/6161776/convert-windows-filetime-to-second-in-unix-linux + */ + const zip_int64_t WINDOWS_TICK = 10000000LL; + const zip_int64_t SEC_TO_UNIX_EPOCH = 11644473600LL; + ULARGE_INTEGER li; + zip_int64_t secs; + time_t temp; + + li.LowPart = ft.dwLowDateTime; + li.HighPart = ft.dwHighDateTime; + secs = (li.QuadPart / WINDOWS_TICK - SEC_TO_UNIX_EPOCH); + + temp = (time_t)secs; + if (secs != (zip_int64_t)temp) { + return false; + } + + *t = temp; + return true; +} diff --git a/Source/Libraries/libzip/Win/zip_source_file_win32_named.c b/Source/Libraries/libzip/Win/zip_source_file_win32_named.c new file mode 100644 index 0000000..1fe5591 --- /dev/null +++ b/Source/Libraries/libzip/Win/zip_source_file_win32_named.c @@ -0,0 +1,275 @@ +/* + zip_source_file_win32_named.c -- source for Windows file opened by name + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zip_source_file_win32.h" + +static zip_int64_t _zip_win32_named_op_commit_write(zip_source_file_context_t *ctx); +static zip_int64_t _zip_win32_named_op_create_temp_output(zip_source_file_context_t *ctx); +static bool _zip_win32_named_op_open(zip_source_file_context_t *ctx); +static zip_int64_t _zip_win32_named_op_remove(zip_source_file_context_t *ctx); +static void _zip_win32_named_op_rollback_write(zip_source_file_context_t *ctx); +static bool _zip_win32_named_op_stat(zip_source_file_context_t *ctx, zip_source_file_stat_t *st); +static char *_zip_win32_named_op_string_duplicate(zip_source_file_context_t *ctx, const char *string); +static zip_int64_t _zip_win32_named_op_write(zip_source_file_context_t *ctx, const void *data, zip_uint64_t len); + +static HANDLE win32_named_open(zip_source_file_context_t *ctx, const char *name, bool temporary, PSECURITY_ATTRIBUTES security_attributes); + +/* clang-format off */ +zip_source_file_operations_t _zip_source_file_win32_named_ops = { + _zip_win32_op_close, + _zip_win32_named_op_commit_write, + _zip_win32_named_op_create_temp_output, + NULL, + _zip_win32_named_op_open, + _zip_win32_op_read, + _zip_win32_named_op_remove, + _zip_win32_named_op_rollback_write, + _zip_win32_op_seek, + _zip_win32_named_op_stat, + _zip_win32_named_op_string_duplicate, + _zip_win32_op_tell, + _zip_win32_named_op_write +}; +/* clang-format on */ + +static zip_int64_t +_zip_win32_named_op_commit_write(zip_source_file_context_t *ctx) { + zip_win32_file_operations_t *file_ops = (zip_win32_file_operations_t *)ctx->ops_userdata; + DWORD attributes; + + if (!CloseHandle((HANDLE)ctx->fout)) { + zip_error_set(&ctx->error, ZIP_ER_WRITE, _zip_win32_error_to_errno(GetLastError())); + return -1; + } + + attributes = file_ops->get_file_attributes(ctx->tmpname); + if (attributes == INVALID_FILE_ATTRIBUTES) { + zip_error_set(&ctx->error, ZIP_ER_RENAME, _zip_win32_error_to_errno(GetLastError())); + return -1; + } + + if (attributes & FILE_ATTRIBUTE_TEMPORARY) { + if (!file_ops->set_file_attributes(ctx->tmpname, attributes & ~FILE_ATTRIBUTE_TEMPORARY)) { + zip_error_set(&ctx->error, ZIP_ER_RENAME, _zip_win32_error_to_errno(GetLastError())); + return -1; + } + } + + if (!file_ops->move_file(ctx->tmpname, ctx->fname, MOVEFILE_REPLACE_EXISTING)) { + zip_error_set(&ctx->error, ZIP_ER_RENAME, _zip_win32_error_to_errno(GetLastError())); + return -1; + } + + return 0; +} + +static zip_int64_t +_zip_win32_named_op_create_temp_output(zip_source_file_context_t *ctx) { + zip_win32_file_operations_t *file_ops = (zip_win32_file_operations_t *)ctx->ops_userdata; + + zip_uint32_t value, i; + HANDLE th = INVALID_HANDLE_VALUE; + void *temp = NULL; + PSECURITY_DESCRIPTOR psd = NULL; + PSECURITY_ATTRIBUTES psa = NULL; + SECURITY_ATTRIBUTES sa; + SECURITY_INFORMATION si; + DWORD success; + PACL dacl = NULL; + char *tempname = NULL; + size_t tempname_size = 0; + + if ((HANDLE)ctx->f != INVALID_HANDLE_VALUE && GetFileType((HANDLE)ctx->f) == FILE_TYPE_DISK) { + si = DACL_SECURITY_INFORMATION | UNPROTECTED_DACL_SECURITY_INFORMATION; + success = GetSecurityInfo((HANDLE)ctx->f, SE_FILE_OBJECT, si, NULL, NULL, &dacl, NULL, &psd); + if (success == ERROR_SUCCESS) { + sa.nLength = sizeof(SECURITY_ATTRIBUTES); + sa.bInheritHandle = FALSE; + sa.lpSecurityDescriptor = psd; + psa = &sa; + } + } + +#ifndef MS_UWP + value = GetTickCount(); +#else + value = (zip_uint32_t)(GetTickCount64() & 0xffffffff); +#endif + + if ((tempname = file_ops->allocate_tempname(ctx->fname, 10, &tempname_size)) == NULL) { + zip_error_set(&ctx->error, ZIP_ER_MEMORY, 0); + return -1; + } + + for (i = 0; i < 1024 && th == INVALID_HANDLE_VALUE; i++) { + file_ops->make_tempname(tempname, tempname_size, ctx->fname, value + i); + + th = win32_named_open(ctx, tempname, true, psa); + if (th == INVALID_HANDLE_VALUE && GetLastError() != ERROR_FILE_EXISTS) + break; + } + + if (th == INVALID_HANDLE_VALUE) { + free(tempname); + LocalFree(psd); + zip_error_set(&ctx->error, ZIP_ER_TMPOPEN, _zip_win32_error_to_errno(GetLastError())); + return -1; + } + + LocalFree(psd); + ctx->fout = th; + ctx->tmpname = tempname; + + return 0; +} + + +static bool +_zip_win32_named_op_open(zip_source_file_context_t *ctx) { + HANDLE h = win32_named_open(ctx, ctx->fname, false, NULL); + + if (h == INVALID_HANDLE_VALUE) { + return false; + } + + ctx->f = h; + return true; +} + + +static zip_int64_t +_zip_win32_named_op_remove(zip_source_file_context_t *ctx) { + zip_win32_file_operations_t *file_ops = (zip_win32_file_operations_t *)ctx->ops_userdata; + + if (!file_ops->delete_file(ctx->fname)) { + zip_error_set(&ctx->error, ZIP_ER_REMOVE, _zip_win32_error_to_errno(GetLastError())); + return -1; + } + + return 0; +} + + +static void +_zip_win32_named_op_rollback_write(zip_source_file_context_t *ctx) { + zip_win32_file_operations_t *file_ops = (zip_win32_file_operations_t *)ctx->ops_userdata; + + if (ctx->fout) { + CloseHandle((HANDLE)ctx->fout); + } + file_ops->delete_file(ctx->tmpname); +} + + +static bool +_zip_win32_named_op_stat(zip_source_file_context_t *ctx, zip_source_file_stat_t *st) { + zip_win32_file_operations_t *file_ops = (zip_win32_file_operations_t *)ctx->ops_userdata; + + WIN32_FILE_ATTRIBUTE_DATA file_attributes; + + if (!file_ops->get_file_attributes_ex(ctx->fname, GetFileExInfoStandard, &file_attributes)) { + DWORD error = GetLastError(); + if (error == ERROR_FILE_NOT_FOUND) { + st->exists = false; + return true; + } + zip_error_set(&ctx->error, ZIP_ER_READ, _zip_win32_error_to_errno(error)); + return false; + } + + st->exists = true; + st->regular_file = false; + + if (file_attributes.dwFileAttributes != INVALID_FILE_ATTRIBUTES) { + if ((file_attributes.dwFileAttributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE | FILE_ATTRIBUTE_REPARSE_POINT)) == 0) { + st->regular_file = true; + } + } + + if (!_zip_filetime_to_time_t(file_attributes.ftLastWriteTime, &st->mtime)) { + zip_error_set(&ctx->error, ZIP_ER_READ, ERANGE); + return false; + } + st->size = ((zip_uint64_t)file_attributes.nFileSizeHigh << 32) | file_attributes.nFileSizeLow; + + /* TODO: fill in ctx->attributes */ + + return true; +} + + +static char * +_zip_win32_named_op_string_duplicate(zip_source_file_context_t *ctx, const char *string) { + zip_win32_file_operations_t *file_ops = (zip_win32_file_operations_t *)ctx->ops_userdata; + + return file_ops->string_duplicate(string); +} + + +static zip_int64_t +_zip_win32_named_op_write(zip_source_file_context_t *ctx, const void *data, zip_uint64_t len) { + DWORD ret; + if (!WriteFile((HANDLE)ctx->fout, data, (DWORD)len, &ret, NULL) || ret != len) { + zip_error_set(&ctx->error, ZIP_ER_WRITE, _zip_win32_error_to_errno(GetLastError())); + return -1; + } + + return (zip_int64_t)ret; +} + + +static HANDLE +win32_named_open(zip_source_file_context_t *ctx, const char *name, bool temporary, PSECURITY_ATTRIBUTES security_attributes) { + zip_win32_file_operations_t *file_ops = (zip_win32_file_operations_t *)ctx->ops_userdata; + + DWORD access = GENERIC_READ; + DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE; + DWORD creation_disposition = OPEN_EXISTING; + DWORD file_attributes = FILE_ATTRIBUTE_NORMAL; + HANDLE h; + + if (temporary) { + access = GENERIC_READ | GENERIC_WRITE; + share_mode = FILE_SHARE_READ; + creation_disposition = CREATE_NEW; + file_attributes = FILE_ATTRIBUTE_NORMAL | FILE_ATTRIBUTE_TEMPORARY; + } + + h = file_ops->create_file(name, access, share_mode, security_attributes, creation_disposition, file_attributes, NULL); + + if (h == INVALID_HANDLE_VALUE) { + zip_error_set(&ctx->error, ZIP_ER_OPEN, _zip_win32_error_to_errno(GetLastError())); + } + + return h; +} diff --git a/Source/Libraries/libzip/Win/zip_source_file_win32_utf16.c b/Source/Libraries/libzip/Win/zip_source_file_win32_utf16.c new file mode 100644 index 0000000..6aef2bb --- /dev/null +++ b/Source/Libraries/libzip/Win/zip_source_file_win32_utf16.c @@ -0,0 +1,111 @@ +/* + zip_source_file_win32_utf16.c -- source for Windows file opened by UTF-16 name + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zip_source_file_win32.h" + +static char *utf16_allocate_tempname(const char *name, size_t extra_chars, size_t *lengthp); +static HANDLE __stdcall utf16_create_file(const char *name, DWORD access, DWORD share_mode, PSECURITY_ATTRIBUTES security_attributes, DWORD creation_disposition, DWORD file_attributes, HANDLE template_file); +static void utf16_make_tempname(char *buf, size_t len, const char *name, zip_uint32_t i); +static char *utf16_strdup(const char *string); + +/* clang-format off */ + +zip_win32_file_operations_t ops_utf16 = { + utf16_allocate_tempname, + utf16_create_file, + DeleteFileW, + GetFileAttributesW, + GetFileAttributesExW, + utf16_make_tempname, + MoveFileExW, + SetFileAttributesW, + utf16_strdup +}; + +/* clang-format on */ + +ZIP_EXTERN zip_source_t * +zip_source_win32w(zip_t *za, const wchar_t *fname, zip_uint64_t start, zip_int64_t len) { + if (za == NULL) + return NULL; + + return zip_source_win32w_create(fname, start, len, &za->error); +} + + +ZIP_EXTERN zip_source_t * +zip_source_win32w_create(const wchar_t *fname, zip_uint64_t start, zip_int64_t length, zip_error_t *error) { + if (fname == NULL || length < -1) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + + return zip_source_file_common_new((const char *)fname, NULL, start, length, NULL, &_zip_source_file_win32_named_ops, &ops_utf16, error); +} + + +static char * +utf16_allocate_tempname(const char *name, size_t extra_chars, size_t *lengthp) { + *lengthp = wcslen((const wchar_t *)name) + extra_chars; + return (char *)malloc(*lengthp * sizeof(wchar_t)); +} + + +static HANDLE __stdcall utf16_create_file(const char *name, DWORD access, DWORD share_mode, PSECURITY_ATTRIBUTES security_attributes, DWORD creation_disposition, DWORD file_attributes, HANDLE template_file) { +#ifdef MS_UWP + CREATEFILE2_EXTENDED_PARAMETERS extParams = {0}; + extParams.dwFileAttributes = file_attributes; + extParams.dwFileFlags = FILE_FLAG_RANDOM_ACCESS; + extParams.dwSecurityQosFlags = SECURITY_ANONYMOUS; + extParams.dwSize = sizeof(extParams); + extParams.hTemplateFile = template_file; + extParams.lpSecurityAttributes = security_attributes; + + return CreateFile2((const wchar_t *)name, access, share_mode, creation_disposition, &extParams); +#else + return CreateFileW((const wchar_t *)name, access, share_mode, security_attributes, creation_disposition, file_attributes, template_file); +#endif +} + + +static void +utf16_make_tempname(char *buf, size_t len, const char *name, zip_uint32_t i) { + _snwprintf((wchar_t *)buf, len, L"%s.%08x", (const wchar_t *)name, i); +} + + +static char * +utf16_strdup(const char *string) { + return (char *)_wcsdup((const wchar_t *)string); +} diff --git a/Source/Libraries/libzip/Win/zip_source_file_win32_utf8.c b/Source/Libraries/libzip/Win/zip_source_file_win32_utf8.c new file mode 100644 index 0000000..d6728e3 --- /dev/null +++ b/Source/Libraries/libzip/Win/zip_source_file_win32_utf8.c @@ -0,0 +1,73 @@ +/* + zip_source_file_win32_ansi.c -- source for Windows file opened by UTF-8 name + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zip_source_file_win32.h" + +ZIP_EXTERN zip_source_t * +zip_source_file(zip_t *za, const char *fname, zip_uint64_t start, zip_int64_t len) { + if (za == NULL) { + return NULL; + } + + return zip_source_file_create(fname, start, len, &za->error); +} + + +ZIP_EXTERN zip_source_t * +zip_source_file_create(const char *fname, zip_uint64_t start, zip_int64_t length, zip_error_t *error) { + int size; + wchar_t *wfname; + zip_source_t *source; + + if (fname == NULL || length < -1) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + /* Convert fname from UTF-8 to Windows-friendly UTF-16. */ + size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, fname, -1, NULL, 0); + if (size == 0) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + if ((wfname = (wchar_t *)malloc(sizeof(wchar_t) * size)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, fname, -1, wfname, size); + + source = zip_source_win32w_create(wfname, start, length, error); + + free(wfname); + return source; +} diff --git a/Source/Libraries/libzip/zip_add.c b/Source/Libraries/libzip/zip_add.c new file mode 100644 index 0000000..ef04f1e --- /dev/null +++ b/Source/Libraries/libzip/zip_add.c @@ -0,0 +1,49 @@ +/* + zip_add.c -- add file via callback function + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + + +#define _ZIP_COMPILING_DEPRECATED +#include "zipint.h" + + +/* + NOTE: Return type is signed so we can return -1 on error. + The index can not be larger than ZIP_INT64_MAX since the size + of the central directory cannot be larger than + ZIP_UINT64_MAX, and each entry is larger than 2 bytes. +*/ + +ZIP_EXTERN zip_int64_t +zip_add(zip_t *za, const char *name, zip_source_t *source) { + return zip_file_add(za, name, source, 0); +} diff --git a/Source/Libraries/libzip/zip_add_dir.c b/Source/Libraries/libzip/zip_add_dir.c new file mode 100644 index 0000000..9999c8d --- /dev/null +++ b/Source/Libraries/libzip/zip_add_dir.c @@ -0,0 +1,44 @@ +/* + zip_add_dir.c -- add directory + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + + +#define _ZIP_COMPILING_DEPRECATED +#include "zipint.h" + + +/* NOTE: Signed due to -1 on error. See zip_add.c for more details. */ + +ZIP_EXTERN zip_int64_t +zip_add_dir(zip_t *za, const char *name) { + return zip_dir_add(za, name, 0); +} diff --git a/Source/Libraries/libzip/zip_add_entry.c b/Source/Libraries/libzip/zip_add_entry.c new file mode 100644 index 0000000..1c9fcff --- /dev/null +++ b/Source/Libraries/libzip/zip_add_entry.c @@ -0,0 +1,80 @@ +/* + zip_add_entry.c -- create and init struct zip_entry + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +/* NOTE: Signed due to -1 on error. See zip_add.c for more details. */ + +zip_int64_t +_zip_add_entry(zip_t *za) { + zip_uint64_t idx; + + if (za->nentry + 1 >= za->nentry_alloc) { + zip_entry_t *rentries; + zip_uint64_t nalloc = za->nentry_alloc; + zip_uint64_t additional_entries = 2 * nalloc; + zip_uint64_t realloc_size; + + if (additional_entries < 16) { + additional_entries = 16; + } + else if (additional_entries > 1024) { + additional_entries = 1024; + } + /* neither + nor * overflows can happen: nentry_alloc * sizeof(struct zip_entry) < UINT64_MAX */ + nalloc += additional_entries; + realloc_size = sizeof(struct zip_entry) * (size_t)nalloc; + + if (sizeof(struct zip_entry) * (size_t)za->nentry_alloc > realloc_size) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + rentries = (zip_entry_t *)realloc(za->entry, sizeof(struct zip_entry) * (size_t)nalloc); + if (!rentries) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + za->entry = rentries; + za->nentry_alloc = nalloc; + } + + idx = za->nentry++; + + _zip_entry_init(za->entry + idx); + + return (zip_int64_t)idx; +} diff --git a/Source/Libraries/libzip/zip_algorithm_deflate.c b/Source/Libraries/libzip/zip_algorithm_deflate.c new file mode 100644 index 0000000..99d8a59 --- /dev/null +++ b/Source/Libraries/libzip/zip_algorithm_deflate.c @@ -0,0 +1,265 @@ +/* + zip_algorithm_deflate.c -- deflate (de)compression routines + Copyright (C) 2017-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +#include +#include +#include + +struct ctx { + zip_error_t *error; + bool compress; + int compression_flags; + bool end_of_input; + z_stream zstr; +}; + + +static zip_uint64_t +maximum_compressed_size(zip_uint64_t uncompressed_size) { + /* max deflate size increase: size + ceil(size/16k)*5+6 */ + + zip_uint64_t compressed_size = uncompressed_size + (uncompressed_size + 16383) / 16384 * 5 + 6; + + if (compressed_size < uncompressed_size) { + return ZIP_UINT64_MAX; + } + return compressed_size; +} + + +static void * +allocate(bool compress, int compression_flags, zip_error_t *error) { + struct ctx *ctx; + + if ((ctx = (struct ctx *)malloc(sizeof(*ctx))) == NULL) { + zip_error_set(error, ZIP_ET_SYS, errno); + return NULL; + } + + ctx->error = error; + ctx->compress = compress; + ctx->compression_flags = compression_flags; + if (ctx->compression_flags < 1 || ctx->compression_flags > 9) { + ctx->compression_flags = Z_BEST_COMPRESSION; + } + ctx->end_of_input = false; + + ctx->zstr.zalloc = Z_NULL; + ctx->zstr.zfree = Z_NULL; + ctx->zstr.opaque = NULL; + + return ctx; +} + + +static void * +compress_allocate(zip_uint16_t method, int compression_flags, zip_error_t *error) { + return allocate(true, compression_flags, error); +} + + +static void * +decompress_allocate(zip_uint16_t method, int compression_flags, zip_error_t *error) { + return allocate(false, compression_flags, error); +} + + +static void +deallocate(void *ud) { + struct ctx *ctx = (struct ctx *)ud; + + free(ctx); +} + + +static zip_uint16_t +general_purpose_bit_flags(void *ud) { + struct ctx *ctx = (struct ctx *)ud; + + if (!ctx->compress) { + return 0; + } + + if (ctx->compression_flags < 3) { + return 2 << 1; + } + else if (ctx->compression_flags > 7) { + return 1 << 1; + } + return 0; +} + + +static bool +start(void *ud, zip_stat_t *st, zip_file_attributes_t *attributes) { + struct ctx *ctx = (struct ctx *)ud; + int ret; + + ctx->zstr.avail_in = 0; + ctx->zstr.next_in = NULL; + ctx->zstr.avail_out = 0; + ctx->zstr.next_out = NULL; + + if (ctx->compress) { + /* negative value to tell zlib not to write a header */ + ret = deflateInit2(&ctx->zstr, ctx->compression_flags, Z_DEFLATED, -MAX_WBITS, MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY); + } + else { + ret = inflateInit2(&ctx->zstr, -MAX_WBITS); + } + + if (ret != Z_OK) { + zip_error_set(ctx->error, ZIP_ER_ZLIB, ret); + return false; + } + + + return true; +} + + +static bool +end(void *ud) { + struct ctx *ctx = (struct ctx *)ud; + int err; + + if (ctx->compress) { + err = deflateEnd(&ctx->zstr); + } + else { + err = inflateEnd(&ctx->zstr); + } + + if (err != Z_OK) { + zip_error_set(ctx->error, ZIP_ER_ZLIB, err); + return false; + } + + return true; +} + + +static bool +input(void *ud, zip_uint8_t *data, zip_uint64_t length) { + struct ctx *ctx = (struct ctx *)ud; + + if (length > UINT_MAX || ctx->zstr.avail_in > 0) { + zip_error_set(ctx->error, ZIP_ER_INVAL, 0); + return false; + } + + ctx->zstr.avail_in = (uInt)length; + ctx->zstr.next_in = (Bytef *)data; + + return true; +} + + +static void +end_of_input(void *ud) { + struct ctx *ctx = (struct ctx *)ud; + + ctx->end_of_input = true; +} + + +static zip_compression_status_t +process(void *ud, zip_uint8_t *data, zip_uint64_t *length) { + struct ctx *ctx = (struct ctx *)ud; + + int ret; + + ctx->zstr.avail_out = (uInt)ZIP_MIN(UINT_MAX, *length); + ctx->zstr.next_out = (Bytef *)data; + + if (ctx->compress) { + ret = deflate(&ctx->zstr, ctx->end_of_input ? Z_FINISH : 0); + } + else { + ret = inflate(&ctx->zstr, Z_SYNC_FLUSH); + } + + *length = *length - ctx->zstr.avail_out; + + switch (ret) { + case Z_OK: + return ZIP_COMPRESSION_OK; + + case Z_STREAM_END: + return ZIP_COMPRESSION_END; + + case Z_BUF_ERROR: + if (ctx->zstr.avail_in == 0) { + return ZIP_COMPRESSION_NEED_DATA; + } + + /* fallthrough */ + + default: + zip_error_set(ctx->error, ZIP_ER_ZLIB, ret); + return ZIP_COMPRESSION_ERROR; + } +} + +/* clang-format off */ + +zip_compression_algorithm_t zip_algorithm_deflate_compress = { + maximum_compressed_size, + compress_allocate, + deallocate, + general_purpose_bit_flags, + 20, + start, + end, + input, + end_of_input, + process +}; + + +zip_compression_algorithm_t zip_algorithm_deflate_decompress = { + maximum_compressed_size, + decompress_allocate, + deallocate, + general_purpose_bit_flags, + 20, + start, + end, + input, + end_of_input, + process +}; + +/* clang-format on */ diff --git a/Source/Libraries/libzip/zip_buffer.c b/Source/Libraries/libzip/zip_buffer.c new file mode 100644 index 0000000..3bfcc82 --- /dev/null +++ b/Source/Libraries/libzip/zip_buffer.c @@ -0,0 +1,324 @@ +/* + zip_buffer.c -- bounds checked access to memory buffer + Copyright (C) 2014-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +zip_uint8_t * +_zip_buffer_data(zip_buffer_t *buffer) { + return buffer->data; +} + + +void +_zip_buffer_free(zip_buffer_t *buffer) { + if (buffer == NULL) { + return; + } + + if (buffer->free_data) { + free(buffer->data); + } + + free(buffer); +} + + +bool +_zip_buffer_eof(zip_buffer_t *buffer) { + return buffer->ok && buffer->offset == buffer->size; +} + + +zip_uint8_t * +_zip_buffer_get(zip_buffer_t *buffer, zip_uint64_t length) { + zip_uint8_t *data; + + data = _zip_buffer_peek(buffer, length); + + if (data != NULL) { + buffer->offset += length; + } + + return data; +} + + +zip_uint16_t +_zip_buffer_get_16(zip_buffer_t *buffer) { + zip_uint8_t *data = _zip_buffer_get(buffer, 2); + + if (data == NULL) { + return 0; + } + + return (zip_uint16_t)(data[0] + (data[1] << 8)); +} + + +zip_uint32_t +_zip_buffer_get_32(zip_buffer_t *buffer) { + zip_uint8_t *data = _zip_buffer_get(buffer, 4); + + if (data == NULL) { + return 0; + } + + return ((((((zip_uint32_t)data[3] << 8) + data[2]) << 8) + data[1]) << 8) + data[0]; +} + + +zip_uint64_t +_zip_buffer_get_64(zip_buffer_t *buffer) { + zip_uint8_t *data = _zip_buffer_get(buffer, 8); + + if (data == NULL) { + return 0; + } + + return ((zip_uint64_t)data[7] << 56) + ((zip_uint64_t)data[6] << 48) + ((zip_uint64_t)data[5] << 40) + ((zip_uint64_t)data[4] << 32) + ((zip_uint64_t)data[3] << 24) + ((zip_uint64_t)data[2] << 16) + ((zip_uint64_t)data[1] << 8) + (zip_uint64_t)data[0]; +} + + +zip_uint8_t +_zip_buffer_get_8(zip_buffer_t *buffer) { + zip_uint8_t *data = _zip_buffer_get(buffer, 1); + + if (data == NULL) { + return 0; + } + + return data[0]; +} + + +zip_uint64_t +_zip_buffer_left(zip_buffer_t *buffer) { + return buffer->ok ? buffer->size - buffer->offset : 0; +} + + +zip_uint64_t +_zip_buffer_read(zip_buffer_t *buffer, zip_uint8_t *data, zip_uint64_t length) { + if (_zip_buffer_left(buffer) < length) { + length = _zip_buffer_left(buffer); + } + + memcpy(data, _zip_buffer_get(buffer, length), length); + + return length; +} + + +zip_buffer_t * +_zip_buffer_new(zip_uint8_t *data, zip_uint64_t size) { + bool free_data = (data == NULL); + zip_buffer_t *buffer; + + if (data == NULL) { + if ((data = (zip_uint8_t *)malloc(size)) == NULL) { + return NULL; + } + } + + if ((buffer = (zip_buffer_t *)malloc(sizeof(*buffer))) == NULL) { + if (free_data) { + free(data); + } + return NULL; + } + + buffer->ok = true; + buffer->data = data; + buffer->size = size; + buffer->offset = 0; + buffer->free_data = free_data; + + return buffer; +} + + +zip_buffer_t * +_zip_buffer_new_from_source(zip_source_t *src, zip_uint64_t size, zip_uint8_t *buf, zip_error_t *error) { + zip_buffer_t *buffer; + + if ((buffer = _zip_buffer_new(buf, size)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + if (_zip_read(src, buffer->data, size, error) < 0) { + _zip_buffer_free(buffer); + return NULL; + } + + return buffer; +} + + +zip_uint64_t +_zip_buffer_offset(zip_buffer_t *buffer) { + return buffer->ok ? buffer->offset : 0; +} + + +bool +_zip_buffer_ok(zip_buffer_t *buffer) { + return buffer->ok; +} + + +zip_uint8_t * +_zip_buffer_peek(zip_buffer_t *buffer, zip_uint64_t length) { + zip_uint8_t *data; + + if (!buffer->ok || buffer->offset + length < length || buffer->offset + length > buffer->size) { + buffer->ok = false; + return NULL; + } + + data = buffer->data + buffer->offset; + return data; +} + +int +_zip_buffer_put(zip_buffer_t *buffer, const void *src, size_t length) { + zip_uint8_t *dst = _zip_buffer_get(buffer, length); + + if (dst == NULL) { + return -1; + } + + memcpy(dst, src, length); + return 0; +} + + +int +_zip_buffer_put_16(zip_buffer_t *buffer, zip_uint16_t i) { + zip_uint8_t *data = _zip_buffer_get(buffer, 2); + + if (data == NULL) { + return -1; + } + + data[0] = (zip_uint8_t)(i & 0xff); + data[1] = (zip_uint8_t)((i >> 8) & 0xff); + + return 0; +} + + +int +_zip_buffer_put_32(zip_buffer_t *buffer, zip_uint32_t i) { + zip_uint8_t *data = _zip_buffer_get(buffer, 4); + + if (data == NULL) { + return -1; + } + + data[0] = (zip_uint8_t)(i & 0xff); + data[1] = (zip_uint8_t)((i >> 8) & 0xff); + data[2] = (zip_uint8_t)((i >> 16) & 0xff); + data[3] = (zip_uint8_t)((i >> 24) & 0xff); + + return 0; +} + + +int +_zip_buffer_put_64(zip_buffer_t *buffer, zip_uint64_t i) { + zip_uint8_t *data = _zip_buffer_get(buffer, 8); + + if (data == NULL) { + return -1; + } + + data[0] = (zip_uint8_t)(i & 0xff); + data[1] = (zip_uint8_t)((i >> 8) & 0xff); + data[2] = (zip_uint8_t)((i >> 16) & 0xff); + data[3] = (zip_uint8_t)((i >> 24) & 0xff); + data[4] = (zip_uint8_t)((i >> 32) & 0xff); + data[5] = (zip_uint8_t)((i >> 40) & 0xff); + data[6] = (zip_uint8_t)((i >> 48) & 0xff); + data[7] = (zip_uint8_t)((i >> 56) & 0xff); + + return 0; +} + + +int +_zip_buffer_put_8(zip_buffer_t *buffer, zip_uint8_t i) { + zip_uint8_t *data = _zip_buffer_get(buffer, 1); + + if (data == NULL) { + return -1; + } + + data[0] = i; + + return 0; +} + + +int +_zip_buffer_set_offset(zip_buffer_t *buffer, zip_uint64_t offset) { + if (offset > buffer->size) { + buffer->ok = false; + return -1; + } + + buffer->ok = true; + buffer->offset = offset; + + return 0; +} + + +int +_zip_buffer_skip(zip_buffer_t *buffer, zip_uint64_t length) { + zip_uint64_t offset = buffer->offset + length; + + if (offset < buffer->offset) { + buffer->ok = false; + return -1; + } + return _zip_buffer_set_offset(buffer, offset); +} + +zip_uint64_t +_zip_buffer_size(zip_buffer_t *buffer) { + return buffer->size; +} diff --git a/Source/Libraries/libzip/zip_close.c b/Source/Libraries/libzip/zip_close.c new file mode 100644 index 0000000..5bd327b --- /dev/null +++ b/Source/Libraries/libzip/zip_close.c @@ -0,0 +1,700 @@ +/* + zip_close.c -- close zip archive and update changes + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +#include +#include +#ifdef _WIN32 +#include +#include +#endif + + +static int add_data(zip_t *, zip_source_t *, zip_dirent_t *, zip_uint32_t); +static int copy_data(zip_t *, zip_uint64_t); +static int copy_source(zip_t *, zip_source_t *, zip_int64_t); +static int write_cdir(zip_t *, const zip_filelist_t *, zip_uint64_t); +static int write_data_descriptor(zip_t *za, const zip_dirent_t *dirent, int is_zip64); + +ZIP_EXTERN int +zip_close(zip_t *za) { + zip_uint64_t i, j, survivors, unchanged_offset; + zip_int64_t off; + int error; + zip_filelist_t *filelist; + int changed; + + if (za == NULL) + return -1; + + changed = _zip_changed(za, &survivors); + + /* don't create zip files with no entries */ + if (survivors == 0) { + if ((za->open_flags & ZIP_TRUNCATE) || changed) { + if (zip_source_remove(za->src) < 0) { + if (!((zip_error_code_zip(zip_source_error(za->src)) == ZIP_ER_REMOVE) && (zip_error_code_system(zip_source_error(za->src)) == ENOENT))) { + _zip_error_set_from_source(&za->error, za->src); + return -1; + } + } + } + zip_discard(za); + return 0; + } + + if (!changed) { + zip_discard(za); + return 0; + } + + if (survivors > za->nentry) { + zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); + return -1; + } + + if ((filelist = (zip_filelist_t *)malloc(sizeof(filelist[0]) * (size_t)survivors)) == NULL) + return -1; + + unchanged_offset = ZIP_UINT64_MAX; + /* create list of files with index into original archive */ + for (i = j = 0; i < za->nentry; i++) { + if (za->entry[i].orig != NULL && ZIP_ENTRY_HAS_CHANGES(&za->entry[i])) { + unchanged_offset = ZIP_MIN(unchanged_offset, za->entry[i].orig->offset); + } + if (za->entry[i].deleted) { + continue; + } + + if (j >= survivors) { + free(filelist); + zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); + return -1; + } + + filelist[j].idx = i; + j++; + } + if (j < survivors) { + free(filelist); + zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); + return -1; + } + + if ((zip_source_supports(za->src) & ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_BEGIN_WRITE_CLONING)) == 0) { + unchanged_offset = 0; + } + else { + if (unchanged_offset == ZIP_UINT64_MAX) { + /* we're keeping all file data, find the end of the last one */ + zip_uint64_t last_index = ZIP_UINT64_MAX; + unchanged_offset = 0; + + for (i = 0; i < za->nentry; i++) { + if (za->entry[i].orig != NULL) { + if (za->entry[i].orig->offset >= unchanged_offset) { + unchanged_offset = za->entry[i].orig->offset; + last_index = i; + } + } + } + if (last_index != ZIP_UINT64_MAX) { + if ((unchanged_offset = _zip_file_get_end(za, last_index, &za->error)) == 0) { + free(filelist); + return -1; + } + } + } + if (unchanged_offset > 0) { + if (zip_source_begin_write_cloning(za->src, unchanged_offset) < 0) { + /* cloning not supported, need to copy everything */ + unchanged_offset = 0; + } + } + } + if (unchanged_offset == 0) { + if (zip_source_begin_write(za->src) < 0) { + _zip_error_set_from_source(&za->error, za->src); + free(filelist); + return -1; + } + } + + if (_zip_progress_start(za->progress) != 0) { + zip_error_set(&za->error, ZIP_ER_CANCELLED, 0); + zip_source_rollback_write(za->src); + free(filelist); + return -1; + } + error = 0; + for (j = 0; j < survivors; j++) { + int new_data; + zip_entry_t *entry; + zip_dirent_t *de; + + if (_zip_progress_subrange(za->progress, (double)j / (double)survivors, (double)(j + 1) / (double)survivors) != 0) { + zip_error_set(&za->error, ZIP_ER_CANCELLED, 0); + error = 1; + break; + } + + i = filelist[j].idx; + entry = za->entry + i; + + if (entry->orig != NULL && entry->orig->offset < unchanged_offset) { + /* already implicitly copied by cloning */ + continue; + } + + new_data = (ZIP_ENTRY_DATA_CHANGED(entry) || ZIP_ENTRY_CHANGED(entry, ZIP_DIRENT_COMP_METHOD) || ZIP_ENTRY_CHANGED(entry, ZIP_DIRENT_ENCRYPTION_METHOD)); + + /* create new local directory entry */ + if (entry->changes == NULL) { + if ((entry->changes = _zip_dirent_clone(entry->orig)) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + error = 1; + break; + } + } + de = entry->changes; + + if (_zip_read_local_ef(za, i) < 0) { + error = 1; + break; + } + + if ((off = zip_source_tell_write(za->src)) < 0) { + _zip_error_set_from_source(&za->error, za->src); + error = 1; + break; + } + de->offset = (zip_uint64_t)off; + + if (new_data) { + zip_source_t *zs; + + zs = NULL; + if (!ZIP_ENTRY_DATA_CHANGED(entry)) { + if ((zs = _zip_source_zip_new(za, za, i, ZIP_FL_UNCHANGED, 0, 0, NULL)) == NULL) { + error = 1; + break; + } + } + + /* add_data writes dirent */ + if (add_data(za, zs ? zs : entry->source, de, entry->changes ? entry->changes->changed : 0) < 0) { + error = 1; + if (zs) + zip_source_free(zs); + break; + } + if (zs) + zip_source_free(zs); + } + else { + zip_uint64_t offset; + + if (de->encryption_method != ZIP_EM_TRAD_PKWARE) { + /* when copying data, all sizes are known -> no data descriptor needed */ + /* except for PKWare encryption, where removing the data descriptor breaks password validation */ + de->bitflags &= (zip_uint16_t)~ZIP_GPBF_DATA_DESCRIPTOR; + } + if (_zip_dirent_write(za, de, ZIP_FL_LOCAL) < 0) { + error = 1; + break; + } + if ((offset = _zip_file_get_offset(za, i, &za->error)) == 0) { + error = 1; + break; + } + if (zip_source_seek(za->src, (zip_int64_t)offset, SEEK_SET) < 0) { + _zip_error_set_from_source(&za->error, za->src); + error = 1; + break; + } + if (copy_data(za, de->comp_size) < 0) { + error = 1; + break; + } + + if (de->bitflags & ZIP_GPBF_DATA_DESCRIPTOR) { + if (write_data_descriptor(za, de, _zip_dirent_needs_zip64(de, 0)) < 0) { + error = 1; + break; + } + } + } + } + + if (!error) { + if (write_cdir(za, filelist, survivors) < 0) + error = 1; + } + + free(filelist); + + if (!error) { + if (zip_source_commit_write(za->src) != 0) { + _zip_error_set_from_source(&za->error, za->src); + error = 1; + } + _zip_progress_end(za->progress); + } + + if (error) { + zip_source_rollback_write(za->src); + return -1; + } + + zip_discard(za); + + return 0; +} + + +static int +add_data(zip_t *za, zip_source_t *src, zip_dirent_t *de, zip_uint32_t changed) { + zip_int64_t offstart, offdata, offend, data_length; + zip_stat_t st; + zip_file_attributes_t attributes; + zip_source_t *src_final, *src_tmp; + int ret; + int is_zip64; + zip_flags_t flags; + bool needs_recompress, needs_decompress, needs_crc, needs_compress, needs_reencrypt, needs_decrypt, needs_encrypt; + + if (zip_source_stat(src, &st) < 0) { + _zip_error_set_from_source(&za->error, src); + return -1; + } + + if ((st.valid & ZIP_STAT_COMP_METHOD) == 0) { + st.valid |= ZIP_STAT_COMP_METHOD; + st.comp_method = ZIP_CM_STORE; + } + + if (ZIP_CM_IS_DEFAULT(de->comp_method) && st.comp_method != ZIP_CM_STORE) + de->comp_method = st.comp_method; + else if (de->comp_method == ZIP_CM_STORE && (st.valid & ZIP_STAT_SIZE)) { + st.valid |= ZIP_STAT_COMP_SIZE; + st.comp_size = st.size; + } + else { + /* we'll recompress */ + st.valid &= ~ZIP_STAT_COMP_SIZE; + } + + if ((st.valid & ZIP_STAT_ENCRYPTION_METHOD) == 0) { + st.valid |= ZIP_STAT_ENCRYPTION_METHOD; + st.encryption_method = ZIP_EM_NONE; + } + + flags = ZIP_EF_LOCAL; + + if ((st.valid & ZIP_STAT_SIZE) == 0) { + flags |= ZIP_FL_FORCE_ZIP64; + data_length = -1; + } + else { + de->uncomp_size = st.size; + /* this is technically incorrect (copy_source counts compressed data), but it's the best we have */ + data_length = (zip_int64_t)st.size; + + if ((st.valid & ZIP_STAT_COMP_SIZE) == 0) { + zip_uint64_t max_compressed_size; + zip_uint16_t compression_method = ZIP_CM_ACTUAL(de->comp_method); + + if (compression_method == ZIP_CM_STORE) { + max_compressed_size = st.size; + } + else { + zip_compression_algorithm_t *algorithm = _zip_get_compression_algorithm(compression_method, true); + if (algorithm == NULL) { + max_compressed_size = ZIP_UINT64_MAX; + } + else { + max_compressed_size = algorithm->maximum_compressed_size(st.size); + } + } + + if (max_compressed_size > 0xffffffffu) { + flags |= ZIP_FL_FORCE_ZIP64; + } + } + else { + de->comp_size = st.comp_size; + data_length = (zip_int64_t)st.comp_size; + } + } + + if ((offstart = zip_source_tell_write(za->src)) < 0) { + _zip_error_set_from_source(&za->error, za->src); + return -1; + } + + /* as long as we don't support non-seekable output, clear data descriptor bit */ + de->bitflags &= (zip_uint16_t)~ZIP_GPBF_DATA_DESCRIPTOR; + if ((is_zip64 = _zip_dirent_write(za, de, flags)) < 0) { + return -1; + } + + needs_recompress = st.comp_method != ZIP_CM_ACTUAL(de->comp_method); + needs_decompress = needs_recompress && (st.comp_method != ZIP_CM_STORE); + /* in these cases we can compute the CRC ourselves, so we do */ + needs_crc = (st.comp_method == ZIP_CM_STORE) || needs_decompress; + needs_compress = needs_recompress && (de->comp_method != ZIP_CM_STORE); + + needs_reencrypt = needs_recompress || (de->changed & ZIP_DIRENT_PASSWORD) || (de->encryption_method != st.encryption_method); + needs_decrypt = needs_reencrypt && (st.encryption_method != ZIP_EM_NONE); + needs_encrypt = needs_reencrypt && (de->encryption_method != ZIP_EM_NONE); + + src_final = src; + zip_source_keep(src_final); + + if (needs_decrypt) { + zip_encryption_implementation impl; + + if ((impl = _zip_get_encryption_implementation(st.encryption_method, ZIP_CODEC_DECODE)) == NULL) { + zip_error_set(&za->error, ZIP_ER_ENCRNOTSUPP, 0); + zip_source_free(src_final); + return -1; + } + if ((src_tmp = impl(za, src_final, st.encryption_method, ZIP_CODEC_DECODE, za->default_password)) == NULL) { + /* error set by impl */ + zip_source_free(src_final); + return -1; + } + + zip_source_free(src_final); + src_final = src_tmp; + } + + if (needs_decompress) { + if ((src_tmp = zip_source_decompress(za, src_final, st.comp_method)) == NULL) { + zip_source_free(src_final); + return -1; + } + + zip_source_free(src_final); + src_final = src_tmp; + } + + if (needs_crc) { + if ((src_tmp = zip_source_crc(za, src_final, 0)) == NULL) { + zip_source_free(src_final); + return -1; + } + + zip_source_free(src_final); + src_final = src_tmp; + } + + if (needs_compress) { + if ((src_tmp = zip_source_compress(za, src_final, de->comp_method, de->compression_level)) == NULL) { + zip_source_free(src_final); + return -1; + } + + zip_source_free(src_final); + src_final = src_tmp; + } + + + if (needs_encrypt) { + zip_encryption_implementation impl; + const char *password = NULL; + + if (de->password) { + password = de->password; + } + else if (za->default_password) { + password = za->default_password; + } + + if ((impl = _zip_get_encryption_implementation(de->encryption_method, ZIP_CODEC_ENCODE)) == NULL) { + zip_error_set(&za->error, ZIP_ER_ENCRNOTSUPP, 0); + zip_source_free(src_final); + return -1; + } + if ((src_tmp = impl(za, src_final, de->encryption_method, ZIP_CODEC_ENCODE, password)) == NULL) { + /* error set by impl */ + zip_source_free(src_final); + return -1; + } + if (de->encryption_method == ZIP_EM_TRAD_PKWARE) { + de->bitflags |= ZIP_GPBF_DATA_DESCRIPTOR; + } + + zip_source_free(src_final); + src_final = src_tmp; + } + + + if ((offdata = zip_source_tell_write(za->src)) < 0) { + _zip_error_set_from_source(&za->error, za->src); + return -1; + } + + ret = copy_source(za, src_final, data_length); + + if (zip_source_stat(src_final, &st) < 0) { + _zip_error_set_from_source(&za->error, src_final); + ret = -1; + } + + if (zip_source_get_file_attributes(src_final, &attributes) != 0) { + _zip_error_set_from_source(&za->error, src_final); + ret = -1; + } + + zip_source_free(src_final); + + if (ret < 0) { + return -1; + } + + if ((offend = zip_source_tell_write(za->src)) < 0) { + _zip_error_set_from_source(&za->error, za->src); + return -1; + } + + if (zip_source_seek_write(za->src, offstart, SEEK_SET) < 0) { + _zip_error_set_from_source(&za->error, za->src); + return -1; + } + + if ((st.valid & (ZIP_STAT_COMP_METHOD | ZIP_STAT_CRC | ZIP_STAT_SIZE)) != (ZIP_STAT_COMP_METHOD | ZIP_STAT_CRC | ZIP_STAT_SIZE)) { + zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); + return -1; + } + + if ((de->changed & ZIP_DIRENT_LAST_MOD) == 0) { + if (st.valid & ZIP_STAT_MTIME) + de->last_mod = st.mtime; + else + time(&de->last_mod); + } + de->comp_method = st.comp_method; + de->crc = st.crc; + de->uncomp_size = st.size; + de->comp_size = (zip_uint64_t)(offend - offdata); + _zip_dirent_apply_attributes(de, &attributes, (flags & ZIP_FL_FORCE_ZIP64) != 0, changed); + + if ((ret = _zip_dirent_write(za, de, flags)) < 0) + return -1; + + if (is_zip64 != ret) { + /* Zip64 mismatch between preliminary file header written before data and final file header written afterwards */ + zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); + return -1; + } + + if (zip_source_seek_write(za->src, offend, SEEK_SET) < 0) { + _zip_error_set_from_source(&za->error, za->src); + return -1; + } + + if (de->bitflags & ZIP_GPBF_DATA_DESCRIPTOR) { + if (write_data_descriptor(za, de, is_zip64) < 0) { + return -1; + } + } + + return 0; +} + + +static int +copy_data(zip_t *za, zip_uint64_t len) { + DEFINE_BYTE_ARRAY(buf, BUFSIZE); + size_t n; + double total = (double)len; + + if (!byte_array_init(buf, BUFSIZE)) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + + while (len > 0) { + n = len > BUFSIZE ? BUFSIZE : len; + if (_zip_read(za->src, buf, n, &za->error) < 0) { + byte_array_fini(buf); + return -1; + } + + if (_zip_write(za, buf, n) < 0) { + byte_array_fini(buf); + return -1; + } + + len -= n; + + if (_zip_progress_update(za->progress, (total - (double)len) / total) != 0) { + zip_error_set(&za->error, ZIP_ER_CANCELLED, 0); + return -1; + } + } + + byte_array_fini(buf); + return 0; +} + + +static int +copy_source(zip_t *za, zip_source_t *src, zip_int64_t data_length) { + DEFINE_BYTE_ARRAY(buf, BUFSIZE); + zip_int64_t n, current; + int ret; + + if (zip_source_open(src) < 0) { + _zip_error_set_from_source(&za->error, src); + return -1; + } + + if (!byte_array_init(buf, BUFSIZE)) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + + ret = 0; + current = 0; + while ((n = zip_source_read(src, buf, BUFSIZE)) > 0) { + if (_zip_write(za, buf, (zip_uint64_t)n) < 0) { + ret = -1; + break; + } + if (n == BUFSIZE && za->progress && data_length > 0) { + current += n; + if (_zip_progress_update(za->progress, (double)current / (double)data_length) != 0) { + zip_error_set(&za->error, ZIP_ER_CANCELLED, 0); + ret = -1; + break; + } + } + } + + if (n < 0) { + _zip_error_set_from_source(&za->error, src); + ret = -1; + } + + byte_array_fini(buf); + + zip_source_close(src); + + return ret; +} + +static int +write_cdir(zip_t *za, const zip_filelist_t *filelist, zip_uint64_t survivors) { + zip_int64_t cd_start, end, size; + + if ((cd_start = zip_source_tell_write(za->src)) < 0) { + return -1; + } + + if ((size = _zip_cdir_write(za, filelist, survivors)) < 0) { + return -1; + } + + if ((end = zip_source_tell_write(za->src)) < 0) { + return -1; + } + + return 0; +} + + +int +_zip_changed(const zip_t *za, zip_uint64_t *survivorsp) { + int changed; + zip_uint64_t i, survivors; + + changed = 0; + survivors = 0; + + if (za->comment_changed || za->ch_flags != za->flags) { + changed = 1; + } + + for (i = 0; i < za->nentry; i++) { + if (ZIP_ENTRY_HAS_CHANGES(&za->entry[i])) { + changed = 1; + } + if (!za->entry[i].deleted) { + survivors++; + } + } + + if (survivorsp) { + *survivorsp = survivors; + } + + return changed; +} + +static int +write_data_descriptor(zip_t *za, const zip_dirent_t *de, int is_zip64) { + zip_buffer_t *buffer = _zip_buffer_new(NULL, MAX_DATA_DESCRIPTOR_LENGTH); + int ret = 0; + + if (buffer == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + + _zip_buffer_put(buffer, DATADES_MAGIC, 4); + _zip_buffer_put_32(buffer, de->crc); + if (is_zip64) { + _zip_buffer_put_64(buffer, de->comp_size); + _zip_buffer_put_64(buffer, de->uncomp_size); + } + else { + _zip_buffer_put_32(buffer, (zip_uint32_t)de->comp_size); + _zip_buffer_put_32(buffer, (zip_uint32_t)de->uncomp_size); + } + + if (!_zip_buffer_ok(buffer)) { + zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); + ret = -1; + } + else { + ret = _zip_write(za, _zip_buffer_data(buffer), _zip_buffer_offset(buffer)); + } + + _zip_buffer_free(buffer); + + return ret; +} diff --git a/Source/Libraries/libzip/zip_delete.c b/Source/Libraries/libzip/zip_delete.c new file mode 100644 index 0000000..4ff4c1a --- /dev/null +++ b/Source/Libraries/libzip/zip_delete.c @@ -0,0 +1,68 @@ +/* + zip_delete.c -- delete file from zip archive + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_delete(zip_t *za, zip_uint64_t idx) { + const char *name; + + if (idx >= za->nentry) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + if ((name = _zip_get_name(za, idx, 0, &za->error)) == NULL) { + return -1; + } + + if (!_zip_hash_delete(za->names, (const zip_uint8_t *)name, &za->error)) { + return -1; + } + + /* allow duplicate file names, because the file will + * be removed directly afterwards */ + if (_zip_unchange(za, idx, 1) != 0) + return -1; + + za->entry[idx].deleted = 1; + + return 0; +} diff --git a/Source/Libraries/libzip/zip_dir_add.c b/Source/Libraries/libzip/zip_dir_add.c new file mode 100644 index 0000000..da1e4a4 --- /dev/null +++ b/Source/Libraries/libzip/zip_dir_add.c @@ -0,0 +1,92 @@ +/* + zip_dir_add.c -- add directory + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +/* NOTE: Signed due to -1 on error. See zip_add.c for more details. */ + +ZIP_EXTERN zip_int64_t +zip_dir_add(zip_t *za, const char *name, zip_flags_t flags) { + size_t len; + zip_int64_t idx; + char *s; + zip_source_t *source; + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + if (name == NULL) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + s = NULL; + len = strlen(name); + + if (name[len - 1] != '/') { + if ((s = (char *)malloc(len + 2)) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + strcpy(s, name); + s[len] = '/'; + s[len + 1] = '\0'; + } + + if ((source = zip_source_buffer(za, NULL, 0, 0)) == NULL) { + free(s); + return -1; + } + + idx = _zip_file_replace(za, ZIP_UINT64_MAX, s ? s : name, source, flags); + + free(s); + + if (idx < 0) + zip_source_free(source); + else { + if (zip_file_set_external_attributes(za, (zip_uint64_t)idx, 0, ZIP_OPSYS_DEFAULT, ZIP_EXT_ATTRIB_DEFAULT_DIR) < 0) { + zip_delete(za, (zip_uint64_t)idx); + return -1; + } + } + + return idx; +} diff --git a/Source/Libraries/libzip/zip_dirent.c b/Source/Libraries/libzip/zip_dirent.c new file mode 100644 index 0000000..5226a6e --- /dev/null +++ b/Source/Libraries/libzip/zip_dirent.c @@ -0,0 +1,1163 @@ +/* + zip_dirent.c -- read directory entry (local or central), clean dirent + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include +#include + +#include "zipint.h" + +static zip_string_t *_zip_dirent_process_ef_utf_8(const zip_dirent_t *de, zip_uint16_t id, zip_string_t *str); +static zip_extra_field_t *_zip_ef_utf8(zip_uint16_t, zip_string_t *, zip_error_t *); +static bool _zip_dirent_process_winzip_aes(zip_dirent_t *de, zip_error_t *error); + + +void +_zip_cdir_free(zip_cdir_t *cd) { + zip_uint64_t i; + + if (!cd) + return; + + for (i = 0; i < cd->nentry; i++) + _zip_entry_finalize(cd->entry + i); + free(cd->entry); + _zip_string_free(cd->comment); + free(cd); +} + + +zip_cdir_t * +_zip_cdir_new(zip_uint64_t nentry, zip_error_t *error) { + zip_cdir_t *cd; + + if ((cd = (zip_cdir_t *)malloc(sizeof(*cd))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + cd->entry = NULL; + cd->nentry = cd->nentry_alloc = 0; + cd->size = cd->offset = 0; + cd->comment = NULL; + cd->is_zip64 = false; + + if (!_zip_cdir_grow(cd, nentry, error)) { + _zip_cdir_free(cd); + return NULL; + } + + return cd; +} + + +bool +_zip_cdir_grow(zip_cdir_t *cd, zip_uint64_t additional_entries, zip_error_t *error) { + zip_uint64_t i, new_alloc; + zip_entry_t *new_entry; + + if (additional_entries == 0) { + return true; + } + + new_alloc = cd->nentry_alloc + additional_entries; + + if (new_alloc < additional_entries || new_alloc > SIZE_MAX / sizeof(*(cd->entry))) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return false; + } + + if ((new_entry = (zip_entry_t *)realloc(cd->entry, sizeof(*(cd->entry)) * (size_t)new_alloc)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return false; + } + + cd->entry = new_entry; + + for (i = cd->nentry; i < new_alloc; i++) { + _zip_entry_init(cd->entry + i); + } + + cd->nentry = cd->nentry_alloc = new_alloc; + + return true; +} + + +zip_int64_t +_zip_cdir_write(zip_t *za, const zip_filelist_t *filelist, zip_uint64_t survivors) { + zip_uint64_t offset, size; + zip_string_t *comment; + zip_uint8_t buf[EOCDLEN + EOCD64LEN + EOCD64LOCLEN]; + zip_buffer_t *buffer; + zip_int64_t off; + zip_uint64_t i; + bool is_zip64; + int ret; + + if ((off = zip_source_tell_write(za->src)) < 0) { + _zip_error_set_from_source(&za->error, za->src); + return -1; + } + offset = (zip_uint64_t)off; + + is_zip64 = false; + + for (i = 0; i < survivors; i++) { + zip_entry_t *entry = za->entry + filelist[i].idx; + + if ((ret = _zip_dirent_write(za, entry->changes ? entry->changes : entry->orig, ZIP_FL_CENTRAL)) < 0) + return -1; + if (ret) + is_zip64 = true; + } + + if ((off = zip_source_tell_write(za->src)) < 0) { + _zip_error_set_from_source(&za->error, za->src); + return -1; + } + size = (zip_uint64_t)off - offset; + + if (offset > ZIP_UINT32_MAX || survivors > ZIP_UINT16_MAX) + is_zip64 = true; + + + if ((buffer = _zip_buffer_new(buf, sizeof(buf))) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + + if (is_zip64) { + _zip_buffer_put(buffer, EOCD64_MAGIC, 4); + _zip_buffer_put_64(buffer, EOCD64LEN - 12); + _zip_buffer_put_16(buffer, 45); + _zip_buffer_put_16(buffer, 45); + _zip_buffer_put_32(buffer, 0); + _zip_buffer_put_32(buffer, 0); + _zip_buffer_put_64(buffer, survivors); + _zip_buffer_put_64(buffer, survivors); + _zip_buffer_put_64(buffer, size); + _zip_buffer_put_64(buffer, offset); + _zip_buffer_put(buffer, EOCD64LOC_MAGIC, 4); + _zip_buffer_put_32(buffer, 0); + _zip_buffer_put_64(buffer, offset + size); + _zip_buffer_put_32(buffer, 1); + } + + _zip_buffer_put(buffer, EOCD_MAGIC, 4); + _zip_buffer_put_32(buffer, 0); + _zip_buffer_put_16(buffer, (zip_uint16_t)(survivors >= ZIP_UINT16_MAX ? ZIP_UINT16_MAX : survivors)); + _zip_buffer_put_16(buffer, (zip_uint16_t)(survivors >= ZIP_UINT16_MAX ? ZIP_UINT16_MAX : survivors)); + _zip_buffer_put_32(buffer, size >= ZIP_UINT32_MAX ? ZIP_UINT32_MAX : (zip_uint32_t)size); + _zip_buffer_put_32(buffer, offset >= ZIP_UINT32_MAX ? ZIP_UINT32_MAX : (zip_uint32_t)offset); + + comment = za->comment_changed ? za->comment_changes : za->comment_orig; + + _zip_buffer_put_16(buffer, (zip_uint16_t)(comment ? comment->length : 0)); + + if (!_zip_buffer_ok(buffer)) { + zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); + _zip_buffer_free(buffer); + return -1; + } + + if (_zip_write(za, _zip_buffer_data(buffer), _zip_buffer_offset(buffer)) < 0) { + _zip_buffer_free(buffer); + return -1; + } + + _zip_buffer_free(buffer); + + if (comment) { + if (_zip_write(za, comment->raw, comment->length) < 0) { + return -1; + } + } + + return (zip_int64_t)size; +} + + +zip_dirent_t * +_zip_dirent_clone(const zip_dirent_t *sde) { + zip_dirent_t *tde; + + if ((tde = (zip_dirent_t *)malloc(sizeof(*tde))) == NULL) + return NULL; + + if (sde) + memcpy(tde, sde, sizeof(*sde)); + else + _zip_dirent_init(tde); + + tde->changed = 0; + tde->cloned = 1; + + return tde; +} + + +void +_zip_dirent_finalize(zip_dirent_t *zde) { + if (!zde->cloned || zde->changed & ZIP_DIRENT_FILENAME) { + _zip_string_free(zde->filename); + zde->filename = NULL; + } + if (!zde->cloned || zde->changed & ZIP_DIRENT_EXTRA_FIELD) { + _zip_ef_free(zde->extra_fields); + zde->extra_fields = NULL; + } + if (!zde->cloned || zde->changed & ZIP_DIRENT_COMMENT) { + _zip_string_free(zde->comment); + zde->comment = NULL; + } + if (!zde->cloned || zde->changed & ZIP_DIRENT_PASSWORD) { + if (zde->password) { + _zip_crypto_clear(zde->password, strlen(zde->password)); + } + free(zde->password); + zde->password = NULL; + } +} + + +void +_zip_dirent_free(zip_dirent_t *zde) { + if (zde == NULL) + return; + + _zip_dirent_finalize(zde); + free(zde); +} + + +void +_zip_dirent_init(zip_dirent_t *de) { + de->changed = 0; + de->local_extra_fields_read = 0; + de->cloned = 0; + + de->crc_valid = true; + de->version_madeby = 63 | (ZIP_OPSYS_DEFAULT << 8); + de->version_needed = 10; /* 1.0 */ + de->bitflags = 0; + de->comp_method = ZIP_CM_DEFAULT; + de->last_mod = 0; + de->crc = 0; + de->comp_size = 0; + de->uncomp_size = 0; + de->filename = NULL; + de->extra_fields = NULL; + de->comment = NULL; + de->disk_number = 0; + de->int_attrib = 0; + de->ext_attrib = ZIP_EXT_ATTRIB_DEFAULT; + de->offset = 0; + de->compression_level = 0; + de->encryption_method = ZIP_EM_NONE; + de->password = NULL; +} + + +bool +_zip_dirent_needs_zip64(const zip_dirent_t *de, zip_flags_t flags) { + if (de->uncomp_size >= ZIP_UINT32_MAX || de->comp_size >= ZIP_UINT32_MAX || ((flags & ZIP_FL_CENTRAL) && de->offset >= ZIP_UINT32_MAX)) + return true; + + return false; +} + + +zip_dirent_t * +_zip_dirent_new(void) { + zip_dirent_t *de; + + if ((de = (zip_dirent_t *)malloc(sizeof(*de))) == NULL) + return NULL; + + _zip_dirent_init(de); + return de; +} + + +/* _zip_dirent_read(zde, fp, bufp, left, localp, error): + Fills the zip directory entry zde. + + If buffer is non-NULL, data is taken from there; otherwise data is read from fp as needed. + + If local is true, it reads a local header instead of a central directory entry. + + Returns size of dirent read if successful. On error, error is filled in and -1 is returned. +*/ + +zip_int64_t +_zip_dirent_read(zip_dirent_t *zde, zip_source_t *src, zip_buffer_t *buffer, bool local, zip_error_t *error) { + zip_uint8_t buf[CDENTRYSIZE]; + zip_uint16_t dostime, dosdate; + zip_uint32_t size, variable_size; + zip_uint16_t filename_len, comment_len, ef_len; + + bool from_buffer = (buffer != NULL); + + size = local ? LENTRYSIZE : CDENTRYSIZE; + + if (buffer) { + if (_zip_buffer_left(buffer) < size) { + zip_error_set(error, ZIP_ER_NOZIP, 0); + return -1; + } + } + else { + if ((buffer = _zip_buffer_new_from_source(src, size, buf, error)) == NULL) { + return -1; + } + } + + if (memcmp(_zip_buffer_get(buffer, 4), (local ? LOCAL_MAGIC : CENTRAL_MAGIC), 4) != 0) { + zip_error_set(error, ZIP_ER_NOZIP, 0); + if (!from_buffer) { + _zip_buffer_free(buffer); + } + return -1; + } + + /* convert buffercontents to zip_dirent */ + + _zip_dirent_init(zde); + if (!local) + zde->version_madeby = _zip_buffer_get_16(buffer); + else + zde->version_madeby = 0; + zde->version_needed = _zip_buffer_get_16(buffer); + zde->bitflags = _zip_buffer_get_16(buffer); + zde->comp_method = _zip_buffer_get_16(buffer); + + /* convert to time_t */ + dostime = _zip_buffer_get_16(buffer); + dosdate = _zip_buffer_get_16(buffer); + zde->last_mod = _zip_d2u_time(dostime, dosdate); + + zde->crc = _zip_buffer_get_32(buffer); + zde->comp_size = _zip_buffer_get_32(buffer); + zde->uncomp_size = _zip_buffer_get_32(buffer); + + filename_len = _zip_buffer_get_16(buffer); + ef_len = _zip_buffer_get_16(buffer); + + if (local) { + comment_len = 0; + zde->disk_number = 0; + zde->int_attrib = 0; + zde->ext_attrib = 0; + zde->offset = 0; + } + else { + comment_len = _zip_buffer_get_16(buffer); + zde->disk_number = _zip_buffer_get_16(buffer); + zde->int_attrib = _zip_buffer_get_16(buffer); + zde->ext_attrib = _zip_buffer_get_32(buffer); + zde->offset = _zip_buffer_get_32(buffer); + } + + if (!_zip_buffer_ok(buffer)) { + zip_error_set(error, ZIP_ER_INTERNAL, 0); + if (!from_buffer) { + _zip_buffer_free(buffer); + } + return -1; + } + + if (zde->bitflags & ZIP_GPBF_ENCRYPTED) { + if (zde->bitflags & ZIP_GPBF_STRONG_ENCRYPTION) { + /* TODO */ + zde->encryption_method = ZIP_EM_UNKNOWN; + } + else { + zde->encryption_method = ZIP_EM_TRAD_PKWARE; + } + } + else { + zde->encryption_method = ZIP_EM_NONE; + } + + zde->filename = NULL; + zde->extra_fields = NULL; + zde->comment = NULL; + + variable_size = (zip_uint32_t)filename_len + (zip_uint32_t)ef_len + (zip_uint32_t)comment_len; + + if (from_buffer) { + if (_zip_buffer_left(buffer) < variable_size) { + zip_error_set(error, ZIP_ER_INCONS, 0); + return -1; + } + } + else { + _zip_buffer_free(buffer); + + if ((buffer = _zip_buffer_new_from_source(src, variable_size, NULL, error)) == NULL) { + return -1; + } + } + + if (filename_len) { + zde->filename = _zip_read_string(buffer, src, filename_len, 1, error); + if (!zde->filename) { + if (zip_error_code_zip(error) == ZIP_ER_EOF) { + zip_error_set(error, ZIP_ER_INCONS, 0); + } + if (!from_buffer) { + _zip_buffer_free(buffer); + } + return -1; + } + + if (zde->bitflags & ZIP_GPBF_ENCODING_UTF_8) { + if (_zip_guess_encoding(zde->filename, ZIP_ENCODING_UTF8_KNOWN) == ZIP_ENCODING_ERROR) { + zip_error_set(error, ZIP_ER_INCONS, 0); + if (!from_buffer) { + _zip_buffer_free(buffer); + } + return -1; + } + } + } + + if (ef_len) { + zip_uint8_t *ef = _zip_read_data(buffer, src, ef_len, 0, error); + + if (ef == NULL) { + if (!from_buffer) { + _zip_buffer_free(buffer); + } + return -1; + } + if (!_zip_ef_parse(ef, ef_len, local ? ZIP_EF_LOCAL : ZIP_EF_CENTRAL, &zde->extra_fields, error)) { + free(ef); + if (!from_buffer) { + _zip_buffer_free(buffer); + } + return -1; + } + free(ef); + if (local) + zde->local_extra_fields_read = 1; + } + + if (comment_len) { + zde->comment = _zip_read_string(buffer, src, comment_len, 0, error); + if (!zde->comment) { + if (!from_buffer) { + _zip_buffer_free(buffer); + } + return -1; + } + if (zde->bitflags & ZIP_GPBF_ENCODING_UTF_8) { + if (_zip_guess_encoding(zde->comment, ZIP_ENCODING_UTF8_KNOWN) == ZIP_ENCODING_ERROR) { + zip_error_set(error, ZIP_ER_INCONS, 0); + if (!from_buffer) { + _zip_buffer_free(buffer); + } + return -1; + } + } + } + + zde->filename = _zip_dirent_process_ef_utf_8(zde, ZIP_EF_UTF_8_NAME, zde->filename); + zde->comment = _zip_dirent_process_ef_utf_8(zde, ZIP_EF_UTF_8_COMMENT, zde->comment); + + /* Zip64 */ + + if (zde->uncomp_size == ZIP_UINT32_MAX || zde->comp_size == ZIP_UINT32_MAX || zde->offset == ZIP_UINT32_MAX) { + zip_uint16_t got_len; + zip_buffer_t *ef_buffer; + const zip_uint8_t *ef = _zip_ef_get_by_id(zde->extra_fields, &got_len, ZIP_EF_ZIP64, 0, local ? ZIP_EF_LOCAL : ZIP_EF_CENTRAL, error); + /* TODO: if got_len == 0 && !ZIP64_EOCD: no error, 0xffffffff is valid value */ + if (ef == NULL) { + if (!from_buffer) { + _zip_buffer_free(buffer); + } + return -1; + } + + if ((ef_buffer = _zip_buffer_new((zip_uint8_t *)ef, got_len)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + if (!from_buffer) { + _zip_buffer_free(buffer); + } + return -1; + } + + if (zde->uncomp_size == ZIP_UINT32_MAX) { + zde->uncomp_size = _zip_buffer_get_64(ef_buffer); + } + else if (local) { + /* From appnote.txt: This entry in the Local header MUST + include BOTH original and compressed file size fields. */ + (void)_zip_buffer_skip(ef_buffer, 8); /* error is caught by _zip_buffer_eof() call */ + } + if (zde->comp_size == ZIP_UINT32_MAX) { + zde->comp_size = _zip_buffer_get_64(ef_buffer); + } + if (!local) { + if (zde->offset == ZIP_UINT32_MAX) { + zde->offset = _zip_buffer_get_64(ef_buffer); + } + if (zde->disk_number == ZIP_UINT16_MAX) { + zde->disk_number = _zip_buffer_get_32(ef_buffer); + } + } + + if (!_zip_buffer_eof(ef_buffer)) { + /* accept additional fields if values match */ + bool ok = true; + switch (got_len) { + case 28: + _zip_buffer_set_offset(ef_buffer, 24); + if (zde->disk_number != _zip_buffer_get_32(ef_buffer)) { + ok = false; + } + /* fallthrough */ + case 24: + _zip_buffer_set_offset(ef_buffer, 0); + if ((zde->uncomp_size != _zip_buffer_get_64(ef_buffer)) || (zde->comp_size != _zip_buffer_get_64(ef_buffer)) || (zde->offset != _zip_buffer_get_64(ef_buffer))) { + ok = false; + } + break; + + default: + ok = false; + } + if (!ok) { + zip_error_set(error, ZIP_ER_INCONS, 0); + _zip_buffer_free(ef_buffer); + if (!from_buffer) { + _zip_buffer_free(buffer); + } + return -1; + } + } + _zip_buffer_free(ef_buffer); + } + + if (!_zip_buffer_ok(buffer)) { + zip_error_set(error, ZIP_ER_INTERNAL, 0); + if (!from_buffer) { + _zip_buffer_free(buffer); + } + return -1; + } + if (!from_buffer) { + _zip_buffer_free(buffer); + } + + /* zip_source_seek / zip_source_tell don't support values > ZIP_INT64_MAX */ + if (zde->offset > ZIP_INT64_MAX) { + zip_error_set(error, ZIP_ER_SEEK, EFBIG); + return -1; + } + + if (!_zip_dirent_process_winzip_aes(zde, error)) { + return -1; + } + + zde->extra_fields = _zip_ef_remove_internal(zde->extra_fields); + + return (zip_int64_t)size + (zip_int64_t)variable_size; +} + + +static zip_string_t * +_zip_dirent_process_ef_utf_8(const zip_dirent_t *de, zip_uint16_t id, zip_string_t *str) { + zip_uint16_t ef_len; + zip_uint32_t ef_crc; + zip_buffer_t *buffer; + + const zip_uint8_t *ef = _zip_ef_get_by_id(de->extra_fields, &ef_len, id, 0, ZIP_EF_BOTH, NULL); + + if (ef == NULL || ef_len < 5 || ef[0] != 1) { + return str; + } + + if ((buffer = _zip_buffer_new((zip_uint8_t *)ef, ef_len)) == NULL) { + return str; + } + + _zip_buffer_get_8(buffer); + ef_crc = _zip_buffer_get_32(buffer); + + if (_zip_string_crc32(str) == ef_crc) { + zip_uint16_t len = (zip_uint16_t)_zip_buffer_left(buffer); + zip_string_t *ef_str = _zip_string_new(_zip_buffer_get(buffer, len), len, ZIP_FL_ENC_UTF_8, NULL); + + if (ef_str != NULL) { + _zip_string_free(str); + str = ef_str; + } + } + + _zip_buffer_free(buffer); + + return str; +} + + +static bool +_zip_dirent_process_winzip_aes(zip_dirent_t *de, zip_error_t *error) { + zip_uint16_t ef_len; + zip_buffer_t *buffer; + const zip_uint8_t *ef; + bool crc_valid; + zip_uint16_t enc_method; + + + if (de->comp_method != ZIP_CM_WINZIP_AES) { + return true; + } + + ef = _zip_ef_get_by_id(de->extra_fields, &ef_len, ZIP_EF_WINZIP_AES, 0, ZIP_EF_BOTH, NULL); + + if (ef == NULL || ef_len < 7) { + zip_error_set(error, ZIP_ER_INCONS, 0); + return false; + } + + if ((buffer = _zip_buffer_new((zip_uint8_t *)ef, ef_len)) == NULL) { + zip_error_set(error, ZIP_ER_INTERNAL, 0); + return false; + } + + /* version */ + + crc_valid = true; + switch (_zip_buffer_get_16(buffer)) { + case 1: + break; + + case 2: + if (de->uncomp_size < 20 /* TODO: constant */) { + crc_valid = false; + } + break; + + default: + zip_error_set(error, ZIP_ER_ENCRNOTSUPP, 0); + _zip_buffer_free(buffer); + return false; + } + + /* vendor */ + if (memcmp(_zip_buffer_get(buffer, 2), "AE", 2) != 0) { + zip_error_set(error, ZIP_ER_ENCRNOTSUPP, 0); + _zip_buffer_free(buffer); + return false; + } + + /* mode */ + switch (_zip_buffer_get_8(buffer)) { + case 1: + enc_method = ZIP_EM_AES_128; + break; + case 2: + enc_method = ZIP_EM_AES_192; + break; + case 3: + enc_method = ZIP_EM_AES_256; + break; + default: + zip_error_set(error, ZIP_ER_ENCRNOTSUPP, 0); + _zip_buffer_free(buffer); + return false; + } + + if (ef_len != 7) { + zip_error_set(error, ZIP_ER_INCONS, 0); + _zip_buffer_free(buffer); + return false; + } + + de->crc_valid = crc_valid; + de->encryption_method = enc_method; + de->comp_method = _zip_buffer_get_16(buffer); + + _zip_buffer_free(buffer); + return true; +} + + +zip_int32_t +_zip_dirent_size(zip_source_t *src, zip_uint16_t flags, zip_error_t *error) { + zip_int32_t size; + bool local = (flags & ZIP_EF_LOCAL) != 0; + int i; + zip_uint8_t b[6]; + zip_buffer_t *buffer; + + size = local ? LENTRYSIZE : CDENTRYSIZE; + + if (zip_source_seek(src, local ? 26 : 28, SEEK_CUR) < 0) { + _zip_error_set_from_source(error, src); + return -1; + } + + if ((buffer = _zip_buffer_new_from_source(src, local ? 4 : 6, b, error)) == NULL) { + return -1; + } + + for (i = 0; i < (local ? 2 : 3); i++) { + size += _zip_buffer_get_16(buffer); + } + + if (!_zip_buffer_eof(buffer)) { + zip_error_set(error, ZIP_ER_INTERNAL, 0); + _zip_buffer_free(buffer); + return -1; + } + + _zip_buffer_free(buffer); + return size; +} + + +/* _zip_dirent_write + Writes zip directory entry. + + If flags & ZIP_EF_LOCAL, it writes a local header instead of a central + directory entry. If flags & ZIP_EF_FORCE_ZIP64, a ZIP64 extra field is written, even if not needed. + + Returns 0 if successful, 1 if successful and wrote ZIP64 extra field. On error, error is filled in and -1 is + returned. +*/ + +int +_zip_dirent_write(zip_t *za, zip_dirent_t *de, zip_flags_t flags) { + zip_uint16_t dostime, dosdate; + zip_encoding_type_t com_enc, name_enc; + zip_extra_field_t *ef; + zip_extra_field_t *ef64; + zip_uint32_t ef_total_size; + bool is_zip64; + bool is_really_zip64; + bool is_winzip_aes; + zip_uint8_t buf[CDENTRYSIZE]; + zip_buffer_t *buffer; + + ef = NULL; + + name_enc = _zip_guess_encoding(de->filename, ZIP_ENCODING_UNKNOWN); + com_enc = _zip_guess_encoding(de->comment, ZIP_ENCODING_UNKNOWN); + + if ((name_enc == ZIP_ENCODING_UTF8_KNOWN && com_enc == ZIP_ENCODING_ASCII) || (name_enc == ZIP_ENCODING_ASCII && com_enc == ZIP_ENCODING_UTF8_KNOWN) || (name_enc == ZIP_ENCODING_UTF8_KNOWN && com_enc == ZIP_ENCODING_UTF8_KNOWN)) + de->bitflags |= ZIP_GPBF_ENCODING_UTF_8; + else { + de->bitflags &= (zip_uint16_t)~ZIP_GPBF_ENCODING_UTF_8; + if (name_enc == ZIP_ENCODING_UTF8_KNOWN) { + ef = _zip_ef_utf8(ZIP_EF_UTF_8_NAME, de->filename, &za->error); + if (ef == NULL) + return -1; + } + if ((flags & ZIP_FL_LOCAL) == 0 && com_enc == ZIP_ENCODING_UTF8_KNOWN) { + zip_extra_field_t *ef2 = _zip_ef_utf8(ZIP_EF_UTF_8_COMMENT, de->comment, &za->error); + if (ef2 == NULL) { + _zip_ef_free(ef); + return -1; + } + ef2->next = ef; + ef = ef2; + } + } + + if (de->encryption_method == ZIP_EM_NONE) { + de->bitflags &= (zip_uint16_t)~ZIP_GPBF_ENCRYPTED; + } + else { + de->bitflags |= (zip_uint16_t)ZIP_GPBF_ENCRYPTED; + } + + is_really_zip64 = _zip_dirent_needs_zip64(de, flags); + is_zip64 = (flags & (ZIP_FL_LOCAL | ZIP_FL_FORCE_ZIP64)) == (ZIP_FL_LOCAL | ZIP_FL_FORCE_ZIP64) || is_really_zip64; + is_winzip_aes = de->encryption_method == ZIP_EM_AES_128 || de->encryption_method == ZIP_EM_AES_192 || de->encryption_method == ZIP_EM_AES_256; + + if (is_zip64) { + zip_uint8_t ef_zip64[EFZIP64SIZE]; + zip_buffer_t *ef_buffer = _zip_buffer_new(ef_zip64, sizeof(ef_zip64)); + if (ef_buffer == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + _zip_ef_free(ef); + return -1; + } + + if (flags & ZIP_FL_LOCAL) { + if ((flags & ZIP_FL_FORCE_ZIP64) || de->comp_size > ZIP_UINT32_MAX || de->uncomp_size > ZIP_UINT32_MAX) { + _zip_buffer_put_64(ef_buffer, de->uncomp_size); + _zip_buffer_put_64(ef_buffer, de->comp_size); + } + } + else { + if ((flags & ZIP_FL_FORCE_ZIP64) || de->comp_size > ZIP_UINT32_MAX || de->uncomp_size > ZIP_UINT32_MAX || de->offset > ZIP_UINT32_MAX) { + if (de->uncomp_size >= ZIP_UINT32_MAX) { + _zip_buffer_put_64(ef_buffer, de->uncomp_size); + } + if (de->comp_size >= ZIP_UINT32_MAX) { + _zip_buffer_put_64(ef_buffer, de->comp_size); + } + if (de->offset >= ZIP_UINT32_MAX) { + _zip_buffer_put_64(ef_buffer, de->offset); + } + } + } + + if (!_zip_buffer_ok(ef_buffer)) { + zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); + _zip_buffer_free(ef_buffer); + _zip_ef_free(ef); + return -1; + } + + ef64 = _zip_ef_new(ZIP_EF_ZIP64, (zip_uint16_t)(_zip_buffer_offset(ef_buffer)), ef_zip64, ZIP_EF_BOTH); + _zip_buffer_free(ef_buffer); + ef64->next = ef; + ef = ef64; + } + + if (is_winzip_aes) { + zip_uint8_t data[EF_WINZIP_AES_SIZE]; + zip_buffer_t *ef_buffer = _zip_buffer_new(data, sizeof(data)); + zip_extra_field_t *ef_winzip; + + if (ef_buffer == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + _zip_ef_free(ef); + return -1; + } + + _zip_buffer_put_16(ef_buffer, 2); + _zip_buffer_put(ef_buffer, "AE", 2); + _zip_buffer_put_8(ef_buffer, (zip_uint8_t)(de->encryption_method & 0xff)); + _zip_buffer_put_16(ef_buffer, (zip_uint16_t)de->comp_method); + + if (!_zip_buffer_ok(ef_buffer)) { + zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); + _zip_buffer_free(ef_buffer); + _zip_ef_free(ef); + return -1; + } + + ef_winzip = _zip_ef_new(ZIP_EF_WINZIP_AES, EF_WINZIP_AES_SIZE, data, ZIP_EF_BOTH); + _zip_buffer_free(ef_buffer); + ef_winzip->next = ef; + ef = ef_winzip; + } + + if ((buffer = _zip_buffer_new(buf, sizeof(buf))) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + _zip_ef_free(ef); + return -1; + } + + _zip_buffer_put(buffer, (flags & ZIP_FL_LOCAL) ? LOCAL_MAGIC : CENTRAL_MAGIC, 4); + + if ((flags & ZIP_FL_LOCAL) == 0) { + _zip_buffer_put_16(buffer, de->version_madeby); + } + _zip_buffer_put_16(buffer, ZIP_MAX(is_really_zip64 ? 45 : 0, de->version_needed)); + _zip_buffer_put_16(buffer, de->bitflags); + if (is_winzip_aes) { + _zip_buffer_put_16(buffer, ZIP_CM_WINZIP_AES); + } + else { + _zip_buffer_put_16(buffer, (zip_uint16_t)de->comp_method); + } + + _zip_u2d_time(de->last_mod, &dostime, &dosdate); + _zip_buffer_put_16(buffer, dostime); + _zip_buffer_put_16(buffer, dosdate); + + if (is_winzip_aes && de->uncomp_size < 20) { + _zip_buffer_put_32(buffer, 0); + } + else { + _zip_buffer_put_32(buffer, de->crc); + } + + if (((flags & ZIP_FL_LOCAL) == ZIP_FL_LOCAL) && ((de->comp_size >= ZIP_UINT32_MAX) || (de->uncomp_size >= ZIP_UINT32_MAX))) { + /* In local headers, if a ZIP64 EF is written, it MUST contain + * both compressed and uncompressed sizes (even if one of the + * two is smaller than 0xFFFFFFFF); on the other hand, those + * may only appear when the corresponding standard entry is + * 0xFFFFFFFF. (appnote.txt 4.5.3) */ + _zip_buffer_put_32(buffer, ZIP_UINT32_MAX); + _zip_buffer_put_32(buffer, ZIP_UINT32_MAX); + } + else { + if (de->comp_size < ZIP_UINT32_MAX) { + _zip_buffer_put_32(buffer, (zip_uint32_t)de->comp_size); + } + else { + _zip_buffer_put_32(buffer, ZIP_UINT32_MAX); + } + if (de->uncomp_size < ZIP_UINT32_MAX) { + _zip_buffer_put_32(buffer, (zip_uint32_t)de->uncomp_size); + } + else { + _zip_buffer_put_32(buffer, ZIP_UINT32_MAX); + } + } + + _zip_buffer_put_16(buffer, _zip_string_length(de->filename)); + /* TODO: check for overflow */ + ef_total_size = (zip_uint32_t)_zip_ef_size(de->extra_fields, flags) + (zip_uint32_t)_zip_ef_size(ef, ZIP_EF_BOTH); + _zip_buffer_put_16(buffer, (zip_uint16_t)ef_total_size); + + if ((flags & ZIP_FL_LOCAL) == 0) { + _zip_buffer_put_16(buffer, _zip_string_length(de->comment)); + _zip_buffer_put_16(buffer, (zip_uint16_t)de->disk_number); + _zip_buffer_put_16(buffer, de->int_attrib); + _zip_buffer_put_32(buffer, de->ext_attrib); + if (de->offset < ZIP_UINT32_MAX) + _zip_buffer_put_32(buffer, (zip_uint32_t)de->offset); + else + _zip_buffer_put_32(buffer, ZIP_UINT32_MAX); + } + + if (!_zip_buffer_ok(buffer)) { + zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); + _zip_buffer_free(buffer); + _zip_ef_free(ef); + return -1; + } + + if (_zip_write(za, buf, _zip_buffer_offset(buffer)) < 0) { + _zip_buffer_free(buffer); + _zip_ef_free(ef); + return -1; + } + + _zip_buffer_free(buffer); + + if (de->filename) { + if (_zip_string_write(za, de->filename) < 0) { + _zip_ef_free(ef); + return -1; + } + } + + if (ef) { + if (_zip_ef_write(za, ef, ZIP_EF_BOTH) < 0) { + _zip_ef_free(ef); + return -1; + } + } + _zip_ef_free(ef); + if (de->extra_fields) { + if (_zip_ef_write(za, de->extra_fields, flags) < 0) { + return -1; + } + } + + if ((flags & ZIP_FL_LOCAL) == 0) { + if (de->comment) { + if (_zip_string_write(za, de->comment) < 0) { + return -1; + } + } + } + + + return is_zip64; +} + + +time_t +_zip_d2u_time(zip_uint16_t dtime, zip_uint16_t ddate) { + struct tm tm; + + memset(&tm, 0, sizeof(tm)); + + /* let mktime decide if DST is in effect */ + tm.tm_isdst = -1; + + tm.tm_year = ((ddate >> 9) & 127) + 1980 - 1900; + tm.tm_mon = ((ddate >> 5) & 15) - 1; + tm.tm_mday = ddate & 31; + + tm.tm_hour = (dtime >> 11) & 31; + tm.tm_min = (dtime >> 5) & 63; + tm.tm_sec = (dtime << 1) & 62; + + return mktime(&tm); +} + + +static zip_extra_field_t * +_zip_ef_utf8(zip_uint16_t id, zip_string_t *str, zip_error_t *error) { + const zip_uint8_t *raw; + zip_uint32_t len; + zip_buffer_t *buffer; + zip_extra_field_t *ef; + + if ((raw = _zip_string_get(str, &len, ZIP_FL_ENC_RAW, NULL)) == NULL) { + /* error already set */ + return NULL; + } + + if (len + 5 > ZIP_UINT16_MAX) { + zip_error_set(error, ZIP_ER_INVAL, 0); /* TODO: better error code? */ + return NULL; + } + + if ((buffer = _zip_buffer_new(NULL, len + 5)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + _zip_buffer_put_8(buffer, 1); + _zip_buffer_put_32(buffer, _zip_string_crc32(str)); + _zip_buffer_put(buffer, raw, len); + + if (!_zip_buffer_ok(buffer)) { + zip_error_set(error, ZIP_ER_INTERNAL, 0); + _zip_buffer_free(buffer); + return NULL; + } + + ef = _zip_ef_new(id, (zip_uint16_t)(_zip_buffer_offset(buffer)), _zip_buffer_data(buffer), ZIP_EF_BOTH); + _zip_buffer_free(buffer); + + return ef; +} + + +zip_dirent_t * +_zip_get_dirent(zip_t *za, zip_uint64_t idx, zip_flags_t flags, zip_error_t *error) { + if (error == NULL) + error = &za->error; + + if (idx >= za->nentry) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + if ((flags & ZIP_FL_UNCHANGED) || za->entry[idx].changes == NULL) { + if (za->entry[idx].orig == NULL) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + if (za->entry[idx].deleted && (flags & ZIP_FL_UNCHANGED) == 0) { + zip_error_set(error, ZIP_ER_DELETED, 0); + return NULL; + } + return za->entry[idx].orig; + } + else + return za->entry[idx].changes; +} + + +void +_zip_u2d_time(time_t intime, zip_uint16_t *dtime, zip_uint16_t *ddate) { + struct tm *tpm; + +#ifdef HAVE_LOCALTIME_R + struct tm tm; + tpm = localtime_r(&intime, &tm); +#else + tpm = localtime(&intime); +#endif + if (tpm == NULL) { + /* if localtime() fails, return an arbitrary date (1980-01-01 00:00:00) */ + *ddate = (1 << 5) + 1; + *dtime = 0; + return; + } + if (tpm->tm_year < 80) { + tpm->tm_year = 80; + } + + *ddate = (zip_uint16_t)(((tpm->tm_year + 1900 - 1980) << 9) + ((tpm->tm_mon + 1) << 5) + tpm->tm_mday); + *dtime = (zip_uint16_t)(((tpm->tm_hour) << 11) + ((tpm->tm_min) << 5) + ((tpm->tm_sec) >> 1)); + + return; +} + + +void +_zip_dirent_apply_attributes(zip_dirent_t *de, zip_file_attributes_t *attributes, bool force_zip64, zip_uint32_t changed) { + zip_uint16_t length; + + if (attributes->valid & ZIP_FILE_ATTRIBUTES_GENERAL_PURPOSE_BIT_FLAGS) { + zip_uint16_t mask = attributes->general_purpose_bit_mask & ZIP_FILE_ATTRIBUTES_GENERAL_PURPOSE_BIT_FLAGS_ALLOWED_MASK; + de->bitflags = (de->bitflags & ~mask) | (attributes->general_purpose_bit_flags & mask); + } + if (attributes->valid & ZIP_FILE_ATTRIBUTES_ASCII) { + de->int_attrib = (de->int_attrib & ~0x1) | (attributes->ascii ? 1 : 0); + } + /* manually set attributes are preferred over attributes provided by source */ + if ((changed & ZIP_DIRENT_ATTRIBUTES) == 0 && (attributes->valid & ZIP_FILE_ATTRIBUTES_EXTERNAL_FILE_ATTRIBUTES)) { + de->ext_attrib = attributes->external_file_attributes; + } + + if (de->comp_method == ZIP_CM_LZMA) { + de->version_needed = 63; + } + else if (de->encryption_method == ZIP_EM_AES_128 || de->encryption_method == ZIP_EM_AES_192 || de->encryption_method == ZIP_EM_AES_256) { + de->version_needed = 51; + } + else if (de->comp_method == ZIP_CM_BZIP2) { + de->version_needed = 46; + } + else if (force_zip64 || _zip_dirent_needs_zip64(de, 0)) { + de->version_needed = 45; + } + else if (de->comp_method == ZIP_CM_DEFLATE || de->encryption_method == ZIP_EM_TRAD_PKWARE) { + de->version_needed = 20; + } + else if ((length = _zip_string_length(de->filename)) > 0 && de->filename->raw[length - 1] == '/') { + de->version_needed = 20; + } + else { + de->version_needed = 10; + } + + if (attributes->valid & ZIP_FILE_ATTRIBUTES_VERSION_NEEDED) { + de->version_needed = ZIP_MAX(de->version_needed, attributes->version_needed); + } + + de->version_madeby = 63 | (de->version_madeby & 0xff00); + if ((changed & ZIP_DIRENT_ATTRIBUTES) == 0 && (attributes->valid & ZIP_FILE_ATTRIBUTES_HOST_SYSTEM)) { + de->version_madeby = (de->version_madeby & 0xff) | (zip_uint16_t)(attributes->host_system << 8); + } +} diff --git a/Source/Libraries/libzip/zip_discard.c b/Source/Libraries/libzip/zip_discard.c new file mode 100644 index 0000000..a29a288 --- /dev/null +++ b/Source/Libraries/libzip/zip_discard.c @@ -0,0 +1,80 @@ +/* + zip_discard.c -- discard and free struct zip + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +/* zip_discard: + frees the space allocated to a zipfile struct, and closes the + corresponding file. */ + +void +zip_discard(zip_t *za) { + zip_uint64_t i; + + if (za == NULL) + return; + + if (za->src) { + zip_source_close(za->src); + zip_source_free(za->src); + } + + free(za->default_password); + _zip_string_free(za->comment_orig); + _zip_string_free(za->comment_changes); + + _zip_hash_free(za->names); + + if (za->entry) { + for (i = 0; i < za->nentry; i++) + _zip_entry_finalize(za->entry + i); + free(za->entry); + } + + for (i = 0; i < za->nopen_source; i++) { + _zip_source_invalidate(za->open_source[i]); + } + free(za->open_source); + + _zip_progress_free(za->progress); + + zip_error_fini(&za->error); + + free(za); + + return; +} diff --git a/Source/Libraries/libzip/zip_entry.c b/Source/Libraries/libzip/zip_entry.c new file mode 100644 index 0000000..837b59c --- /dev/null +++ b/Source/Libraries/libzip/zip_entry.c @@ -0,0 +1,51 @@ +/* + zip_entry.c -- struct zip_entry helper functions + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +void +_zip_entry_finalize(zip_entry_t *e) { + _zip_unchange_data(e); + _zip_dirent_free(e->orig); + _zip_dirent_free(e->changes); +} + + +void +_zip_entry_init(zip_entry_t *e) { + e->orig = NULL; + e->changes = NULL; + e->source = NULL; + e->deleted = 0; +} diff --git a/Source/Libraries/libzip/zip_err_str.c b/Source/Libraries/libzip/zip_err_str.c new file mode 100644 index 0000000..c46258b --- /dev/null +++ b/Source/Libraries/libzip/zip_err_str.c @@ -0,0 +1,84 @@ +/* + This file was generated automatically by CMake + from zip.h; make changes there. +*/ + +#include "zipint.h" + +const char * const _zip_err_str[] = { + "No error", + "Multi-disk zip archives not supported", + "Renaming temporary file failed", + "Closing zip archive failed", + "Seek error", + "Read error", + "Write error", + "CRC error", + "Containing zip archive was closed", + "No such file", + "File already exists", + "Can't open file", + "Failure to create temporary file", + "Zlib error", + "Malloc failure", + "Entry has been changed", + "Compression method not supported", + "Premature end of file", + "Invalid argument", + "Not a zip archive", + "Internal error", + "Zip archive inconsistent", + "Can't remove file", + "Entry has been deleted", + "Encryption method not supported", + "Read-only archive", + "No password provided", + "Wrong password provided", + "Operation not supported", + "Resource still in use", + "Tell error", + "Compressed data invalid", + "Operation cancelled", +}; + +const int _zip_nerr_str = sizeof(_zip_err_str)/sizeof(_zip_err_str[0]); + +#define N ZIP_ET_NONE +#define S ZIP_ET_SYS +#define Z ZIP_ET_ZLIB + +const int _zip_err_type[] = { + N, + N, + S, + S, + S, + S, + S, + N, + N, + N, + N, + S, + S, + Z, + N, + N, + N, + N, + N, + N, + N, + N, + S, + N, + N, + N, + N, + N, + N, + N, + S, + N, + N, +}; diff --git a/Source/Libraries/libzip/zip_error.c b/Source/Libraries/libzip/zip_error.c new file mode 100644 index 0000000..9381d5b --- /dev/null +++ b/Source/Libraries/libzip/zip_error.c @@ -0,0 +1,150 @@ +/* + zip_error.c -- zip_error_t helper functions + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_error_code_system(const zip_error_t *error) { + return error->sys_err; +} + + +ZIP_EXTERN int +zip_error_code_zip(const zip_error_t *error) { + return error->zip_err; +} + + +ZIP_EXTERN void +zip_error_fini(zip_error_t *err) { + free(err->str); + err->str = NULL; +} + + +ZIP_EXTERN void +zip_error_init(zip_error_t *err) { + err->zip_err = ZIP_ER_OK; + err->sys_err = 0; + err->str = NULL; +} + +ZIP_EXTERN void +zip_error_init_with_code(zip_error_t *error, int ze) { + zip_error_init(error); + error->zip_err = ze; + switch (zip_error_system_type(error)) { + case ZIP_ET_SYS: + error->sys_err = errno; + break; + + default: + error->sys_err = 0; + break; + } +} + + +ZIP_EXTERN int +zip_error_system_type(const zip_error_t *error) { + if (error->zip_err < 0 || error->zip_err >= _zip_nerr_str) + return ZIP_ET_NONE; + + return _zip_err_type[error->zip_err]; +} + + +void +_zip_error_clear(zip_error_t *err) { + if (err == NULL) + return; + + err->zip_err = ZIP_ER_OK; + err->sys_err = 0; +} + + +void +_zip_error_copy(zip_error_t *dst, const zip_error_t *src) { + if (dst == NULL) { + return; + } + + dst->zip_err = src->zip_err; + dst->sys_err = src->sys_err; +} + + +void +_zip_error_get(const zip_error_t *err, int *zep, int *sep) { + if (zep) + *zep = err->zip_err; + if (sep) { + if (zip_error_system_type(err) != ZIP_ET_NONE) + *sep = err->sys_err; + else + *sep = 0; + } +} + + +void +zip_error_set(zip_error_t *err, int ze, int se) { + if (err) { + err->zip_err = ze; + err->sys_err = se; + } +} + + +void +_zip_error_set_from_source(zip_error_t *err, zip_source_t *src) { + _zip_error_copy(err, zip_source_error(src)); +} + + +zip_int64_t +zip_error_to_data(const zip_error_t *error, void *data, zip_uint64_t length) { + int *e = (int *)data; + + if (length < sizeof(int) * 2) { + return -1; + } + + e[0] = zip_error_code_zip(error); + e[1] = zip_error_code_system(error); + return sizeof(int) * 2; +} diff --git a/Source/Libraries/libzip/zip_error_clear.c b/Source/Libraries/libzip/zip_error_clear.c new file mode 100644 index 0000000..9bcd506 --- /dev/null +++ b/Source/Libraries/libzip/zip_error_clear.c @@ -0,0 +1,44 @@ +/* + zip_error_clear.c -- clear zip error + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN void +zip_error_clear(zip_t *za) { + if (za == NULL) + return; + + _zip_error_clear(&za->error); +} diff --git a/Source/Libraries/libzip/zip_error_get.c b/Source/Libraries/libzip/zip_error_get.c new file mode 100644 index 0000000..9d0ec03 --- /dev/null +++ b/Source/Libraries/libzip/zip_error_get.c @@ -0,0 +1,54 @@ +/* + zip_error_get.c -- get zip error + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + + +#define _ZIP_COMPILING_DEPRECATED +#include "zipint.h" + + +ZIP_EXTERN void +zip_error_get(zip_t *za, int *zep, int *sep) { + _zip_error_get(&za->error, zep, sep); +} + + +ZIP_EXTERN zip_error_t * +zip_get_error(zip_t *za) { + return &za->error; +} + + +ZIP_EXTERN zip_error_t * +zip_file_get_error(zip_file_t *f) { + return &f->error; +} diff --git a/Source/Libraries/libzip/zip_error_get_sys_type.c b/Source/Libraries/libzip/zip_error_get_sys_type.c new file mode 100644 index 0000000..3c9998c --- /dev/null +++ b/Source/Libraries/libzip/zip_error_get_sys_type.c @@ -0,0 +1,44 @@ +/* + zip_error_get_sys_type.c -- return type of system error code + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + +#define _ZIP_COMPILING_DEPRECATED +#include "zipint.h" + + +ZIP_EXTERN int +zip_error_get_sys_type(int ze) { + if (ze < 0 || ze >= _zip_nerr_str) + return 0; + + return _zip_err_type[ze]; +} diff --git a/Source/Libraries/libzip/zip_error_strerror.c b/Source/Libraries/libzip/zip_error_strerror.c new file mode 100644 index 0000000..d20b3b2 --- /dev/null +++ b/Source/Libraries/libzip/zip_error_strerror.c @@ -0,0 +1,83 @@ +/* + zip_error_sterror.c -- get string representation of struct zip_error + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include + +#include "zipint.h" + + +ZIP_EXTERN const char * +zip_error_strerror(zip_error_t *err) { + const char *zs, *ss; + char buf[128], *s; + + zip_error_fini(err); + + if (err->zip_err < 0 || err->zip_err >= _zip_nerr_str) { + sprintf(buf, "Unknown error %d", err->zip_err); + zs = NULL; + ss = buf; + } + else { + zs = _zip_err_str[err->zip_err]; + + switch (_zip_err_type[err->zip_err]) { + case ZIP_ET_SYS: + ss = strerror(err->sys_err); + break; + + case ZIP_ET_ZLIB: + ss = zError(err->sys_err); + break; + + default: + ss = NULL; + } + } + + if (ss == NULL) + return zs; + else { + if ((s = (char *)malloc(strlen(ss) + (zs ? strlen(zs) + 2 : 0) + 1)) == NULL) + return _zip_err_str[ZIP_ER_MEMORY]; + + sprintf(s, "%s%s%s", (zs ? zs : ""), (zs ? ": " : ""), ss); + err->str = s; + + return s; + } +} diff --git a/Source/Libraries/libzip/zip_error_to_str.c b/Source/Libraries/libzip/zip_error_to_str.c new file mode 100644 index 0000000..adb4829 --- /dev/null +++ b/Source/Libraries/libzip/zip_error_to_str.c @@ -0,0 +1,67 @@ +/* + zip_error_to_str.c -- get string representation of zip error code + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#define _ZIP_COMPILING_DEPRECATED +#include "zipint.h" + +#define snprintf _snprintf + +ZIP_EXTERN int +zip_error_to_str(char *buf, zip_uint64_t len, int ze, int se) { + const char *zs, *ss; + + if (ze < 0 || ze >= _zip_nerr_str) + return snprintf(buf, len, "Unknown error %d", ze); + + zs = _zip_err_str[ze]; + + switch (_zip_err_type[ze]) { + case ZIP_ET_SYS: + ss = strerror(se); + break; + + case ZIP_ET_ZLIB: + ss = zError(se); + break; + + default: + ss = NULL; + } + + return snprintf(buf, len, "%s%s%s", zs, (ss ? ": " : ""), (ss ? ss : "")); +} diff --git a/Source/Libraries/libzip/zip_extra_field.c b/Source/Libraries/libzip/zip_extra_field.c new file mode 100644 index 0000000..7424d88 --- /dev/null +++ b/Source/Libraries/libzip/zip_extra_field.c @@ -0,0 +1,426 @@ +/* + zip_extra_field.c -- manipulate extra fields + Copyright (C) 2012-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +zip_extra_field_t * +_zip_ef_clone(const zip_extra_field_t *ef, zip_error_t *error) { + zip_extra_field_t *head, *prev, *def; + + head = prev = NULL; + + while (ef) { + if ((def = _zip_ef_new(ef->id, ef->size, ef->data, ef->flags)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + _zip_ef_free(head); + return NULL; + } + + if (head == NULL) + head = def; + if (prev) + prev->next = def; + prev = def; + + ef = ef->next; + } + + return head; +} + + +zip_extra_field_t * +_zip_ef_delete_by_id(zip_extra_field_t *ef, zip_uint16_t id, zip_uint16_t id_idx, zip_flags_t flags) { + zip_extra_field_t *head, *prev; + int i; + + i = 0; + head = ef; + prev = NULL; + for (; ef; ef = (prev ? prev->next : head)) { + if ((ef->flags & flags & ZIP_EF_BOTH) && ((ef->id == id) || (id == ZIP_EXTRA_FIELD_ALL))) { + if (id_idx == ZIP_EXTRA_FIELD_ALL || i == id_idx) { + ef->flags &= ~(flags & ZIP_EF_BOTH); + if ((ef->flags & ZIP_EF_BOTH) == 0) { + if (prev) + prev->next = ef->next; + else + head = ef->next; + ef->next = NULL; + _zip_ef_free(ef); + + if (id_idx == ZIP_EXTRA_FIELD_ALL) + continue; + } + } + + i++; + if (i > id_idx) + break; + } + prev = ef; + } + + return head; +} + + +void +_zip_ef_free(zip_extra_field_t *ef) { + zip_extra_field_t *ef2; + + while (ef) { + ef2 = ef->next; + free(ef->data); + free(ef); + ef = ef2; + } +} + + +const zip_uint8_t * +_zip_ef_get_by_id(const zip_extra_field_t *ef, zip_uint16_t *lenp, zip_uint16_t id, zip_uint16_t id_idx, zip_flags_t flags, zip_error_t *error) { + static const zip_uint8_t empty[1] = {'\0'}; + + int i; + + i = 0; + for (; ef; ef = ef->next) { + if (ef->id == id && (ef->flags & flags & ZIP_EF_BOTH)) { + if (i < id_idx) { + i++; + continue; + } + + if (lenp) + *lenp = ef->size; + if (ef->size > 0) + return ef->data; + else + return empty; + } + } + + zip_error_set(error, ZIP_ER_NOENT, 0); + return NULL; +} + + +zip_extra_field_t * +_zip_ef_merge(zip_extra_field_t *to, zip_extra_field_t *from) { + zip_extra_field_t *ef2, *tt, *tail; + int duplicate; + + if (to == NULL) + return from; + + for (tail = to; tail->next; tail = tail->next) + ; + + for (; from; from = ef2) { + ef2 = from->next; + + duplicate = 0; + for (tt = to; tt; tt = tt->next) { + if (tt->id == from->id && tt->size == from->size && (tt->size == 0 || memcmp(tt->data, from->data, tt->size) == 0)) { + tt->flags |= (from->flags & ZIP_EF_BOTH); + duplicate = 1; + break; + } + } + + from->next = NULL; + if (duplicate) + _zip_ef_free(from); + else + tail = tail->next = from; + } + + return to; +} + + +zip_extra_field_t * +_zip_ef_new(zip_uint16_t id, zip_uint16_t size, const zip_uint8_t *data, zip_flags_t flags) { + zip_extra_field_t *ef; + + if ((ef = (zip_extra_field_t *)malloc(sizeof(*ef))) == NULL) + return NULL; + + ef->next = NULL; + ef->flags = flags; + ef->id = id; + ef->size = size; + if (size > 0) { + if ((ef->data = (zip_uint8_t *)_zip_memdup(data, size, NULL)) == NULL) { + free(ef); + return NULL; + } + } + else + ef->data = NULL; + + return ef; +} + + +bool +_zip_ef_parse(const zip_uint8_t *data, zip_uint16_t len, zip_flags_t flags, zip_extra_field_t **ef_head_p, zip_error_t *error) { + zip_buffer_t *buffer; + zip_extra_field_t *ef, *ef2, *ef_head; + + if ((buffer = _zip_buffer_new((zip_uint8_t *)data, len)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return false; + } + + ef_head = ef = NULL; + + while (_zip_buffer_ok(buffer) && _zip_buffer_left(buffer) >= 4) { + zip_uint16_t fid, flen; + zip_uint8_t *ef_data; + + fid = _zip_buffer_get_16(buffer); + flen = _zip_buffer_get_16(buffer); + ef_data = _zip_buffer_get(buffer, flen); + + if (ef_data == NULL) { + zip_error_set(error, ZIP_ER_INCONS, 0); + _zip_buffer_free(buffer); + _zip_ef_free(ef_head); + return false; + } + + if ((ef2 = _zip_ef_new(fid, flen, ef_data, flags)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + _zip_buffer_free(buffer); + _zip_ef_free(ef_head); + return false; + } + + if (ef_head) { + ef->next = ef2; + ef = ef2; + } + else + ef_head = ef = ef2; + } + + if (!_zip_buffer_eof(buffer)) { + /* Android APK files align stored file data with padding in extra fields; ignore. */ + /* see https://android.googlesource.com/platform/build/+/master/tools/zipalign/ZipAlign.cpp */ + size_t glen = _zip_buffer_left(buffer); + zip_uint8_t *garbage; + garbage = _zip_buffer_get(buffer, glen); + if (glen >= 4 || garbage == NULL || memcmp(garbage, "\0\0\0", glen) != 0) { + zip_error_set(error, ZIP_ER_INCONS, 0); + _zip_buffer_free(buffer); + _zip_ef_free(ef_head); + return false; + } + } + + _zip_buffer_free(buffer); + + if (ef_head_p) { + *ef_head_p = ef_head; + } + else { + _zip_ef_free(ef_head); + } + + return true; +} + + +zip_extra_field_t * +_zip_ef_remove_internal(zip_extra_field_t *ef) { + zip_extra_field_t *ef_head; + zip_extra_field_t *prev, *next; + + ef_head = ef; + prev = NULL; + + while (ef) { + if (ZIP_EF_IS_INTERNAL(ef->id)) { + next = ef->next; + if (ef_head == ef) + ef_head = next; + ef->next = NULL; + _zip_ef_free(ef); + if (prev) + prev->next = next; + ef = next; + } + else { + prev = ef; + ef = ef->next; + } + } + + return ef_head; +} + + +zip_uint16_t +_zip_ef_size(const zip_extra_field_t *ef, zip_flags_t flags) { + zip_uint16_t size; + + size = 0; + for (; ef; ef = ef->next) { + if (ef->flags & flags & ZIP_EF_BOTH) + size = (zip_uint16_t)(size + 4 + ef->size); + } + + return size; +} + + +int +_zip_ef_write(zip_t *za, const zip_extra_field_t *ef, zip_flags_t flags) { + zip_uint8_t b[4]; + zip_buffer_t *buffer = _zip_buffer_new(b, sizeof(b)); + + if (buffer == NULL) { + return -1; + } + + for (; ef; ef = ef->next) { + if (ef->flags & flags & ZIP_EF_BOTH) { + _zip_buffer_set_offset(buffer, 0); + _zip_buffer_put_16(buffer, ef->id); + _zip_buffer_put_16(buffer, ef->size); + if (!_zip_buffer_ok(buffer)) { + zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); + _zip_buffer_free(buffer); + return -1; + } + if (_zip_write(za, b, 4) < 0) { + _zip_buffer_free(buffer); + return -1; + } + if (ef->size > 0) { + if (_zip_write(za, ef->data, ef->size) < 0) { + _zip_buffer_free(buffer); + return -1; + } + } + } + } + + _zip_buffer_free(buffer); + return 0; +} + + +int +_zip_read_local_ef(zip_t *za, zip_uint64_t idx) { + zip_entry_t *e; + unsigned char b[4]; + zip_buffer_t *buffer; + zip_uint16_t fname_len, ef_len; + + if (idx >= za->nentry) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + e = za->entry + idx; + + if (e->orig == NULL || e->orig->local_extra_fields_read) + return 0; + + if (e->orig->offset + 26 > ZIP_INT64_MAX) { + zip_error_set(&za->error, ZIP_ER_SEEK, EFBIG); + return -1; + } + + if (zip_source_seek(za->src, (zip_int64_t)(e->orig->offset + 26), SEEK_SET) < 0) { + _zip_error_set_from_source(&za->error, za->src); + return -1; + } + + if ((buffer = _zip_buffer_new_from_source(za->src, sizeof(b), b, &za->error)) == NULL) { + return -1; + } + + fname_len = _zip_buffer_get_16(buffer); + ef_len = _zip_buffer_get_16(buffer); + + if (!_zip_buffer_eof(buffer)) { + _zip_buffer_free(buffer); + zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); + return -1; + } + + _zip_buffer_free(buffer); + + if (ef_len > 0) { + zip_extra_field_t *ef; + zip_uint8_t *ef_raw; + + if (zip_source_seek(za->src, fname_len, SEEK_CUR) < 0) { + zip_error_set(&za->error, ZIP_ER_SEEK, errno); + return -1; + } + + ef_raw = _zip_read_data(NULL, za->src, ef_len, 0, &za->error); + + if (ef_raw == NULL) + return -1; + + if (!_zip_ef_parse(ef_raw, ef_len, ZIP_EF_LOCAL, &ef, &za->error)) { + free(ef_raw); + return -1; + } + free(ef_raw); + + if (ef) { + ef = _zip_ef_remove_internal(ef); + e->orig->extra_fields = _zip_ef_merge(e->orig->extra_fields, ef); + } + } + + e->orig->local_extra_fields_read = 1; + + if (e->changes && e->changes->local_extra_fields_read == 0) { + e->changes->extra_fields = e->orig->extra_fields; + e->changes->local_extra_fields_read = 1; + } + + return 0; +} diff --git a/Source/Libraries/libzip/zip_extra_field_api.c b/Source/Libraries/libzip/zip_extra_field_api.c new file mode 100644 index 0000000..cf2b0e7 --- /dev/null +++ b/Source/Libraries/libzip/zip_extra_field_api.c @@ -0,0 +1,355 @@ +/* + zip_extra_field_api.c -- public extra fields API functions + Copyright (C) 2012-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_file_extra_field_delete(zip_t *za, zip_uint64_t idx, zip_uint16_t ef_idx, zip_flags_t flags) { + zip_dirent_t *de; + + if ((flags & ZIP_EF_BOTH) == 0) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (((flags & ZIP_EF_BOTH) == ZIP_EF_BOTH) && (ef_idx != ZIP_EXTRA_FIELD_ALL)) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (_zip_get_dirent(za, idx, 0, NULL) == NULL) + return -1; + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + if (_zip_file_extra_field_prepare_for_change(za, idx) < 0) + return -1; + + de = za->entry[idx].changes; + + de->extra_fields = _zip_ef_delete_by_id(de->extra_fields, ZIP_EXTRA_FIELD_ALL, ef_idx, flags); + return 0; +} + + +ZIP_EXTERN int +zip_file_extra_field_delete_by_id(zip_t *za, zip_uint64_t idx, zip_uint16_t ef_id, zip_uint16_t ef_idx, zip_flags_t flags) { + zip_dirent_t *de; + + if ((flags & ZIP_EF_BOTH) == 0) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (((flags & ZIP_EF_BOTH) == ZIP_EF_BOTH) && (ef_idx != ZIP_EXTRA_FIELD_ALL)) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (_zip_get_dirent(za, idx, 0, NULL) == NULL) + return -1; + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + if (_zip_file_extra_field_prepare_for_change(za, idx) < 0) + return -1; + + de = za->entry[idx].changes; + + de->extra_fields = _zip_ef_delete_by_id(de->extra_fields, ef_id, ef_idx, flags); + return 0; +} + + +ZIP_EXTERN const zip_uint8_t * +zip_file_extra_field_get(zip_t *za, zip_uint64_t idx, zip_uint16_t ef_idx, zip_uint16_t *idp, zip_uint16_t *lenp, zip_flags_t flags) { + static const zip_uint8_t empty[1] = {'\0'}; + + zip_dirent_t *de; + zip_extra_field_t *ef; + int i; + + if ((flags & ZIP_EF_BOTH) == 0) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return NULL; + } + + if ((de = _zip_get_dirent(za, idx, flags, &za->error)) == NULL) + return NULL; + + if (flags & ZIP_FL_LOCAL) + if (_zip_read_local_ef(za, idx) < 0) + return NULL; + + i = 0; + for (ef = de->extra_fields; ef; ef = ef->next) { + if (ef->flags & flags & ZIP_EF_BOTH) { + if (i < ef_idx) { + i++; + continue; + } + + if (idp) + *idp = ef->id; + if (lenp) + *lenp = ef->size; + if (ef->size > 0) + return ef->data; + else + return empty; + } + } + + zip_error_set(&za->error, ZIP_ER_NOENT, 0); + return NULL; +} + + +ZIP_EXTERN const zip_uint8_t * +zip_file_extra_field_get_by_id(zip_t *za, zip_uint64_t idx, zip_uint16_t ef_id, zip_uint16_t ef_idx, zip_uint16_t *lenp, zip_flags_t flags) { + zip_dirent_t *de; + + if ((flags & ZIP_EF_BOTH) == 0) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return NULL; + } + + if ((de = _zip_get_dirent(za, idx, flags, &za->error)) == NULL) + return NULL; + + if (flags & ZIP_FL_LOCAL) + if (_zip_read_local_ef(za, idx) < 0) + return NULL; + + return _zip_ef_get_by_id(de->extra_fields, lenp, ef_id, ef_idx, flags, &za->error); +} + + +ZIP_EXTERN zip_int16_t +zip_file_extra_fields_count(zip_t *za, zip_uint64_t idx, zip_flags_t flags) { + zip_dirent_t *de; + zip_extra_field_t *ef; + zip_uint16_t n; + + if ((flags & ZIP_EF_BOTH) == 0) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if ((de = _zip_get_dirent(za, idx, flags, &za->error)) == NULL) + return -1; + + if (flags & ZIP_FL_LOCAL) + if (_zip_read_local_ef(za, idx) < 0) + return -1; + + n = 0; + for (ef = de->extra_fields; ef; ef = ef->next) + if (ef->flags & flags & ZIP_EF_BOTH) + n++; + + return (zip_int16_t)n; +} + + +ZIP_EXTERN zip_int16_t +zip_file_extra_fields_count_by_id(zip_t *za, zip_uint64_t idx, zip_uint16_t ef_id, zip_flags_t flags) { + zip_dirent_t *de; + zip_extra_field_t *ef; + zip_uint16_t n; + + if ((flags & ZIP_EF_BOTH) == 0) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if ((de = _zip_get_dirent(za, idx, flags, &za->error)) == NULL) + return -1; + + if (flags & ZIP_FL_LOCAL) + if (_zip_read_local_ef(za, idx) < 0) + return -1; + + n = 0; + for (ef = de->extra_fields; ef; ef = ef->next) + if (ef->id == ef_id && (ef->flags & flags & ZIP_EF_BOTH)) + n++; + + return (zip_int16_t)n; +} + + +ZIP_EXTERN int +zip_file_extra_field_set(zip_t *za, zip_uint64_t idx, zip_uint16_t ef_id, zip_uint16_t ef_idx, const zip_uint8_t *data, zip_uint16_t len, zip_flags_t flags) { + zip_dirent_t *de; + zip_uint16_t ls, cs; + zip_extra_field_t *ef, *ef_prev, *ef_new; + int i, found, new_len; + + if ((flags & ZIP_EF_BOTH) == 0) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (_zip_get_dirent(za, idx, 0, NULL) == NULL) + return -1; + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + if (ZIP_EF_IS_INTERNAL(ef_id)) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (_zip_file_extra_field_prepare_for_change(za, idx) < 0) + return -1; + + de = za->entry[idx].changes; + + ef = de->extra_fields; + ef_prev = NULL; + i = 0; + found = 0; + + for (; ef; ef = ef->next) { + if (ef->id == ef_id && (ef->flags & flags & ZIP_EF_BOTH)) { + if (i == ef_idx) { + found = 1; + break; + } + i++; + } + ef_prev = ef; + } + + if (i < ef_idx && ef_idx != ZIP_EXTRA_FIELD_NEW) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (flags & ZIP_EF_LOCAL) + ls = _zip_ef_size(de->extra_fields, ZIP_EF_LOCAL); + else + ls = 0; + if (flags & ZIP_EF_CENTRAL) + cs = _zip_ef_size(de->extra_fields, ZIP_EF_CENTRAL); + else + cs = 0; + + new_len = ls > cs ? ls : cs; + if (found) + new_len -= ef->size + 4; + new_len += len + 4; + + if (new_len > ZIP_UINT16_MAX) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if ((ef_new = _zip_ef_new(ef_id, len, data, flags)) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + + if (found) { + if ((ef->flags & ZIP_EF_BOTH) == (flags & ZIP_EF_BOTH)) { + ef_new->next = ef->next; + ef->next = NULL; + _zip_ef_free(ef); + if (ef_prev) + ef_prev->next = ef_new; + else + de->extra_fields = ef_new; + } + else { + ef->flags &= ~(flags & ZIP_EF_BOTH); + ef_new->next = ef->next; + ef->next = ef_new; + } + } + else if (ef_prev) { + ef_new->next = ef_prev->next; + ef_prev->next = ef_new; + } + else + de->extra_fields = ef_new; + + return 0; +} + + +int +_zip_file_extra_field_prepare_for_change(zip_t *za, zip_uint64_t idx) { + zip_entry_t *e; + + if (idx >= za->nentry) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + e = za->entry + idx; + + if (e->changes && (e->changes->changed & ZIP_DIRENT_EXTRA_FIELD)) + return 0; + + if (e->orig) { + if (_zip_read_local_ef(za, idx) < 0) + return -1; + } + + if (e->changes == NULL) { + if ((e->changes = _zip_dirent_clone(e->orig)) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + } + + if (e->orig && e->orig->extra_fields) { + if ((e->changes->extra_fields = _zip_ef_clone(e->orig->extra_fields, &za->error)) == NULL) + return -1; + } + e->changes->changed |= ZIP_DIRENT_EXTRA_FIELD; + + return 0; +} diff --git a/Source/Libraries/libzip/zip_fclose.c b/Source/Libraries/libzip/zip_fclose.c new file mode 100644 index 0000000..4d6fc59 --- /dev/null +++ b/Source/Libraries/libzip/zip_fclose.c @@ -0,0 +1,54 @@ +/* + zip_fclose.c -- close file in zip archive + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_fclose(zip_file_t *zf) { + int ret; + + if (zf->src) + zip_source_free(zf->src); + + ret = 0; + if (zf->error.zip_err) + ret = zf->error.zip_err; + + zip_error_fini(&zf->error); + free(zf); + return ret; +} diff --git a/Source/Libraries/libzip/zip_fdopen.c b/Source/Libraries/libzip/zip_fdopen.c new file mode 100644 index 0000000..14f243f --- /dev/null +++ b/Source/Libraries/libzip/zip_fdopen.c @@ -0,0 +1,86 @@ +/* + zip_fdopen.c -- open read-only archive from file descriptor + Copyright (C) 2009-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" +#ifdef HAVE_UNISTD_H +#include +#endif + + +ZIP_EXTERN zip_t * +zip_fdopen(int fd_orig, int _flags, int *zep) { + int fd; + FILE *fp; + zip_t *za; + zip_source_t *src; + struct zip_error error; + + if (_flags < 0 || (_flags & ~(ZIP_CHECKCONS | ZIP_RDONLY))) { + _zip_set_open_error(zep, NULL, ZIP_ER_INVAL); + return NULL; + } + + /* We dup() here to avoid messing with the passed in fd. + We could not restore it to the original state in case of error. */ + + if ((fd = dup(fd_orig)) < 0) { + _zip_set_open_error(zep, NULL, ZIP_ER_OPEN); + return NULL; + } + + if ((fp = fdopen(fd, "rb")) == NULL) { + close(fd); + _zip_set_open_error(zep, NULL, ZIP_ER_OPEN); + return NULL; + } + + zip_error_init(&error); + if ((src = zip_source_filep_create(fp, 0, -1, &error)) == NULL) { + fclose(fp); + _zip_set_open_error(zep, &error, 0); + zip_error_fini(&error); + return NULL; + } + + if ((za = zip_open_from_source(src, _flags, &error)) == NULL) { + zip_source_free(src); + _zip_set_open_error(zep, &error, 0); + zip_error_fini(&error); + return NULL; + } + + zip_error_fini(&error); + close(fd_orig); + return za; +} diff --git a/Source/Libraries/libzip/zip_file_add.c b/Source/Libraries/libzip/zip_file_add.c new file mode 100644 index 0000000..40386c0 --- /dev/null +++ b/Source/Libraries/libzip/zip_file_add.c @@ -0,0 +1,52 @@ +/* + zip_file_add.c -- add file via callback function + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +/* + NOTE: Return type is signed so we can return -1 on error. + The index can not be larger than ZIP_INT64_MAX since the size + of the central directory cannot be larger than + ZIP_UINT64_MAX, and each entry is larger than 2 bytes. +*/ + +ZIP_EXTERN zip_int64_t +zip_file_add(zip_t *za, const char *name, zip_source_t *source, zip_flags_t flags) { + if (name == NULL || source == NULL) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + return _zip_file_replace(za, ZIP_UINT64_MAX, name, source, flags); +} diff --git a/Source/Libraries/libzip/zip_file_error_clear.c b/Source/Libraries/libzip/zip_file_error_clear.c new file mode 100644 index 0000000..863dae7 --- /dev/null +++ b/Source/Libraries/libzip/zip_file_error_clear.c @@ -0,0 +1,44 @@ +/* + zip_file_error_clear.c -- clear zip file error + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN void +zip_file_error_clear(zip_file_t *zf) { + if (zf == NULL) + return; + + _zip_error_clear(&zf->error); +} diff --git a/Source/Libraries/libzip/zip_file_error_get.c b/Source/Libraries/libzip/zip_file_error_get.c new file mode 100644 index 0000000..a477976 --- /dev/null +++ b/Source/Libraries/libzip/zip_file_error_get.c @@ -0,0 +1,41 @@ +/* + zip_file_error_get.c -- get zip file error + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + +#define _ZIP_COMPILING_DEPRECATED +#include "zipint.h" + + +ZIP_EXTERN void +zip_file_error_get(zip_file_t *zf, int *zep, int *sep) { + _zip_error_get(&zf->error, zep, sep); +} diff --git a/Source/Libraries/libzip/zip_file_get_comment.c b/Source/Libraries/libzip/zip_file_get_comment.c new file mode 100644 index 0000000..746186a --- /dev/null +++ b/Source/Libraries/libzip/zip_file_get_comment.c @@ -0,0 +1,55 @@ +/* + zip_file_get_comment.c -- get file comment + Copyright (C) 2006-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +/* lenp is 32 bit because converted comment can be longer than ZIP_UINT16_MAX */ + +ZIP_EXTERN const char * +zip_file_get_comment(zip_t *za, zip_uint64_t idx, zip_uint32_t *lenp, zip_flags_t flags) { + zip_dirent_t *de; + zip_uint32_t len; + const zip_uint8_t *str; + + if ((de = _zip_get_dirent(za, idx, flags, NULL)) == NULL) + return NULL; + + if ((str = _zip_string_get(de->comment, &len, flags, &za->error)) == NULL) + return NULL; + + if (lenp) + *lenp = len; + + return (const char *)str; +} diff --git a/Source/Libraries/libzip/zip_file_get_external_attributes.c b/Source/Libraries/libzip/zip_file_get_external_attributes.c new file mode 100644 index 0000000..6d4e0e4 --- /dev/null +++ b/Source/Libraries/libzip/zip_file_get_external_attributes.c @@ -0,0 +1,50 @@ +/* + zip_file_get_external_attributes.c -- get opsys/external attributes + Copyright (C) 2013-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +int +zip_file_get_external_attributes(zip_t *za, zip_uint64_t idx, zip_flags_t flags, zip_uint8_t *opsys, zip_uint32_t *attributes) { + zip_dirent_t *de; + + if ((de = _zip_get_dirent(za, idx, flags, NULL)) == NULL) + return -1; + + if (opsys) + *opsys = (zip_uint8_t)((de->version_madeby >> 8) & 0xff); + + if (attributes) + *attributes = de->ext_attrib; + + return 0; +} diff --git a/Source/Libraries/libzip/zip_file_get_offset.c b/Source/Libraries/libzip/zip_file_get_offset.c new file mode 100644 index 0000000..eb9b017 --- /dev/null +++ b/Source/Libraries/libzip/zip_file_get_offset.c @@ -0,0 +1,117 @@ +/* + zip_file_get_offset.c -- get offset of file data in archive. + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +/* _zip_file_get_offset(za, ze): + Returns the offset of the file data for entry ze. + + On error, fills in za->error and returns 0. +*/ + +zip_uint64_t +_zip_file_get_offset(const zip_t *za, zip_uint64_t idx, zip_error_t *error) { + zip_uint64_t offset; + zip_int32_t size; + + if (za->entry[idx].orig == NULL) { + zip_error_set(error, ZIP_ER_INTERNAL, 0); + return 0; + } + + offset = za->entry[idx].orig->offset; + + if (zip_source_seek(za->src, (zip_int64_t)offset, SEEK_SET) < 0) { + _zip_error_set_from_source(error, za->src); + return 0; + } + + /* TODO: cache? */ + if ((size = _zip_dirent_size(za->src, ZIP_EF_LOCAL, error)) < 0) + return 0; + + if (offset + (zip_uint32_t)size > ZIP_INT64_MAX) { + zip_error_set(error, ZIP_ER_SEEK, EFBIG); + return 0; + } + + return offset + (zip_uint32_t)size; +} + +zip_uint64_t +_zip_file_get_end(const zip_t *za, zip_uint64_t index, zip_error_t *error) { + zip_uint64_t offset; + zip_dirent_t *entry; + + if ((offset = _zip_file_get_offset(za, index, error)) == 0) { + return 0; + } + + entry = za->entry[index].orig; + + if (offset + entry->comp_size < offset || offset + entry->comp_size > ZIP_INT64_MAX) { + zip_error_set(error, ZIP_ER_SEEK, EFBIG); + return 0; + } + offset += entry->comp_size; + + if (entry->bitflags & ZIP_GPBF_DATA_DESCRIPTOR) { + zip_uint8_t buf[4]; + if (zip_source_seek(za->src, (zip_int64_t)offset, SEEK_SET) < 0) { + _zip_error_set_from_source(error, za->src); + return 0; + } + if (zip_source_read(za->src, buf, 4) != 4) { + _zip_error_set_from_source(error, za->src); + return 0; + } + if (memcmp(buf, DATADES_MAGIC, 4) == 0) { + offset += 4; + } + offset += 12; + if (_zip_dirent_needs_zip64(entry, 0)) { + offset += 8; + } + if (offset > ZIP_INT64_MAX) { + zip_error_set(error, ZIP_ER_SEEK, EFBIG); + return 0; + } + } + + return offset; +} diff --git a/Source/Libraries/libzip/zip_file_rename.c b/Source/Libraries/libzip/zip_file_rename.c new file mode 100644 index 0000000..a830b6a --- /dev/null +++ b/Source/Libraries/libzip/zip_file_rename.c @@ -0,0 +1,67 @@ +/* + zip_file_rename.c -- rename file in zip archive + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_file_rename(zip_t *za, zip_uint64_t idx, const char *name, zip_flags_t flags) { + const char *old_name; + int old_is_dir, new_is_dir; + + if (idx >= za->nentry || (name != NULL && strlen(name) > ZIP_UINT16_MAX)) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + if ((old_name = zip_get_name(za, idx, 0)) == NULL) + return -1; + + new_is_dir = (name != NULL && name[strlen(name) - 1] == '/'); + old_is_dir = (old_name[strlen(old_name) - 1] == '/'); + + if (new_is_dir != old_is_dir) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + return _zip_set_name(za, idx, name, flags); +} diff --git a/Source/Libraries/libzip/zip_file_replace.c b/Source/Libraries/libzip/zip_file_replace.c new file mode 100644 index 0000000..c824d7f --- /dev/null +++ b/Source/Libraries/libzip/zip_file_replace.c @@ -0,0 +1,105 @@ +/* + zip_file_replace.c -- replace file via callback function + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_file_replace(zip_t *za, zip_uint64_t idx, zip_source_t *source, zip_flags_t flags) { + if (idx >= za->nentry || source == NULL) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (_zip_file_replace(za, idx, NULL, source, flags) == -1) + return -1; + + return 0; +} + + +/* NOTE: Signed due to -1 on error. See zip_add.c for more details. */ + +zip_int64_t +_zip_file_replace(zip_t *za, zip_uint64_t idx, const char *name, zip_source_t *source, zip_flags_t flags) { + zip_uint64_t za_nentry_prev; + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + za_nentry_prev = za->nentry; + if (idx == ZIP_UINT64_MAX) { + zip_int64_t i = -1; + + if (flags & ZIP_FL_OVERWRITE) + i = _zip_name_locate(za, name, flags, NULL); + + if (i == -1) { + /* create and use new entry, used by zip_add */ + if ((i = _zip_add_entry(za)) < 0) + return -1; + } + idx = (zip_uint64_t)i; + } + + if (name && _zip_set_name(za, idx, name, flags) != 0) { + if (za->nentry != za_nentry_prev) { + _zip_entry_finalize(za->entry + idx); + za->nentry = za_nentry_prev; + } + return -1; + } + + /* does not change any name related data, so we can do it here; + * needed for a double add of the same file name */ + _zip_unchange_data(za->entry + idx); + + if (za->entry[idx].orig != NULL && (za->entry[idx].changes == NULL || (za->entry[idx].changes->changed & ZIP_DIRENT_COMP_METHOD) == 0)) { + if (za->entry[idx].changes == NULL) { + if ((za->entry[idx].changes = _zip_dirent_clone(za->entry[idx].orig)) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + } + + za->entry[idx].changes->comp_method = ZIP_CM_REPLACED_DEFAULT; + za->entry[idx].changes->changed |= ZIP_DIRENT_COMP_METHOD; + } + + za->entry[idx].source = source; + + return (zip_int64_t)idx; +} diff --git a/Source/Libraries/libzip/zip_file_set_comment.c b/Source/Libraries/libzip/zip_file_set_comment.c new file mode 100644 index 0000000..8c76f25 --- /dev/null +++ b/Source/Libraries/libzip/zip_file_set_comment.c @@ -0,0 +1,101 @@ +/* + zip_file_set_comment.c -- set comment for file in archive + Copyright (C) 2006-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_file_set_comment(zip_t *za, zip_uint64_t idx, const char *comment, zip_uint16_t len, zip_flags_t flags) { + zip_entry_t *e; + zip_string_t *cstr; + int changed; + + if (_zip_get_dirent(za, idx, 0, NULL) == NULL) + return -1; + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + if (len > 0 && comment == NULL) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (len > 0) { + if ((cstr = _zip_string_new((const zip_uint8_t *)comment, len, flags, &za->error)) == NULL) + return -1; + if ((flags & ZIP_FL_ENCODING_ALL) == ZIP_FL_ENC_GUESS && _zip_guess_encoding(cstr, ZIP_ENCODING_UNKNOWN) == ZIP_ENCODING_UTF8_GUESSED) + cstr->encoding = ZIP_ENCODING_UTF8_KNOWN; + } + else + cstr = NULL; + + e = za->entry + idx; + + if (e->changes) { + _zip_string_free(e->changes->comment); + e->changes->comment = NULL; + e->changes->changed &= ~ZIP_DIRENT_COMMENT; + } + + if (e->orig && e->orig->comment) + changed = !_zip_string_equal(e->orig->comment, cstr); + else + changed = (cstr != NULL); + + if (changed) { + if (e->changes == NULL) { + if ((e->changes = _zip_dirent_clone(e->orig)) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + _zip_string_free(cstr); + return -1; + } + } + e->changes->comment = cstr; + e->changes->changed |= ZIP_DIRENT_COMMENT; + } + else { + _zip_string_free(cstr); + if (e->changes && e->changes->changed == 0) { + _zip_dirent_free(e->changes); + e->changes = NULL; + } + } + + return 0; +} diff --git a/Source/Libraries/libzip/zip_file_set_encryption.c b/Source/Libraries/libzip/zip_file_set_encryption.c new file mode 100644 index 0000000..6025e4a --- /dev/null +++ b/Source/Libraries/libzip/zip_file_set_encryption.c @@ -0,0 +1,116 @@ +/* + zip_file_set_encryption.c -- set encryption for file in archive + Copyright (C) 2016-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +#include +#include + +ZIP_EXTERN int +zip_file_set_encryption(zip_t *za, zip_uint64_t idx, zip_uint16_t method, const char *password) { + zip_entry_t *e; + zip_uint16_t old_method; + + if (idx >= za->nentry) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + if (method != ZIP_EM_NONE && _zip_get_encryption_implementation(method, ZIP_CODEC_ENCODE) == NULL) { + zip_error_set(&za->error, ZIP_ER_ENCRNOTSUPP, 0); + return -1; + } + + e = za->entry + idx; + + old_method = (e->orig == NULL ? ZIP_EM_NONE : e->orig->encryption_method); + + if (method == old_method && password == NULL) { + if (e->changes) { + if (e->changes->changed & ZIP_DIRENT_PASSWORD) { + _zip_crypto_clear(e->changes->password, strlen(e->changes->password)); + free(e->changes->password); + e->changes->password = (e->orig == NULL ? NULL : e->orig->password); + } + e->changes->changed &= ~(ZIP_DIRENT_ENCRYPTION_METHOD | ZIP_DIRENT_PASSWORD); + if (e->changes->changed == 0) { + _zip_dirent_free(e->changes); + e->changes = NULL; + } + } + } + else { + char *our_password = NULL; + + if (password) { + if ((our_password = strdup(password)) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + } + + if (e->changes == NULL) { + if ((e->changes = _zip_dirent_clone(e->orig)) == NULL) { + if (our_password) { + _zip_crypto_clear(our_password, strlen(our_password)); + } + free(our_password); + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + } + + e->changes->encryption_method = method; + e->changes->changed |= ZIP_DIRENT_ENCRYPTION_METHOD; + if (password) { + e->changes->password = our_password; + e->changes->changed |= ZIP_DIRENT_PASSWORD; + } + else { + if (e->changes->changed & ZIP_DIRENT_PASSWORD) { + _zip_crypto_clear(e->changes->password, strlen(e->changes->password)); + free(e->changes->password); + e->changes->password = e->orig ? e->orig->password : NULL; + e->changes->changed &= ~ZIP_DIRENT_PASSWORD; + } + } + } + + return 0; +} diff --git a/Source/Libraries/libzip/zip_file_set_external_attributes.c b/Source/Libraries/libzip/zip_file_set_external_attributes.c new file mode 100644 index 0000000..0662f60 --- /dev/null +++ b/Source/Libraries/libzip/zip_file_set_external_attributes.c @@ -0,0 +1,82 @@ +/* + zip_file_set_external_attributes.c -- set external attributes for entry + Copyright (C) 2013-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +ZIP_EXTERN int +zip_file_set_external_attributes(zip_t *za, zip_uint64_t idx, zip_flags_t flags, zip_uint8_t opsys, zip_uint32_t attributes) { + zip_entry_t *e; + int changed; + zip_uint8_t unchanged_opsys; + zip_uint32_t unchanged_attributes; + + if (_zip_get_dirent(za, idx, 0, NULL) == NULL) + return -1; + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + e = za->entry + idx; + + unchanged_opsys = (e->orig ? (zip_uint8_t)(e->orig->version_madeby >> 8) : (zip_uint8_t)ZIP_OPSYS_DEFAULT); + unchanged_attributes = e->orig ? e->orig->ext_attrib : ZIP_EXT_ATTRIB_DEFAULT; + + changed = (opsys != unchanged_opsys || attributes != unchanged_attributes); + + if (changed) { + if (e->changes == NULL) { + if ((e->changes = _zip_dirent_clone(e->orig)) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + } + e->changes->version_madeby = (zip_uint16_t)((opsys << 8) | (e->changes->version_madeby & 0xff)); + e->changes->ext_attrib = attributes; + e->changes->changed |= ZIP_DIRENT_ATTRIBUTES; + } + else if (e->changes) { + e->changes->changed &= ~ZIP_DIRENT_ATTRIBUTES; + if (e->changes->changed == 0) { + _zip_dirent_free(e->changes); + e->changes = NULL; + } + else { + e->changes->version_madeby = (zip_uint16_t)((unchanged_opsys << 8) | (e->changes->version_madeby & 0xff)); + e->changes->ext_attrib = unchanged_attributes; + } + } + + return 0; +} diff --git a/Source/Libraries/libzip/zip_file_set_mtime.c b/Source/Libraries/libzip/zip_file_set_mtime.c new file mode 100644 index 0000000..2753d59 --- /dev/null +++ b/Source/Libraries/libzip/zip_file_set_mtime.c @@ -0,0 +1,68 @@ +/* + zip_file_set_mtime.c -- set modification time of entry. + Copyright (C) 2014-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +ZIP_EXTERN int +zip_file_set_dostime(zip_t *za, zip_uint64_t idx, zip_uint16_t dtime, zip_uint16_t ddate, zip_flags_t flags) { + time_t mtime; + mtime = _zip_d2u_time(dtime, ddate); + return zip_file_set_mtime(za, idx, mtime, flags); +} + +ZIP_EXTERN int +zip_file_set_mtime(zip_t *za, zip_uint64_t idx, time_t mtime, zip_flags_t flags) { + zip_entry_t *e; + + if (_zip_get_dirent(za, idx, 0, NULL) == NULL) + return -1; + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + e = za->entry + idx; + + if (e->changes == NULL) { + if ((e->changes = _zip_dirent_clone(e->orig)) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + } + + e->changes->last_mod = mtime; + e->changes->changed |= ZIP_DIRENT_LAST_MOD; + + return 0; +} diff --git a/Source/Libraries/libzip/zip_file_strerror.c b/Source/Libraries/libzip/zip_file_strerror.c new file mode 100644 index 0000000..2dcdba7 --- /dev/null +++ b/Source/Libraries/libzip/zip_file_strerror.c @@ -0,0 +1,41 @@ +/* + zip_file_sterror.c -- get string representation of zip file error + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN const char * +zip_file_strerror(zip_file_t *zf) { + return zip_error_strerror(&zf->error); +} diff --git a/Source/Libraries/libzip/zip_fopen.c b/Source/Libraries/libzip/zip_fopen.c new file mode 100644 index 0000000..2da0cc5 --- /dev/null +++ b/Source/Libraries/libzip/zip_fopen.c @@ -0,0 +1,46 @@ +/* + zip_fopen.c -- open file in zip archive for reading + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN zip_file_t * +zip_fopen(zip_t *za, const char *fname, zip_flags_t flags) { + zip_int64_t idx; + + if ((idx = zip_name_locate(za, fname, flags)) < 0) + return NULL; + + return zip_fopen_index_encrypted(za, (zip_uint64_t)idx, flags, za->default_password); +} diff --git a/Source/Libraries/libzip/zip_fopen_encrypted.c b/Source/Libraries/libzip/zip_fopen_encrypted.c new file mode 100644 index 0000000..8016015 --- /dev/null +++ b/Source/Libraries/libzip/zip_fopen_encrypted.c @@ -0,0 +1,46 @@ +/* + zip_fopen_encrypted.c -- open file for reading with password + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN zip_file_t * +zip_fopen_encrypted(zip_t *za, const char *fname, zip_flags_t flags, const char *password) { + zip_int64_t idx; + + if ((idx = zip_name_locate(za, fname, flags)) < 0) + return NULL; + + return zip_fopen_index_encrypted(za, (zip_uint64_t)idx, flags, password); +} diff --git a/Source/Libraries/libzip/zip_fopen_index.c b/Source/Libraries/libzip/zip_fopen_index.c new file mode 100644 index 0000000..5fd5f1a --- /dev/null +++ b/Source/Libraries/libzip/zip_fopen_index.c @@ -0,0 +1,41 @@ +/* + zip_fopen_index.c -- open file in zip archive for reading by index + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN zip_file_t * +zip_fopen_index(zip_t *za, zip_uint64_t index, zip_flags_t flags) { + return zip_fopen_index_encrypted(za, index, flags, za->default_password); +} diff --git a/Source/Libraries/libzip/zip_fopen_index_encrypted.c b/Source/Libraries/libzip/zip_fopen_index_encrypted.c new file mode 100644 index 0000000..280a5bd --- /dev/null +++ b/Source/Libraries/libzip/zip_fopen_index_encrypted.c @@ -0,0 +1,87 @@ +/* + zip_fopen_index_encrypted.c -- open file for reading by index w/ password + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +static zip_file_t *_zip_file_new(zip_t *za); + + +ZIP_EXTERN zip_file_t * +zip_fopen_index_encrypted(zip_t *za, zip_uint64_t index, zip_flags_t flags, const char *password) { + zip_file_t *zf; + zip_source_t *src; + + if (password != NULL && password[0] == '\0') { + password = NULL; + } + + if ((src = _zip_source_zip_new(za, za, index, flags, 0, 0, password)) == NULL) + return NULL; + + if (zip_source_open(src) < 0) { + _zip_error_set_from_source(&za->error, src); + zip_source_free(src); + return NULL; + } + + if ((zf = _zip_file_new(za)) == NULL) { + zip_source_free(src); + return NULL; + } + + zf->src = src; + + return zf; +} + + +static zip_file_t * +_zip_file_new(zip_t *za) { + zip_file_t *zf; + + if ((zf = (zip_file_t *)malloc(sizeof(struct zip_file))) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return NULL; + } + + zf->za = za; + zip_error_init(&zf->error); + zf->eof = 0; + zf->src = NULL; + + return zf; +} diff --git a/Source/Libraries/libzip/zip_fread.c b/Source/Libraries/libzip/zip_fread.c new file mode 100644 index 0000000..ecf0c3b --- /dev/null +++ b/Source/Libraries/libzip/zip_fread.c @@ -0,0 +1,62 @@ +/* + zip_fread.c -- read from file + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN zip_int64_t +zip_fread(zip_file_t *zf, void *outbuf, zip_uint64_t toread) { + zip_int64_t n; + + if (!zf) + return -1; + + if (zf->error.zip_err != 0) + return -1; + + if (toread > ZIP_INT64_MAX) { + zip_error_set(&zf->error, ZIP_ER_INVAL, 0); + return -1; + } + + if ((zf->eof) || (toread == 0)) + return 0; + + if ((n = zip_source_read(zf->src, outbuf, toread)) < 0) { + _zip_error_set_from_source(&zf->error, zf->src); + return -1; + } + + return n; +} diff --git a/Source/Libraries/libzip/zip_fseek.c b/Source/Libraries/libzip/zip_fseek.c new file mode 100644 index 0000000..21f344a --- /dev/null +++ b/Source/Libraries/libzip/zip_fseek.c @@ -0,0 +1,51 @@ +/* + zip_fseek.c -- seek in file + Copyright (C) 2016-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +ZIP_EXTERN zip_int8_t +zip_fseek(zip_file_t *zf, zip_int64_t offset, int whence) { + if (!zf) + return -1; + + if (zf->error.zip_err != 0) + return -1; + + if (zip_source_seek(zf->src, offset, whence) < 0) { + _zip_error_set_from_source(&zf->error, zf->src); + return -1; + } + + return 0; +} diff --git a/Source/Libraries/libzip/zip_ftell.c b/Source/Libraries/libzip/zip_ftell.c new file mode 100644 index 0000000..2b36770 --- /dev/null +++ b/Source/Libraries/libzip/zip_ftell.c @@ -0,0 +1,54 @@ +/* + zip_ftell.c -- tell position in file + Copyright (C) 2016-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +ZIP_EXTERN zip_int64_t +zip_ftell(zip_file_t *zf) { + zip_int64_t res; + + if (!zf) + return -1; + + if (zf->error.zip_err != 0) + return -1; + + res = zip_source_tell(zf->src); + if (res < 0) { + _zip_error_set_from_source(&zf->error, zf->src); + return -1; + } + + return res; +} diff --git a/Source/Libraries/libzip/zip_get_archive_comment.c b/Source/Libraries/libzip/zip_get_archive_comment.c new file mode 100644 index 0000000..18a4b61 --- /dev/null +++ b/Source/Libraries/libzip/zip_get_archive_comment.c @@ -0,0 +1,58 @@ +/* + zip_get_archive_comment.c -- get archive comment + Copyright (C) 2006-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN const char * +zip_get_archive_comment(zip_t *za, int *lenp, zip_flags_t flags) { + zip_string_t *comment; + zip_uint32_t len; + const zip_uint8_t *str; + + if ((flags & ZIP_FL_UNCHANGED) || (za->comment_changes == NULL)) + comment = za->comment_orig; + else + comment = za->comment_changes; + + if ((str = _zip_string_get(comment, &len, flags, &za->error)) == NULL) + return NULL; + + if (lenp) + *lenp = (int)len; + + return (const char *)str; +} diff --git a/Source/Libraries/libzip/zip_get_archive_flag.c b/Source/Libraries/libzip/zip_get_archive_flag.c new file mode 100644 index 0000000..3185ac5 --- /dev/null +++ b/Source/Libraries/libzip/zip_get_archive_flag.c @@ -0,0 +1,45 @@ +/* + zip_get_archive_flag.c -- get archive global flag + Copyright (C) 2008-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_get_archive_flag(zip_t *za, zip_flags_t flag, zip_flags_t flags) { + unsigned int fl; + + fl = (flags & ZIP_FL_UNCHANGED) ? za->flags : za->ch_flags; + + return (fl & flag) ? 1 : 0; +} diff --git a/Source/Libraries/libzip/zip_get_encryption_implementation.c b/Source/Libraries/libzip/zip_get_encryption_implementation.c new file mode 100644 index 0000000..3270b84 --- /dev/null +++ b/Source/Libraries/libzip/zip_get_encryption_implementation.c @@ -0,0 +1,61 @@ +/* + zip_get_encryption_implementation.c -- get encryption implementation + Copyright (C) 2009-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +zip_encryption_implementation +_zip_get_encryption_implementation(zip_uint16_t em, int operation) { + switch (em) { + case ZIP_EM_TRAD_PKWARE: + return operation == ZIP_CODEC_DECODE ? zip_source_pkware_decode : zip_source_pkware_encode; + +#if defined(HAVE_CRYPTO) + case ZIP_EM_AES_128: + case ZIP_EM_AES_192: + case ZIP_EM_AES_256: + return operation == ZIP_CODEC_DECODE ? zip_source_winzip_aes_decode : zip_source_winzip_aes_encode; +#endif + + default: + return NULL; + } +} + +ZIP_EXTERN int +zip_encryption_method_supported(zip_uint16_t method, int encode) { + if (method == ZIP_EM_NONE) { + return 1; + } + return _zip_get_encryption_implementation(method, encode ? ZIP_CODEC_ENCODE : ZIP_CODEC_DECODE) != NULL; +} diff --git a/Source/Libraries/libzip/zip_get_file_comment.c b/Source/Libraries/libzip/zip_get_file_comment.c new file mode 100644 index 0000000..28429bc --- /dev/null +++ b/Source/Libraries/libzip/zip_get_file_comment.c @@ -0,0 +1,50 @@ +/* + zip_get_file_comment.c -- get file comment + Copyright (C) 2006-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + + +#define _ZIP_COMPILING_DEPRECATED +#include "zipint.h" + + +ZIP_EXTERN const char * +zip_get_file_comment(zip_t *za, zip_uint64_t idx, int *lenp, int flags) { + zip_uint32_t len; + const char *s; + + if ((s = zip_file_get_comment(za, idx, &len, (zip_flags_t)flags)) != NULL) { + if (lenp) + *lenp = (int)len; + } + + return s; +} diff --git a/Source/Libraries/libzip/zip_get_name.c b/Source/Libraries/libzip/zip_get_name.c new file mode 100644 index 0000000..1a4bab8 --- /dev/null +++ b/Source/Libraries/libzip/zip_get_name.c @@ -0,0 +1,58 @@ +/* + zip_get_name.c -- get filename for a file in zip file + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN const char * +zip_get_name(zip_t *za, zip_uint64_t idx, zip_flags_t flags) { + return _zip_get_name(za, idx, flags, &za->error); +} + + +const char * +_zip_get_name(zip_t *za, zip_uint64_t idx, zip_flags_t flags, zip_error_t *error) { + zip_dirent_t *de; + const zip_uint8_t *str; + + if ((de = _zip_get_dirent(za, idx, flags, error)) == NULL) + return NULL; + + if ((str = _zip_string_get(de->filename, NULL, flags, error)) == NULL) + return NULL; + + return (const char *)str; +} diff --git a/Source/Libraries/libzip/zip_get_num_entries.c b/Source/Libraries/libzip/zip_get_num_entries.c new file mode 100644 index 0000000..3b18c74 --- /dev/null +++ b/Source/Libraries/libzip/zip_get_num_entries.c @@ -0,0 +1,52 @@ +/* + zip_get_num_entries.c -- get number of entries in archive + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN zip_int64_t +zip_get_num_entries(zip_t *za, zip_flags_t flags) { + zip_uint64_t n; + + if (za == NULL) + return -1; + + if (flags & ZIP_FL_UNCHANGED) { + n = za->nentry; + while (n > 0 && za->entry[n - 1].orig == NULL) + --n; + return (zip_int64_t)n; + } + return (zip_int64_t)za->nentry; +} diff --git a/Source/Libraries/libzip/zip_get_num_files.c b/Source/Libraries/libzip/zip_get_num_files.c new file mode 100644 index 0000000..23d7c9c --- /dev/null +++ b/Source/Libraries/libzip/zip_get_num_files.c @@ -0,0 +1,51 @@ +/* + zip_get_num_files.c -- get number of files in archive + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + + +#define _ZIP_COMPILING_DEPRECATED +#include "zipint.h" +#include + + +ZIP_EXTERN int +zip_get_num_files(zip_t *za) { + if (za == NULL) + return -1; + + if (za->nentry > INT_MAX) { + zip_error_set(&za->error, ZIP_ER_OPNOTSUPP, 0); + return -1; + } + + return (int)za->nentry; +} diff --git a/Source/Libraries/libzip/zip_hash.c b/Source/Libraries/libzip/zip_hash.c new file mode 100644 index 0000000..56e8d78 --- /dev/null +++ b/Source/Libraries/libzip/zip_hash.c @@ -0,0 +1,410 @@ +/* + zip_hash.c -- hash table string -> uint64 + Copyright (C) 2015-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" +#include +#include + +/* parameter for the string hash function */ +#define HASH_MULTIPLIER 33 +#define HASH_START 5381 + +/* hash table's fill ratio is kept between these by doubling/halfing its size as necessary */ +#define HASH_MAX_FILL .75 +#define HASH_MIN_FILL .01 + +/* but hash table size is kept between these */ +#define HASH_MIN_SIZE 256 +#define HASH_MAX_SIZE 0x80000000ul + +struct zip_hash_entry { + const zip_uint8_t *name; + zip_int64_t orig_index; + zip_int64_t current_index; + struct zip_hash_entry *next; + zip_uint32_t hash_value; +}; +typedef struct zip_hash_entry zip_hash_entry_t; + +struct zip_hash { + zip_uint32_t table_size; + zip_uint64_t nentries; + zip_hash_entry_t **table; +}; + + +/* free list of entries */ +static void +free_list(zip_hash_entry_t *entry) { + while (entry != NULL) { + zip_hash_entry_t *next = entry->next; + free(entry); + entry = next; + } +} + + +/* compute hash of string, full 32 bit value */ +static zip_uint32_t +hash_string(const zip_uint8_t *name) { + zip_uint64_t value = HASH_START; + + if (name == NULL) { + return 0; + } + + while (*name != 0) { + value = (zip_uint64_t)(((value * HASH_MULTIPLIER) + (zip_uint8_t)*name) % 0x100000000ul); + name++; + } + + return (zip_uint32_t)value; +} + + +/* resize hash table; new_size must be a power of 2, can be larger or smaller than current size */ +static bool +hash_resize(zip_hash_t *hash, zip_uint32_t new_size, zip_error_t *error) { + zip_hash_entry_t **new_table; + + if (new_size == hash->table_size) { + return true; + } + + if ((new_table = (zip_hash_entry_t **)calloc(new_size, sizeof(zip_hash_entry_t *))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return false; + } + + if (hash->nentries > 0) { + zip_uint32_t i; + + for (i = 0; i < hash->table_size; i++) { + zip_hash_entry_t *entry = hash->table[i]; + while (entry) { + zip_hash_entry_t *next = entry->next; + + zip_uint32_t new_index = entry->hash_value % new_size; + + entry->next = new_table[new_index]; + new_table[new_index] = entry; + + entry = next; + } + } + } + + free(hash->table); + hash->table = new_table; + hash->table_size = new_size; + + return true; +} + + +static zip_uint32_t +size_for_capacity(zip_uint64_t capacity) { + double needed_size = capacity / HASH_MAX_FILL; + zip_uint32_t v; + + if (needed_size > ZIP_UINT32_MAX) { + v = ZIP_UINT32_MAX; + } + else { + v = (zip_uint32_t)needed_size; + } + + if (v > HASH_MAX_SIZE) { + return HASH_MAX_SIZE; + } + + /* From Bit Twiddling Hacks by Sean Eron Anderson + (http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2). */ + + v--; + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + v++; + + return v; +} + + +zip_hash_t * +_zip_hash_new(zip_error_t *error) { + zip_hash_t *hash; + + if ((hash = (zip_hash_t *)malloc(sizeof(zip_hash_t))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + hash->table_size = 0; + hash->nentries = 0; + hash->table = NULL; + + return hash; +} + + +void +_zip_hash_free(zip_hash_t *hash) { + zip_uint32_t i; + + if (hash == NULL) { + return; + } + + if (hash->table != NULL) { + for (i = 0; i < hash->table_size; i++) { + if (hash->table[i] != NULL) { + free_list(hash->table[i]); + } + } + free(hash->table); + } + free(hash); +} + + +/* insert into hash, return error on existence or memory issues */ +bool +_zip_hash_add(zip_hash_t *hash, const zip_uint8_t *name, zip_uint64_t index, zip_flags_t flags, zip_error_t *error) { + zip_uint32_t hash_value, table_index; + zip_hash_entry_t *entry; + + if (hash == NULL || name == NULL || index > ZIP_INT64_MAX) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return false; + } + + if (hash->table_size == 0) { + if (!hash_resize(hash, HASH_MIN_SIZE, error)) { + return false; + } + } + + hash_value = hash_string(name); + table_index = hash_value % hash->table_size; + + for (entry = hash->table[table_index]; entry != NULL; entry = entry->next) { + if (entry->hash_value == hash_value && strcmp((const char *)name, (const char *)entry->name) == 0) { + if (((flags & ZIP_FL_UNCHANGED) && entry->orig_index != -1) || entry->current_index != -1) { + zip_error_set(error, ZIP_ER_EXISTS, 0); + return false; + } + else { + break; + } + } + } + + if (entry == NULL) { + if ((entry = (zip_hash_entry_t *)malloc(sizeof(zip_hash_entry_t))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return false; + } + entry->name = name; + entry->next = hash->table[table_index]; + hash->table[table_index] = entry; + entry->hash_value = hash_value; + entry->orig_index = -1; + hash->nentries++; + if (hash->nentries > hash->table_size * HASH_MAX_FILL && hash->table_size < HASH_MAX_SIZE) { + if (!hash_resize(hash, hash->table_size * 2, error)) { + return false; + } + } + } + + if (flags & ZIP_FL_UNCHANGED) { + entry->orig_index = (zip_int64_t)index; + } + entry->current_index = (zip_int64_t)index; + + return true; +} + + +/* remove entry from hash, error if not found */ +bool +_zip_hash_delete(zip_hash_t *hash, const zip_uint8_t *name, zip_error_t *error) { + zip_uint32_t hash_value, index; + zip_hash_entry_t *entry, *previous; + + if (hash == NULL || name == NULL) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return false; + } + + if (hash->nentries > 0) { + hash_value = hash_string(name); + index = hash_value % hash->table_size; + previous = NULL; + entry = hash->table[index]; + while (entry) { + if (entry->hash_value == hash_value && strcmp((const char *)name, (const char *)entry->name) == 0) { + if (entry->orig_index == -1) { + if (previous) { + previous->next = entry->next; + } + else { + hash->table[index] = entry->next; + } + free(entry); + hash->nentries--; + if (hash->nentries < hash->table_size * HASH_MIN_FILL && hash->table_size > HASH_MIN_SIZE) { + if (!hash_resize(hash, hash->table_size / 2, error)) { + return false; + } + } + } + else { + entry->current_index = -1; + } + return true; + } + previous = entry; + entry = entry->next; + } + } + + zip_error_set(error, ZIP_ER_NOENT, 0); + return false; +} + + +/* find value for entry in hash, -1 if not found */ +zip_int64_t +_zip_hash_lookup(zip_hash_t *hash, const zip_uint8_t *name, zip_flags_t flags, zip_error_t *error) { + zip_uint32_t hash_value, index; + zip_hash_entry_t *entry; + + if (hash == NULL || name == NULL) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return -1; + } + + if (hash->nentries > 0) { + hash_value = hash_string(name); + index = hash_value % hash->table_size; + for (entry = hash->table[index]; entry != NULL; entry = entry->next) { + if (strcmp((const char *)name, (const char *)entry->name) == 0) { + if (flags & ZIP_FL_UNCHANGED) { + if (entry->orig_index != -1) { + return entry->orig_index; + } + } + else { + if (entry->current_index != -1) { + return entry->current_index; + } + } + break; + } + } + } + + zip_error_set(error, ZIP_ER_NOENT, 0); + return -1; +} + + +bool +_zip_hash_reserve_capacity(zip_hash_t *hash, zip_uint64_t capacity, zip_error_t *error) { + zip_uint32_t new_size; + + if (capacity == 0) { + return true; + } + + new_size = size_for_capacity(capacity); + + if (new_size <= hash->table_size) { + return true; + } + + if (!hash_resize(hash, new_size, error)) { + return false; + } + + return true; +} + + +bool +_zip_hash_revert(zip_hash_t *hash, zip_error_t *error) { + zip_uint32_t i; + zip_hash_entry_t *entry, *previous; + + for (i = 0; i < hash->table_size; i++) { + previous = NULL; + entry = hash->table[i]; + while (entry) { + if (entry->orig_index == -1) { + zip_hash_entry_t *p; + if (previous) { + previous->next = entry->next; + } + else { + hash->table[i] = entry->next; + } + p = entry; + entry = entry->next; + /* previous does not change */ + free(p); + hash->nentries--; + } + else { + entry->current_index = entry->orig_index; + previous = entry; + entry = entry->next; + } + } + } + + if (hash->nentries < hash->table_size * HASH_MIN_FILL && hash->table_size > HASH_MIN_SIZE) { + zip_uint32_t new_size = hash->table_size / 2; + while (hash->nentries < new_size * HASH_MIN_FILL && new_size > HASH_MIN_SIZE) { + new_size /= 2; + } + if (!hash_resize(hash, new_size, error)) { + return false; + } + } + + return true; +} diff --git a/Source/Libraries/libzip/zip_io_util.c b/Source/Libraries/libzip/zip_io_util.c new file mode 100644 index 0000000..3678dd5 --- /dev/null +++ b/Source/Libraries/libzip/zip_io_util.c @@ -0,0 +1,134 @@ +/* + zip_io_util.c -- I/O helper functions + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +int +_zip_read(zip_source_t *src, zip_uint8_t *b, zip_uint64_t length, zip_error_t *error) { + zip_int64_t n; + + if (length > ZIP_INT64_MAX) { + zip_error_set(error, ZIP_ER_INTERNAL, 0); + return -1; + } + + if ((n = zip_source_read(src, b, length)) < 0) { + _zip_error_set_from_source(error, src); + return -1; + } + + if (n < (zip_int64_t)length) { + zip_error_set(error, ZIP_ER_EOF, 0); + return -1; + } + + return 0; +} + + +zip_uint8_t * +_zip_read_data(zip_buffer_t *buffer, zip_source_t *src, size_t length, bool nulp, zip_error_t *error) { + zip_uint8_t *r; + + if (length == 0 && !nulp) { + return NULL; + } + + r = (zip_uint8_t *)malloc(length + (nulp ? 1 : 0)); + if (!r) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + if (buffer) { + zip_uint8_t *data = _zip_buffer_get(buffer, length); + + if (data == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + free(r); + return NULL; + } + memcpy(r, data, length); + } + else { + if (_zip_read(src, r, length, error) < 0) { + free(r); + return NULL; + } + } + + if (nulp) { + zip_uint8_t *o; + /* replace any in-string NUL characters with spaces */ + r[length] = 0; + for (o = r; o < r + length; o++) + if (*o == '\0') + *o = ' '; + } + + return r; +} + + +zip_string_t * +_zip_read_string(zip_buffer_t *buffer, zip_source_t *src, zip_uint16_t len, bool nulp, zip_error_t *error) { + zip_uint8_t *raw; + zip_string_t *s; + + if ((raw = _zip_read_data(buffer, src, len, nulp, error)) == NULL) + return NULL; + + s = _zip_string_new(raw, len, ZIP_FL_ENC_GUESS, error); + free(raw); + return s; +} + + +int +_zip_write(zip_t *za, const void *data, zip_uint64_t length) { + zip_int64_t n; + + if ((n = zip_source_write(za->src, data, length)) < 0) { + _zip_error_set_from_source(&za->error, za->src); + return -1; + } + if ((zip_uint64_t)n != length) { + zip_error_set(&za->error, ZIP_ER_WRITE, EINTR); + return -1; + } + + return 0; +} diff --git a/Source/Libraries/libzip/zip_libzip_version.c b/Source/Libraries/libzip/zip_libzip_version.c new file mode 100644 index 0000000..df1e55b --- /dev/null +++ b/Source/Libraries/libzip/zip_libzip_version.c @@ -0,0 +1,41 @@ +/* + zip_libzip_version.c -- return run-time version of library + Copyright (C) 2017-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN const char * +zip_libzip_version(void) { + return LIBZIP_VERSION; +} diff --git a/Source/Libraries/libzip/zip_memdup.c b/Source/Libraries/libzip/zip_memdup.c new file mode 100644 index 0000000..1691860 --- /dev/null +++ b/Source/Libraries/libzip/zip_memdup.c @@ -0,0 +1,56 @@ +/* + zip_memdup.c -- internal zip function, "strdup" with len + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +void * +_zip_memdup(const void *mem, size_t len, zip_error_t *error) { + void *ret; + + if (len == 0) + return NULL; + + ret = malloc(len); + if (!ret) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + memcpy(ret, mem, len); + + return ret; +} diff --git a/Source/Libraries/libzip/zip_name_locate.c b/Source/Libraries/libzip/zip_name_locate.c new file mode 100644 index 0000000..308d843 --- /dev/null +++ b/Source/Libraries/libzip/zip_name_locate.c @@ -0,0 +1,92 @@ +/* + zip_name_locate.c -- get index by name + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#ifdef HAVE_STRINGS_H +#include +#endif + +#include "zipint.h" + + +ZIP_EXTERN zip_int64_t +zip_name_locate(zip_t *za, const char *fname, zip_flags_t flags) { + return _zip_name_locate(za, fname, flags, &za->error); +} + + +zip_int64_t +_zip_name_locate(zip_t *za, const char *fname, zip_flags_t flags, zip_error_t *error) { + int (*cmp)(const char *, const char *); + const char *fn, *p; + zip_uint64_t i; + + if (za == NULL) + return -1; + + if (fname == NULL) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return -1; + } + + if (flags & (ZIP_FL_NOCASE | ZIP_FL_NODIR | ZIP_FL_ENC_CP437)) { + /* can't use hash table */ + cmp = (flags & ZIP_FL_NOCASE) ? strcasecmp : strcmp; + + for (i = 0; i < za->nentry; i++) { + fn = _zip_get_name(za, i, flags, error); + + /* newly added (partially filled) entry or error */ + if (fn == NULL) + continue; + + if (flags & ZIP_FL_NODIR) { + p = strrchr(fn, '/'); + if (p) + fn = p + 1; + } + + if (cmp(fname, fn) == 0) { + _zip_error_clear(error); + return (zip_int64_t)i; + } + } + + zip_error_set(error, ZIP_ER_NOENT, 0); + return -1; + } + else { + return _zip_hash_lookup(za->names, (const zip_uint8_t *)fname, flags, error); + } +} diff --git a/Source/Libraries/libzip/zip_new.c b/Source/Libraries/libzip/zip_new.c new file mode 100644 index 0000000..d2a5fa1 --- /dev/null +++ b/Source/Libraries/libzip/zip_new.c @@ -0,0 +1,73 @@ +/* + zip_new.c -- create and init struct zip + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +/* _zip_new: + creates a new zipfile struct, and sets the contents to zero; returns + the new struct. */ + +zip_t * +_zip_new(zip_error_t *error) { + zip_t *za; + + za = (zip_t *)malloc(sizeof(struct zip)); + if (!za) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + if ((za->names = _zip_hash_new(error)) == NULL) { + free(za); + return NULL; + } + + za->src = NULL; + za->open_flags = 0; + zip_error_init(&za->error); + za->flags = za->ch_flags = 0; + za->default_password = NULL; + za->comment_orig = za->comment_changes = NULL; + za->comment_changed = 0; + za->nentry = za->nentry_alloc = 0; + za->entry = NULL; + za->nopen_source = za->nopen_source_alloc = 0; + za->open_source = NULL; + za->progress = NULL; + + return za; +} diff --git a/Source/Libraries/libzip/zip_open.c b/Source/Libraries/libzip/zip_open.c new file mode 100644 index 0000000..292bfc8 --- /dev/null +++ b/Source/Libraries/libzip/zip_open.c @@ -0,0 +1,849 @@ +/* + zip_open.c -- open zip archive by name + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" + +typedef enum { EXISTS_ERROR = -1, EXISTS_NOT = 0, EXISTS_OK } exists_t; +static zip_t *_zip_allocate_new(zip_source_t *src, unsigned int flags, zip_error_t *error); +static zip_int64_t _zip_checkcons(zip_t *za, zip_cdir_t *cdir, zip_error_t *error); +static zip_cdir_t *_zip_find_central_dir(zip_t *za, zip_uint64_t len); +static exists_t _zip_file_exists(zip_source_t *src, zip_error_t *error); +static int _zip_headercomp(const zip_dirent_t *, const zip_dirent_t *); +static unsigned char *_zip_memmem(const unsigned char *, size_t, const unsigned char *, size_t); +static zip_cdir_t *_zip_read_cdir(zip_t *za, zip_buffer_t *buffer, zip_uint64_t buf_offset, zip_error_t *error); +static zip_cdir_t *_zip_read_eocd(zip_buffer_t *buffer, zip_uint64_t buf_offset, unsigned int flags, zip_error_t *error); +static zip_cdir_t *_zip_read_eocd64(zip_source_t *src, zip_buffer_t *buffer, zip_uint64_t buf_offset, unsigned int flags, zip_error_t *error); + + +ZIP_EXTERN zip_t * +zip_open(const char *fn, int _flags, int *zep) { + zip_t *za; + zip_source_t *src; + struct zip_error error; + + zip_error_init(&error); + if ((src = zip_source_file_create(fn, 0, -1, &error)) == NULL) { + _zip_set_open_error(zep, &error, 0); + zip_error_fini(&error); + return NULL; + } + + if ((za = zip_open_from_source(src, _flags, &error)) == NULL) { + zip_source_free(src); + _zip_set_open_error(zep, &error, 0); + zip_error_fini(&error); + return NULL; + } + + zip_error_fini(&error); + return za; +} + + +ZIP_EXTERN zip_t * +zip_open_from_source(zip_source_t *src, int _flags, zip_error_t *error) { + static zip_int64_t needed_support_read = -1; + static zip_int64_t needed_support_write = -1; + + unsigned int flags; + zip_int64_t supported; + exists_t exists; + + if (_flags < 0 || src == NULL) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + flags = (unsigned int)_flags; + + supported = zip_source_supports(src); + if (needed_support_read == -1) { + needed_support_read = zip_source_make_command_bitmap(ZIP_SOURCE_OPEN, ZIP_SOURCE_READ, ZIP_SOURCE_CLOSE, ZIP_SOURCE_SEEK, ZIP_SOURCE_TELL, ZIP_SOURCE_STAT, -1); + needed_support_write = zip_source_make_command_bitmap(ZIP_SOURCE_BEGIN_WRITE, ZIP_SOURCE_COMMIT_WRITE, ZIP_SOURCE_ROLLBACK_WRITE, ZIP_SOURCE_SEEK_WRITE, ZIP_SOURCE_TELL_WRITE, ZIP_SOURCE_REMOVE, -1); + } + if ((supported & needed_support_read) != needed_support_read) { + zip_error_set(error, ZIP_ER_OPNOTSUPP, 0); + return NULL; + } + if ((supported & needed_support_write) != needed_support_write) { + flags |= ZIP_RDONLY; + } + + if ((flags & (ZIP_RDONLY | ZIP_TRUNCATE)) == (ZIP_RDONLY | ZIP_TRUNCATE)) { + zip_error_set(error, ZIP_ER_RDONLY, 0); + return NULL; + } + + exists = _zip_file_exists(src, error); + switch (exists) { + case EXISTS_ERROR: + return NULL; + + case EXISTS_NOT: + if ((flags & ZIP_CREATE) == 0) { + zip_error_set(error, ZIP_ER_NOENT, 0); + return NULL; + } + return _zip_allocate_new(src, flags, error); + + default: { + zip_t *za; + if (flags & ZIP_EXCL) { + zip_error_set(error, ZIP_ER_EXISTS, 0); + return NULL; + } + if (zip_source_open(src) < 0) { + _zip_error_set_from_source(error, src); + return NULL; + } + + if (flags & ZIP_TRUNCATE) { + za = _zip_allocate_new(src, flags, error); + } + else { + /* ZIP_CREATE gets ignored if file exists and not ZIP_EXCL, just like open() */ + za = _zip_open(src, flags, error); + } + + if (za == NULL) { + zip_source_close(src); + return NULL; + } + return za; + } + } +} + + +zip_t * +_zip_open(zip_source_t *src, unsigned int flags, zip_error_t *error) { + zip_t *za; + zip_cdir_t *cdir; + struct zip_stat st; + zip_uint64_t len, idx; + + zip_stat_init(&st); + if (zip_source_stat(src, &st) < 0) { + _zip_error_set_from_source(error, src); + return NULL; + } + if ((st.valid & ZIP_STAT_SIZE) == 0) { + zip_error_set(error, ZIP_ER_SEEK, EOPNOTSUPP); + return NULL; + } + len = st.size; + + + if ((za = _zip_allocate_new(src, flags, error)) == NULL) { + return NULL; + } + + /* treat empty files as empty archives */ + if (len == 0 && zip_source_accept_empty(src)) { + return za; + } + + if ((cdir = _zip_find_central_dir(za, len)) == NULL) { + _zip_error_copy(error, &za->error); + /* keep src so discard does not get rid of it */ + zip_source_keep(src); + zip_discard(za); + return NULL; + } + + za->entry = cdir->entry; + za->nentry = cdir->nentry; + za->nentry_alloc = cdir->nentry_alloc; + za->comment_orig = cdir->comment; + + free(cdir); + + _zip_hash_reserve_capacity(za->names, za->nentry, &za->error); + + for (idx = 0; idx < za->nentry; idx++) { + const zip_uint8_t *name = _zip_string_get(za->entry[idx].orig->filename, NULL, 0, error); + if (name == NULL) { + /* keep src so discard does not get rid of it */ + zip_source_keep(src); + zip_discard(za); + return NULL; + } + + if (_zip_hash_add(za->names, name, idx, ZIP_FL_UNCHANGED, &za->error) == false) { + if (za->error.zip_err != ZIP_ER_EXISTS || (flags & ZIP_CHECKCONS)) { + _zip_error_copy(error, &za->error); + /* keep src so discard does not get rid of it */ + zip_source_keep(src); + zip_discard(za); + return NULL; + } + } + } + + za->ch_flags = za->flags; + + return za; +} + + +void +_zip_set_open_error(int *zep, const zip_error_t *err, int ze) { + if (err) { + ze = zip_error_code_zip(err); + if (zip_error_system_type(err) == ZIP_ET_SYS) { + errno = zip_error_code_system(err); + } + } + + if (zep) + *zep = ze; +} + + +/* _zip_readcdir: + tries to find a valid end-of-central-directory at the beginning of + buf, and then the corresponding central directory entries. + Returns a struct zip_cdir which contains the central directory + entries, or NULL if unsuccessful. */ + +static zip_cdir_t * +_zip_read_cdir(zip_t *za, zip_buffer_t *buffer, zip_uint64_t buf_offset, zip_error_t *error) { + zip_cdir_t *cd; + zip_uint16_t comment_len; + zip_uint64_t i, left; + zip_uint64_t eocd_offset = _zip_buffer_offset(buffer); + zip_buffer_t *cd_buffer; + + if (_zip_buffer_left(buffer) < EOCDLEN) { + /* not enough bytes left for comment */ + zip_error_set(error, ZIP_ER_NOZIP, 0); + return NULL; + } + + /* check for end-of-central-dir magic */ + if (memcmp(_zip_buffer_get(buffer, 4), EOCD_MAGIC, 4) != 0) { + zip_error_set(error, ZIP_ER_NOZIP, 0); + return NULL; + } + + if (eocd_offset >= EOCD64LOCLEN && memcmp(_zip_buffer_data(buffer) + eocd_offset - EOCD64LOCLEN, EOCD64LOC_MAGIC, 4) == 0) { + _zip_buffer_set_offset(buffer, eocd_offset - EOCD64LOCLEN); + cd = _zip_read_eocd64(za->src, buffer, buf_offset, za->flags, error); + } + else { + _zip_buffer_set_offset(buffer, eocd_offset); + cd = _zip_read_eocd(buffer, buf_offset, za->flags, error); + } + + if (cd == NULL) + return NULL; + + _zip_buffer_set_offset(buffer, eocd_offset + 20); + comment_len = _zip_buffer_get_16(buffer); + + if (cd->offset + cd->size > buf_offset + eocd_offset) { + /* cdir spans past EOCD record */ + zip_error_set(error, ZIP_ER_INCONS, 0); + _zip_cdir_free(cd); + return NULL; + } + + if (comment_len || (za->open_flags & ZIP_CHECKCONS)) { + zip_uint64_t tail_len; + + _zip_buffer_set_offset(buffer, eocd_offset + EOCDLEN); + tail_len = _zip_buffer_left(buffer); + + if (tail_len < comment_len || ((za->open_flags & ZIP_CHECKCONS) && tail_len != comment_len)) { + zip_error_set(error, ZIP_ER_INCONS, 0); + _zip_cdir_free(cd); + return NULL; + } + + if (comment_len) { + if ((cd->comment = _zip_string_new(_zip_buffer_get(buffer, comment_len), comment_len, ZIP_FL_ENC_GUESS, error)) == NULL) { + _zip_cdir_free(cd); + return NULL; + } + } + } + + if (cd->offset >= buf_offset) { + zip_uint8_t *data; + /* if buffer already read in, use it */ + _zip_buffer_set_offset(buffer, cd->offset - buf_offset); + + if ((data = _zip_buffer_get(buffer, cd->size)) == NULL) { + zip_error_set(error, ZIP_ER_INCONS, 0); + _zip_cdir_free(cd); + return NULL; + } + if ((cd_buffer = _zip_buffer_new(data, cd->size)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + _zip_cdir_free(cd); + return NULL; + } + } + else { + cd_buffer = NULL; + + if (zip_source_seek(za->src, (zip_int64_t)cd->offset, SEEK_SET) < 0) { + _zip_error_set_from_source(error, za->src); + _zip_cdir_free(cd); + return NULL; + } + + /* possible consistency check: cd->offset = len-(cd->size+cd->comment_len+EOCDLEN) ? */ + if (zip_source_tell(za->src) != (zip_int64_t)cd->offset) { + zip_error_set(error, ZIP_ER_NOZIP, 0); + _zip_cdir_free(cd); + return NULL; + } + } + + left = (zip_uint64_t)cd->size; + i = 0; + while (left > 0) { + bool grown = false; + zip_int64_t entry_size; + + if (i == cd->nentry) { + /* InfoZIP has a hack to avoid using Zip64: it stores nentries % 0x10000 */ + /* This hack isn't applicable if we're using Zip64, or if there is no central directory entry following. */ + + if (cd->is_zip64 || left < CDENTRYSIZE) { + break; + } + + if (!_zip_cdir_grow(cd, 0x10000, error)) { + _zip_cdir_free(cd); + _zip_buffer_free(cd_buffer); + return NULL; + } + grown = true; + } + + if ((cd->entry[i].orig = _zip_dirent_new()) == NULL || (entry_size = _zip_dirent_read(cd->entry[i].orig, za->src, cd_buffer, false, error)) < 0) { + if (grown && zip_error_code_zip(error) == ZIP_ER_NOZIP) { + zip_error_set(error, ZIP_ER_INCONS, 0); + } + _zip_cdir_free(cd); + _zip_buffer_free(cd_buffer); + return NULL; + } + i++; + left -= (zip_uint64_t)entry_size; + } + + if (i != cd->nentry || left > 0) { + zip_error_set(error, ZIP_ER_INCONS, 0); + _zip_buffer_free(cd_buffer); + _zip_cdir_free(cd); + return NULL; + } + + if (za->open_flags & ZIP_CHECKCONS) { + bool ok; + + if (cd_buffer) { + ok = _zip_buffer_eof(cd_buffer); + } + else { + zip_int64_t offset = zip_source_tell(za->src); + + if (offset < 0) { + _zip_error_set_from_source(error, za->src); + _zip_cdir_free(cd); + return NULL; + } + ok = ((zip_uint64_t)offset == cd->offset + cd->size); + } + + if (!ok) { + zip_error_set(error, ZIP_ER_INCONS, 0); + _zip_buffer_free(cd_buffer); + _zip_cdir_free(cd); + return NULL; + } + } + + _zip_buffer_free(cd_buffer); + return cd; +} + + +/* _zip_checkcons: + Checks the consistency of the central directory by comparing central + directory entries with local headers and checking for plausible + file and header offsets. Returns -1 if not plausible, else the + difference between the lowest and the highest fileposition reached */ + +static zip_int64_t +_zip_checkcons(zip_t *za, zip_cdir_t *cd, zip_error_t *error) { + zip_uint64_t i; + zip_uint64_t min, max, j; + struct zip_dirent temp; + + _zip_dirent_init(&temp); + if (cd->nentry) { + max = cd->entry[0].orig->offset; + min = cd->entry[0].orig->offset; + } + else + min = max = 0; + + for (i = 0; i < cd->nentry; i++) { + if (cd->entry[i].orig->offset < min) + min = cd->entry[i].orig->offset; + if (min > (zip_uint64_t)cd->offset) { + zip_error_set(error, ZIP_ER_NOZIP, 0); + return -1; + } + + j = cd->entry[i].orig->offset + cd->entry[i].orig->comp_size + _zip_string_length(cd->entry[i].orig->filename) + LENTRYSIZE; + if (j > max) + max = j; + if (max > (zip_uint64_t)cd->offset) { + zip_error_set(error, ZIP_ER_NOZIP, 0); + return -1; + } + + if (zip_source_seek(za->src, (zip_int64_t)cd->entry[i].orig->offset, SEEK_SET) < 0) { + _zip_error_set_from_source(error, za->src); + return -1; + } + + if (_zip_dirent_read(&temp, za->src, NULL, true, error) == -1) { + _zip_dirent_finalize(&temp); + return -1; + } + + if (_zip_headercomp(cd->entry[i].orig, &temp) != 0) { + zip_error_set(error, ZIP_ER_INCONS, 0); + _zip_dirent_finalize(&temp); + return -1; + } + + cd->entry[i].orig->extra_fields = _zip_ef_merge(cd->entry[i].orig->extra_fields, temp.extra_fields); + cd->entry[i].orig->local_extra_fields_read = 1; + temp.extra_fields = NULL; + + _zip_dirent_finalize(&temp); + } + + return (max - min) < ZIP_INT64_MAX ? (zip_int64_t)(max - min) : ZIP_INT64_MAX; +} + + +/* _zip_headercomp: + compares a central directory entry and a local file header + Return 0 if they are consistent, -1 if not. */ + +static int +_zip_headercomp(const zip_dirent_t *central, const zip_dirent_t *local) { + if ((central->version_needed < local->version_needed) +#if 0 + /* some zip-files have different values in local + and global headers for the bitflags */ + || (central->bitflags != local->bitflags) +#endif + || (central->comp_method != local->comp_method) || (central->last_mod != local->last_mod) || !_zip_string_equal(central->filename, local->filename)) + return -1; + + if ((central->crc != local->crc) || (central->comp_size != local->comp_size) || (central->uncomp_size != local->uncomp_size)) { + /* InfoZip stores valid values in local header even when data descriptor is used. + This is in violation of the appnote. */ + if (((local->bitflags & ZIP_GPBF_DATA_DESCRIPTOR) == 0 || local->crc != 0 || local->comp_size != 0 || local->uncomp_size != 0)) + return -1; + } + + return 0; +} + + +static zip_t * +_zip_allocate_new(zip_source_t *src, unsigned int flags, zip_error_t *error) { + zip_t *za; + + if ((za = _zip_new(error)) == NULL) { + return NULL; + } + + za->src = src; + za->open_flags = flags; + if (flags & ZIP_RDONLY) { + za->flags |= ZIP_AFL_RDONLY; + za->ch_flags |= ZIP_AFL_RDONLY; + } + return za; +} + + +/* + * tests for file existence + */ +static exists_t +_zip_file_exists(zip_source_t *src, zip_error_t *error) { + struct zip_stat st; + + zip_stat_init(&st); + if (zip_source_stat(src, &st) != 0) { + zip_error_t *src_error = zip_source_error(src); + if (zip_error_code_zip(src_error) == ZIP_ER_READ && zip_error_code_system(src_error) == ENOENT) { + return EXISTS_NOT; + } + _zip_error_copy(error, src_error); + return EXISTS_ERROR; + } + + return EXISTS_OK; +} + + +static zip_cdir_t * +_zip_find_central_dir(zip_t *za, zip_uint64_t len) { + zip_cdir_t *cdir, *cdirnew; + zip_uint8_t *match; + zip_int64_t buf_offset; + zip_uint64_t buflen; + zip_int64_t a; + zip_int64_t best; + zip_error_t error; + zip_buffer_t *buffer; + + if (len < EOCDLEN) { + zip_error_set(&za->error, ZIP_ER_NOZIP, 0); + return NULL; + } + + buflen = (len < CDBUFSIZE ? len : CDBUFSIZE); + if (zip_source_seek(za->src, -(zip_int64_t)buflen, SEEK_END) < 0) { + zip_error_t *src_error = zip_source_error(za->src); + if (zip_error_code_zip(src_error) != ZIP_ER_SEEK || zip_error_code_system(src_error) != EFBIG) { + /* seek before start of file on my machine */ + _zip_error_copy(&za->error, src_error); + return NULL; + } + } + if ((buf_offset = zip_source_tell(za->src)) < 0) { + _zip_error_set_from_source(&za->error, za->src); + return NULL; + } + + if ((buffer = _zip_buffer_new_from_source(za->src, buflen, NULL, &za->error)) == NULL) { + return NULL; + } + + best = -1; + cdir = NULL; + if (buflen >= CDBUFSIZE) { + /* EOCD64 locator is before EOCD, so leave place for it */ + _zip_buffer_set_offset(buffer, EOCD64LOCLEN); + } + zip_error_set(&error, ZIP_ER_NOZIP, 0); + + match = _zip_buffer_get(buffer, 0); + while ((match = _zip_memmem(match, _zip_buffer_left(buffer) - (EOCDLEN - 4), (const unsigned char *)EOCD_MAGIC, 4)) != NULL) { + _zip_buffer_set_offset(buffer, (zip_uint64_t)(match - _zip_buffer_data(buffer))); + if ((cdirnew = _zip_read_cdir(za, buffer, (zip_uint64_t)buf_offset, &error)) != NULL) { + if (cdir) { + if (best <= 0) { + best = _zip_checkcons(za, cdir, &error); + } + + a = _zip_checkcons(za, cdirnew, &error); + if (best < a) { + _zip_cdir_free(cdir); + cdir = cdirnew; + best = a; + } + else { + _zip_cdir_free(cdirnew); + } + } + else { + cdir = cdirnew; + if (za->open_flags & ZIP_CHECKCONS) + best = _zip_checkcons(za, cdir, &error); + else { + best = 0; + } + } + cdirnew = NULL; + } + + match++; + _zip_buffer_set_offset(buffer, (zip_uint64_t)(match - _zip_buffer_data(buffer))); + } + + _zip_buffer_free(buffer); + + if (best < 0) { + _zip_error_copy(&za->error, &error); + _zip_cdir_free(cdir); + return NULL; + } + + return cdir; +} + + +static unsigned char * +_zip_memmem(const unsigned char *big, size_t biglen, const unsigned char *little, size_t littlelen) { + const unsigned char *p; + + if ((biglen < littlelen) || (littlelen == 0)) + return NULL; + p = big - 1; + while ((p = (const unsigned char *)memchr(p + 1, little[0], (size_t)(big - (p + 1)) + (size_t)(biglen - littlelen) + 1)) != NULL) { + if (memcmp(p + 1, little + 1, littlelen - 1) == 0) + return (unsigned char *)p; + } + + return NULL; +} + + +static zip_cdir_t * +_zip_read_eocd(zip_buffer_t *buffer, zip_uint64_t buf_offset, unsigned int flags, zip_error_t *error) { + zip_cdir_t *cd; + zip_uint64_t i, nentry, size, offset, eocd_offset; + + if (_zip_buffer_left(buffer) < EOCDLEN) { + zip_error_set(error, ZIP_ER_INCONS, 0); + return NULL; + } + + eocd_offset = _zip_buffer_offset(buffer); + + _zip_buffer_get(buffer, 4); /* magic already verified */ + + if (_zip_buffer_get_32(buffer) != 0) { + zip_error_set(error, ZIP_ER_MULTIDISK, 0); + return NULL; + } + + /* number of cdir-entries on this disk */ + i = _zip_buffer_get_16(buffer); + /* number of cdir-entries */ + nentry = _zip_buffer_get_16(buffer); + + if (nentry != i) { + zip_error_set(error, ZIP_ER_NOZIP, 0); + return NULL; + } + + size = _zip_buffer_get_32(buffer); + offset = _zip_buffer_get_32(buffer); + + if (offset + size < offset) { + zip_error_set(error, ZIP_ER_SEEK, EFBIG); + return NULL; + } + + if (offset + size > buf_offset + eocd_offset) { + /* cdir spans past EOCD record */ + zip_error_set(error, ZIP_ER_INCONS, 0); + return NULL; + } + + if ((flags & ZIP_CHECKCONS) && offset + size != buf_offset + eocd_offset) { + zip_error_set(error, ZIP_ER_INCONS, 0); + return NULL; + } + + if ((cd = _zip_cdir_new(nentry, error)) == NULL) + return NULL; + + cd->is_zip64 = false; + cd->size = size; + cd->offset = offset; + + return cd; +} + + +static zip_cdir_t * +_zip_read_eocd64(zip_source_t *src, zip_buffer_t *buffer, zip_uint64_t buf_offset, unsigned int flags, zip_error_t *error) { + zip_cdir_t *cd; + zip_uint64_t offset; + zip_uint8_t eocd[EOCD64LEN]; + zip_uint64_t eocd_offset; + zip_uint64_t size, nentry, i, eocdloc_offset; + bool free_buffer; + zip_uint32_t num_disks, num_disks64, eocd_disk, eocd_disk64; + + eocdloc_offset = _zip_buffer_offset(buffer); + + _zip_buffer_get(buffer, 4); /* magic already verified */ + + num_disks = _zip_buffer_get_16(buffer); + eocd_disk = _zip_buffer_get_16(buffer); + eocd_offset = _zip_buffer_get_64(buffer); + + /* valid seek value for start of EOCD */ + if (eocd_offset > ZIP_INT64_MAX) { + zip_error_set(error, ZIP_ER_SEEK, EFBIG); + return NULL; + } + + /* does EOCD fit before EOCD locator? */ + if (eocd_offset + EOCD64LEN > eocdloc_offset + buf_offset) { + zip_error_set(error, ZIP_ER_INCONS, 0); + return NULL; + } + + /* make sure current position of buffer is beginning of EOCD */ + if (eocd_offset >= buf_offset && eocd_offset + EOCD64LEN <= buf_offset + _zip_buffer_size(buffer)) { + _zip_buffer_set_offset(buffer, eocd_offset - buf_offset); + free_buffer = false; + } + else { + if (zip_source_seek(src, (zip_int64_t)eocd_offset, SEEK_SET) < 0) { + _zip_error_set_from_source(error, src); + return NULL; + } + if ((buffer = _zip_buffer_new_from_source(src, EOCD64LEN, eocd, error)) == NULL) { + return NULL; + } + free_buffer = true; + } + + if (memcmp(_zip_buffer_get(buffer, 4), EOCD64_MAGIC, 4) != 0) { + zip_error_set(error, ZIP_ER_INCONS, 0); + if (free_buffer) { + _zip_buffer_free(buffer); + } + return NULL; + } + + /* size of EOCD */ + size = _zip_buffer_get_64(buffer); + + /* is there a hole between EOCD and EOCD locator, or do they overlap? */ + if ((flags & ZIP_CHECKCONS) && size + eocd_offset + 12 != buf_offset + eocdloc_offset) { + zip_error_set(error, ZIP_ER_INCONS, 0); + if (free_buffer) { + _zip_buffer_free(buffer); + } + return NULL; + } + + _zip_buffer_get(buffer, 4); /* skip version made by/needed */ + + num_disks64 = _zip_buffer_get_32(buffer); + eocd_disk64 = _zip_buffer_get_32(buffer); + + /* if eocd values are 0xffff, we have to use eocd64 values. + otherwise, if the values are not the same, it's inconsistent; + in any case, if the value is not 0, we don't support it */ + if (num_disks == 0xffff) { + num_disks = num_disks64; + } + if (eocd_disk == 0xffff) { + eocd_disk = eocd_disk64; + } + if ((flags & ZIP_CHECKCONS) && (eocd_disk != eocd_disk64 || num_disks != num_disks64)) { + zip_error_set(error, ZIP_ER_INCONS, 0); + if (free_buffer) { + _zip_buffer_free(buffer); + } + return NULL; + } + if (num_disks != 0 || eocd_disk != 0) { + zip_error_set(error, ZIP_ER_MULTIDISK, 0); + if (free_buffer) { + _zip_buffer_free(buffer); + } + return NULL; + } + + nentry = _zip_buffer_get_64(buffer); + i = _zip_buffer_get_64(buffer); + + if (nentry != i) { + zip_error_set(error, ZIP_ER_MULTIDISK, 0); + if (free_buffer) { + _zip_buffer_free(buffer); + } + return NULL; + } + + size = _zip_buffer_get_64(buffer); + offset = _zip_buffer_get_64(buffer); + + /* did we read past the end of the buffer? */ + if (!_zip_buffer_ok(buffer)) { + zip_error_set(error, ZIP_ER_INTERNAL, 0); + if (free_buffer) { + _zip_buffer_free(buffer); + } + return NULL; + } + + if (free_buffer) { + _zip_buffer_free(buffer); + } + + if (offset > ZIP_INT64_MAX || offset + size < offset) { + zip_error_set(error, ZIP_ER_SEEK, EFBIG); + return NULL; + } + if (offset + size > buf_offset + eocd_offset) { + /* cdir spans past EOCD record */ + zip_error_set(error, ZIP_ER_INCONS, 0); + return NULL; + } + if ((flags & ZIP_CHECKCONS) && offset + size != buf_offset + eocd_offset) { + zip_error_set(error, ZIP_ER_INCONS, 0); + return NULL; + } + + if (nentry > size / CDENTRYSIZE) { + zip_error_set(error, ZIP_ER_INCONS, 0); + return NULL; + } + + if ((cd = _zip_cdir_new(nentry, error)) == NULL) + return NULL; + + cd->is_zip64 = true; + cd->size = size; + cd->offset = offset; + + return cd; +} diff --git a/Source/Libraries/libzip/zip_pkware.c b/Source/Libraries/libzip/zip_pkware.c new file mode 100644 index 0000000..1b1b461 --- /dev/null +++ b/Source/Libraries/libzip/zip_pkware.c @@ -0,0 +1,112 @@ +/* + zip_pkware.c -- Traditional PKWARE de/encryption backend routines + Copyright (C) 2009-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +#define PKWARE_KEY0 305419896 +#define PKWARE_KEY1 591751049 +#define PKWARE_KEY2 878082192 + + +static void +update_keys(zip_pkware_keys_t *keys, zip_uint8_t b) { + keys->key[0] = (zip_uint32_t)crc32(keys->key[0] ^ 0xffffffffUL, &b, 1) ^ 0xffffffffUL; + keys->key[1] = (keys->key[1] + (keys->key[0] & 0xff)) * 134775813 + 1; + b = (zip_uint8_t)(keys->key[1] >> 24); + keys->key[2] = (zip_uint32_t)crc32(keys->key[2] ^ 0xffffffffUL, &b, 1) ^ 0xffffffffUL; +} + + +static zip_uint8_t +crypt_byte(zip_pkware_keys_t *keys) { + zip_uint16_t tmp; + tmp = (zip_uint16_t)(keys->key[2] | 2); + tmp = (zip_uint16_t)(((zip_uint32_t)tmp * (tmp ^ 1)) >> 8); + return (zip_uint8_t)tmp; +} + + +void +_zip_pkware_keys_reset(zip_pkware_keys_t *keys) { + keys->key[0] = PKWARE_KEY0; + keys->key[1] = PKWARE_KEY1; + keys->key[2] = PKWARE_KEY2; +} + + +void +_zip_pkware_encrypt(zip_pkware_keys_t *keys, zip_uint8_t *out, const zip_uint8_t *in, zip_uint64_t len) { + zip_uint64_t i; + zip_uint8_t b; + zip_uint8_t tmp; + + for (i = 0; i < len; i++) { + b = in[i]; + + if (out != NULL) { + tmp = crypt_byte(keys); + update_keys(keys, b); + b ^= tmp; + out[i] = b; + } + else { + /* during initialization, we're only interested in key updates */ + update_keys(keys, b); + } + } +} + + +void +_zip_pkware_decrypt(zip_pkware_keys_t *keys, zip_uint8_t *out, const zip_uint8_t *in, zip_uint64_t len) { + zip_uint64_t i; + zip_uint8_t b; + zip_uint8_t tmp; + + for (i = 0; i < len; i++) { + b = in[i]; + + /* during initialization, we're only interested in key updates */ + if (out != NULL) { + tmp = crypt_byte(keys); + b ^= tmp; + out[i] = b; + } + + update_keys(keys, b); + } +} diff --git a/Source/Libraries/libzip/zip_progress.c b/Source/Libraries/libzip/zip_progress.c new file mode 100644 index 0000000..a881df4 --- /dev/null +++ b/Source/Libraries/libzip/zip_progress.c @@ -0,0 +1,293 @@ +/* + zip_progress.c -- progress reporting + Copyright (C) 2017-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + + +#define _ZIP_COMPILING_DEPRECATED +#include "zipint.h" + +struct zip_progress { + zip_t *za; + + zip_progress_callback callback_progress; + void (*ud_progress_free)(void *); + void *ud_progress; + + zip_cancel_callback callback_cancel; + void (*ud_cancel_free)(void *); + void *ud_cancel; + + double precision; + + /* state */ + double last_update; /* last value callback function was called with */ + + double start; /* start of sub-progress section */ + double end; /* end of sub-progress section */ +}; + +static void _zip_progress_free_cancel_callback(zip_progress_t *progress); +static void _zip_progress_free_progress_callback(zip_progress_t *progress); +static zip_progress_t *_zip_progress_new(zip_t *za); +static void _zip_progress_set_cancel_callback(zip_progress_t *progress, zip_cancel_callback callback, void (*ud_free)(void *), void *ud); +static void _zip_progress_set_progress_callback(zip_progress_t *progress, double precision, zip_progress_callback callback, void (*ud_free)(void *), void *ud); + +void +_zip_progress_end(zip_progress_t *progress) { + _zip_progress_update(progress, 1.0); +} + + +void +_zip_progress_free(zip_progress_t *progress) { + if (progress == NULL) { + return; + } + + _zip_progress_free_progress_callback(progress); + _zip_progress_free_cancel_callback(progress); + + free(progress); +} + + +static zip_progress_t * +_zip_progress_new(zip_t *za) { + zip_progress_t *progress = (zip_progress_t *)malloc(sizeof(*progress)); + + if (progress == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return NULL; + } + + progress->za = za; + + progress->callback_progress = NULL; + progress->ud_progress_free = NULL; + progress->ud_progress = NULL; + progress->precision = 0.0; + + progress->callback_cancel = NULL; + progress->ud_cancel_free = NULL; + progress->ud_cancel = NULL; + + return progress; +} + +static void +_zip_progress_free_progress_callback(zip_progress_t *progress) { + if (progress->ud_progress_free) { + progress->ud_progress_free(progress->ud_progress); + } + + progress->callback_progress = NULL; + progress->ud_progress = NULL; + progress->ud_progress_free = NULL; +} + +static void +_zip_progress_free_cancel_callback(zip_progress_t *progress) { + if (progress->ud_cancel_free) { + progress->ud_cancel_free(progress->ud_cancel); + } + + progress->callback_cancel = NULL; + progress->ud_cancel = NULL; + progress->ud_cancel_free = NULL; +} + +static void +_zip_progress_set_progress_callback(zip_progress_t *progress, double precision, zip_progress_callback callback, void (*ud_free)(void *), void *ud) { + _zip_progress_free_progress_callback(progress); + + progress->callback_progress = callback; + progress->ud_progress_free = ud_free; + progress->ud_progress = ud; + progress->precision = precision; +} + +void +_zip_progress_set_cancel_callback(zip_progress_t *progress, zip_cancel_callback callback, void (*ud_free)(void *), void *ud) { + _zip_progress_free_cancel_callback(progress); + + progress->callback_cancel = callback; + progress->ud_cancel_free = ud_free; + progress->ud_cancel = ud; +} + +int +_zip_progress_start(zip_progress_t *progress) { + if (progress == NULL) { + return 0; + } + + if (progress->callback_progress != NULL) { + progress->last_update = 0.0; + progress->callback_progress(progress->za, 0.0, progress->ud_progress); + } + + if (progress->callback_cancel != NULL) { + if (progress->callback_cancel(progress->za, progress->ud_cancel)) { + return -1; + } + } + + return 0; +} + + +int +_zip_progress_subrange(zip_progress_t *progress, double start, double end) { + if (progress == NULL) { + return 0; + } + + progress->start = start; + progress->end = end; + + return _zip_progress_update(progress, 0.0); +} + +int +_zip_progress_update(zip_progress_t *progress, double sub_current) { + double current; + + if (progress == NULL) { + return 0; + } + + if (progress->callback_progress != NULL) { + current = ZIP_MIN(ZIP_MAX(sub_current, 0.0), 1.0) * (progress->end - progress->start) + progress->start; + + if (current - progress->last_update > progress->precision) { + progress->callback_progress(progress->za, current, progress->ud_progress); + progress->last_update = current; + } + } + + if (progress->callback_cancel != NULL) { + if (progress->callback_cancel(progress->za, progress->ud_cancel)) { + return -1; + } + } + + return 0; +} + + +ZIP_EXTERN int +zip_register_progress_callback_with_state(zip_t *za, double precision, zip_progress_callback callback, void (*ud_free)(void *), void *ud) { + if (callback != NULL) { + if (za->progress == NULL) { + if ((za->progress = _zip_progress_new(za)) == NULL) { + return -1; + } + } + + _zip_progress_set_progress_callback(za->progress, precision, callback, ud_free, ud); + } + else { + if (za->progress != NULL) { + if (za->progress->callback_cancel == NULL) { + _zip_progress_free(za->progress); + za->progress = NULL; + } + else { + _zip_progress_free_progress_callback(za->progress); + } + } + } + + return 0; +} + + +ZIP_EXTERN int +zip_register_cancel_callback_with_state(zip_t *za, zip_cancel_callback callback, void (*ud_free)(void *), void *ud) { + if (callback != NULL) { + if (za->progress == NULL) { + if ((za->progress = _zip_progress_new(za)) == NULL) { + return -1; + } + } + + _zip_progress_set_cancel_callback(za->progress, callback, ud_free, ud); + } + else { + if (za->progress != NULL) { + if (za->progress->callback_progress == NULL) { + _zip_progress_free(za->progress); + za->progress = NULL; + } + else { + _zip_progress_free_cancel_callback(za->progress); + } + } + } + + return 0; +} + + +struct legacy_ud { + zip_progress_callback_t callback; +}; + + +static void +_zip_legacy_progress_callback(zip_t *za, double progress, void *vud) { + struct legacy_ud *ud = (struct legacy_ud *)vud; + + ud->callback(progress); +} + +ZIP_EXTERN void +zip_register_progress_callback(zip_t *za, zip_progress_callback_t progress_callback) { + struct legacy_ud *ud; + + if (progress_callback == NULL) { + zip_register_progress_callback_with_state(za, 0, NULL, NULL, NULL); + } + + if ((ud = (struct legacy_ud *)malloc(sizeof(*ud))) == NULL) { + return; + } + + ud->callback = progress_callback; + + if (zip_register_progress_callback_with_state(za, 0.001, _zip_legacy_progress_callback, free, ud) < 0) { + free(ud); + } +} diff --git a/Source/Libraries/libzip/zip_rename.c b/Source/Libraries/libzip/zip_rename.c new file mode 100644 index 0000000..eb1b395 --- /dev/null +++ b/Source/Libraries/libzip/zip_rename.c @@ -0,0 +1,42 @@ +/* + zip_rename.c -- rename file in zip archive + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + + +#define _ZIP_COMPILING_DEPRECATED +#include "zipint.h" + + +ZIP_EXTERN int +zip_rename(zip_t *za, zip_uint64_t idx, const char *name) { + return zip_file_rename(za, idx, name, 0); +} diff --git a/Source/Libraries/libzip/zip_replace.c b/Source/Libraries/libzip/zip_replace.c new file mode 100644 index 0000000..2140223 --- /dev/null +++ b/Source/Libraries/libzip/zip_replace.c @@ -0,0 +1,42 @@ +/* + zip_replace.c -- replace file via callback function + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + + +#define _ZIP_COMPILING_DEPRECATED +#include "zipint.h" + + +ZIP_EXTERN int +zip_replace(zip_t *za, zip_uint64_t idx, zip_source_t *source) { + return zip_file_replace(za, idx, source, 0); +} diff --git a/Source/Libraries/libzip/zip_set_archive_comment.c b/Source/Libraries/libzip/zip_set_archive_comment.c new file mode 100644 index 0000000..ce0c5d3 --- /dev/null +++ b/Source/Libraries/libzip/zip_set_archive_comment.c @@ -0,0 +1,80 @@ +/* + zip_set_archive_comment.c -- set archive comment + Copyright (C) 2006-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_set_archive_comment(zip_t *za, const char *comment, zip_uint16_t len) { + zip_string_t *cstr; + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + if (len > 0 && comment == NULL) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (len > 0) { + if ((cstr = _zip_string_new((const zip_uint8_t *)comment, len, ZIP_FL_ENC_GUESS, &za->error)) == NULL) + return -1; + + if (_zip_guess_encoding(cstr, ZIP_ENCODING_UNKNOWN) == ZIP_ENCODING_CP437) { + _zip_string_free(cstr); + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + } + else + cstr = NULL; + + _zip_string_free(za->comment_changes); + za->comment_changes = NULL; + + if (((za->comment_orig && _zip_string_equal(za->comment_orig, cstr)) || (za->comment_orig == NULL && cstr == NULL))) { + _zip_string_free(cstr); + za->comment_changed = 0; + } + else { + za->comment_changes = cstr; + za->comment_changed = 1; + } + + return 0; +} diff --git a/Source/Libraries/libzip/zip_set_archive_flag.c b/Source/Libraries/libzip/zip_set_archive_flag.c new file mode 100644 index 0000000..fe9f62f --- /dev/null +++ b/Source/Libraries/libzip/zip_set_archive_flag.c @@ -0,0 +1,65 @@ +/* + zip_get_archive_flag.c -- set archive global flag + Copyright (C) 2008-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_set_archive_flag(zip_t *za, zip_flags_t flag, int value) { + unsigned int new_flags; + + if (value) + new_flags = za->ch_flags | flag; + else + new_flags = za->ch_flags & ~flag; + + if (new_flags == za->ch_flags) + return 0; + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + if ((flag & ZIP_AFL_RDONLY) && value && (za->ch_flags & ZIP_AFL_RDONLY) == 0) { + if (_zip_changed(za, NULL)) { + zip_error_set(&za->error, ZIP_ER_CHANGED, 0); + return -1; + } + } + + za->ch_flags = new_flags; + + return 0; +} diff --git a/Source/Libraries/libzip/zip_set_default_password.c b/Source/Libraries/libzip/zip_set_default_password.c new file mode 100644 index 0000000..d893949 --- /dev/null +++ b/Source/Libraries/libzip/zip_set_default_password.c @@ -0,0 +1,58 @@ +/* + zip_set_default_password.c -- set default password for decryption + Copyright (C) 2009-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_set_default_password(zip_t *za, const char *passwd) { + if (za == NULL) + return -1; + + free(za->default_password); + + if (passwd && passwd[0] != '\0') { + if ((za->default_password = strdup(passwd)) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + } + else + za->default_password = NULL; + + return 0; +} diff --git a/Source/Libraries/libzip/zip_set_file_comment.c b/Source/Libraries/libzip/zip_set_file_comment.c new file mode 100644 index 0000000..d19121f --- /dev/null +++ b/Source/Libraries/libzip/zip_set_file_comment.c @@ -0,0 +1,46 @@ +/* + zip_set_file_comment.c -- set comment for file in archive + Copyright (C) 2006-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + + +#define _ZIP_COMPILING_DEPRECATED +#include "zipint.h" + + +ZIP_EXTERN int +zip_set_file_comment(zip_t *za, zip_uint64_t idx, const char *comment, int len) { + if (len < 0 || len > ZIP_UINT16_MAX) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + return zip_file_set_comment(za, idx, comment, (zip_uint16_t)len, 0); +} diff --git a/Source/Libraries/libzip/zip_set_file_compression.c b/Source/Libraries/libzip/zip_set_file_compression.c new file mode 100644 index 0000000..511c7d5 --- /dev/null +++ b/Source/Libraries/libzip/zip_set_file_compression.c @@ -0,0 +1,91 @@ +/* + zip_set_file_compression.c -- set compression for file in archive + Copyright (C) 2012-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_set_file_compression(zip_t *za, zip_uint64_t idx, zip_int32_t method, zip_uint32_t flags) { + zip_entry_t *e; + zip_int32_t old_method; + + if (idx >= za->nentry || flags > 9) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + if (!zip_compression_method_supported(method, true)) { + zip_error_set(&za->error, ZIP_ER_COMPNOTSUPP, 0); + return -1; + } + + e = za->entry + idx; + + old_method = (e->orig == NULL ? ZIP_CM_DEFAULT : e->orig->comp_method); + + /* TODO: do we want to recompress if level is set? Only if it's + * different than what bit flags tell us, but those are not + * defined for all compression methods, or not directly mappable + * to levels */ + + if (method == old_method) { + if (e->changes) { + e->changes->changed &= ~ZIP_DIRENT_COMP_METHOD; + e->changes->compression_level = 0; + if (e->changes->changed == 0) { + _zip_dirent_free(e->changes); + e->changes = NULL; + } + } + } + else { + if (e->changes == NULL) { + if ((e->changes = _zip_dirent_clone(e->orig)) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + } + + e->changes->comp_method = method; + e->changes->compression_level = (zip_uint16_t)flags; + e->changes->changed |= ZIP_DIRENT_COMP_METHOD; + } + + return 0; +} diff --git a/Source/Libraries/libzip/zip_set_name.c b/Source/Libraries/libzip/zip_set_name.c new file mode 100644 index 0000000..5267685 --- /dev/null +++ b/Source/Libraries/libzip/zip_set_name.c @@ -0,0 +1,157 @@ +/* + zip_set_name.c -- rename helper function + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +int +_zip_set_name(zip_t *za, zip_uint64_t idx, const char *name, zip_flags_t flags) { + zip_entry_t *e; + zip_string_t *str; + bool same_as_orig; + zip_int64_t i; + const zip_uint8_t *old_name, *new_name; + zip_string_t *old_str; + + if (idx >= za->nentry) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + if (name && name[0] != '\0') { + /* TODO: check for string too long */ + if ((str = _zip_string_new((const zip_uint8_t *)name, (zip_uint16_t)strlen(name), flags, &za->error)) == NULL) + return -1; + if ((flags & ZIP_FL_ENCODING_ALL) == ZIP_FL_ENC_GUESS && _zip_guess_encoding(str, ZIP_ENCODING_UNKNOWN) == ZIP_ENCODING_UTF8_GUESSED) + str->encoding = ZIP_ENCODING_UTF8_KNOWN; + } + else + str = NULL; + + /* TODO: encoding flags needed for CP437? */ + if ((i = _zip_name_locate(za, name, 0, NULL)) >= 0 && (zip_uint64_t)i != idx) { + _zip_string_free(str); + zip_error_set(&za->error, ZIP_ER_EXISTS, 0); + return -1; + } + + /* no effective name change */ + if (i >= 0 && (zip_uint64_t)i == idx) { + _zip_string_free(str); + return 0; + } + + e = za->entry + idx; + + if (e->orig) + same_as_orig = _zip_string_equal(e->orig->filename, str); + else + same_as_orig = false; + + if (!same_as_orig && e->changes == NULL) { + if ((e->changes = _zip_dirent_clone(e->orig)) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + _zip_string_free(str); + return -1; + } + } + + if ((new_name = _zip_string_get(same_as_orig ? e->orig->filename : str, NULL, 0, &za->error)) == NULL) { + _zip_string_free(str); + return -1; + } + + if (e->changes) { + old_str = e->changes->filename; + } + else if (e->orig) { + old_str = e->orig->filename; + } + else { + old_str = NULL; + } + + if (old_str) { + if ((old_name = _zip_string_get(old_str, NULL, 0, &za->error)) == NULL) { + _zip_string_free(str); + return -1; + } + } + else { + old_name = NULL; + } + + if (_zip_hash_add(za->names, new_name, idx, 0, &za->error) == false) { + _zip_string_free(str); + return -1; + } + if (old_name) { + _zip_hash_delete(za->names, old_name, NULL); + } + + if (same_as_orig) { + if (e->changes) { + if (e->changes->changed & ZIP_DIRENT_FILENAME) { + _zip_string_free(e->changes->filename); + e->changes->changed &= ~ZIP_DIRENT_FILENAME; + if (e->changes->changed == 0) { + _zip_dirent_free(e->changes); + e->changes = NULL; + } + else { + /* TODO: what if not cloned? can that happen? */ + e->changes->filename = e->orig->filename; + } + } + } + _zip_string_free(str); + } + else { + if (e->changes->changed & ZIP_DIRENT_FILENAME) { + _zip_string_free(e->changes->filename); + } + e->changes->changed |= ZIP_DIRENT_FILENAME; + e->changes->filename = str; + } + + return 0; +} diff --git a/Source/Libraries/libzip/zip_source_accept_empty.c b/Source/Libraries/libzip/zip_source_accept_empty.c new file mode 100644 index 0000000..754b80b --- /dev/null +++ b/Source/Libraries/libzip/zip_source_accept_empty.c @@ -0,0 +1,52 @@ +/* + zip_source_accept_empty.c -- if empty source is a valid archive + Copyright (C) 2019-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +bool +zip_source_accept_empty(zip_source_t *src) { + int ret; + + if ((zip_source_supports(src) & ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_ACCEPT_EMPTY)) == 0) { + if (ZIP_SOURCE_IS_LAYERED(src)) { + return zip_source_accept_empty(src->src); + } + return true; + } + + ret = (int)_zip_source_call(src, NULL, 0, ZIP_SOURCE_ACCEPT_EMPTY); + + return ret != 0; +} diff --git a/Source/Libraries/libzip/zip_source_begin_write.c b/Source/Libraries/libzip/zip_source_begin_write.c new file mode 100644 index 0000000..3981dc1 --- /dev/null +++ b/Source/Libraries/libzip/zip_source_begin_write.c @@ -0,0 +1,52 @@ +/* + zip_source_begin_write.c -- start a new file for writing + Copyright (C) 2014-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_source_begin_write(zip_source_t *src) { + if (ZIP_SOURCE_IS_OPEN_WRITING(src)) { + zip_error_set(&src->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (_zip_source_call(src, NULL, 0, ZIP_SOURCE_BEGIN_WRITE) < 0) { + return -1; + } + + src->write_state = ZIP_SOURCE_WRITE_OPEN; + + return 0; +} diff --git a/Source/Libraries/libzip/zip_source_begin_write_cloning.c b/Source/Libraries/libzip/zip_source_begin_write_cloning.c new file mode 100644 index 0000000..bfc63c8 --- /dev/null +++ b/Source/Libraries/libzip/zip_source_begin_write_cloning.c @@ -0,0 +1,52 @@ +/* + zip_source_begin_write_cloning.c -- clone part of file for writing + Copyright (C) 2017-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_source_begin_write_cloning(zip_source_t *src, zip_uint64_t offset) { + if (ZIP_SOURCE_IS_OPEN_WRITING(src)) { + zip_error_set(&src->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (_zip_source_call(src, NULL, offset, ZIP_SOURCE_BEGIN_WRITE_CLONING) < 0) { + return -1; + } + + src->write_state = ZIP_SOURCE_WRITE_OPEN; + + return 0; +} diff --git a/Source/Libraries/libzip/zip_source_buffer.c b/Source/Libraries/libzip/zip_source_buffer.c new file mode 100644 index 0000000..a54c4fc --- /dev/null +++ b/Source/Libraries/libzip/zip_source_buffer.c @@ -0,0 +1,620 @@ +/* + zip_source_buffer.c -- create zip data source from buffer + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +#ifndef WRITE_FRAGMENT_SIZE +#define WRITE_FRAGMENT_SIZE (64 * 1024) +#endif + +struct buffer { + zip_buffer_fragment_t *fragments; /* fragments */ + zip_uint64_t *fragment_offsets; /* offset of each fragment from start of buffer, nfragments+1 entries */ + zip_uint64_t nfragments; /* number of allocated fragments */ + zip_uint64_t fragments_capacity; /* size of fragments (number of pointers) */ + + zip_uint64_t first_owned_fragment; /* first fragment to free data from */ + + zip_uint64_t shared_fragments; /* number of shared fragments */ + struct buffer *shared_buffer; /* buffer fragments are shared with */ + zip_uint64_t size; /* size of buffer */ + + zip_uint64_t offset; /* current offset in buffer */ + zip_uint64_t current_fragment; /* fragment current offset is in */ +}; + +typedef struct buffer buffer_t; + +struct read_data { + zip_error_t error; + time_t mtime; + zip_file_attributes_t attributes; + buffer_t *in; + buffer_t *out; +}; + +#define buffer_capacity(buffer) ((buffer)->fragment_offsets[(buffer)->nfragments]) +#define buffer_size(buffer) ((buffer)->size) + +static buffer_t *buffer_clone(buffer_t *buffer, zip_uint64_t length, zip_error_t *error); +static zip_uint64_t buffer_find_fragment(const buffer_t *buffer, zip_uint64_t offset); +static void buffer_free(buffer_t *buffer); +static bool buffer_grow_fragments(buffer_t *buffer, zip_uint64_t capacity, zip_error_t *error); +static buffer_t *buffer_new(const zip_buffer_fragment_t *fragments, zip_uint64_t nfragments, int free_data, zip_error_t *error); +static zip_int64_t buffer_read(buffer_t *buffer, zip_uint8_t *data, zip_uint64_t length); +static int buffer_seek(buffer_t *buffer, void *data, zip_uint64_t len, zip_error_t *error); +static zip_int64_t buffer_write(buffer_t *buffer, const zip_uint8_t *data, zip_uint64_t length, zip_error_t *); + +static zip_int64_t read_data(void *, void *, zip_uint64_t, zip_source_cmd_t); + +zip_source_t *zip_source_buffer_with_attributes_create(const void *data, zip_uint64_t len, int freep, zip_file_attributes_t *attributes, zip_error_t *error); +zip_source_t *zip_source_buffer_fragment_with_attributes_create(const zip_buffer_fragment_t *fragments, zip_uint64_t nfragments, int freep, zip_file_attributes_t *attributes, zip_error_t *error); + + +ZIP_EXTERN zip_source_t * +zip_source_buffer(zip_t *za, const void *data, zip_uint64_t len, int freep) { + if (za == NULL) + return NULL; + + return zip_source_buffer_with_attributes_create(data, len, freep, NULL, &za->error); +} + + +ZIP_EXTERN zip_source_t * +zip_source_buffer_create(const void *data, zip_uint64_t len, int freep, zip_error_t *error) { + return zip_source_buffer_with_attributes_create(data, len, freep, NULL, error); +} + + +zip_source_t * +zip_source_buffer_with_attributes_create(const void *data, zip_uint64_t len, int freep, zip_file_attributes_t *attributes, zip_error_t *error) { + zip_buffer_fragment_t fragment; + + if (data == NULL) { + if (len > 0) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + return zip_source_buffer_fragment_with_attributes_create(NULL, 0, freep, attributes, error); + } + + fragment.data = (zip_uint8_t *)data; + fragment.length = len; + + return zip_source_buffer_fragment_with_attributes_create(&fragment, 1, freep, attributes, error); +} + + +ZIP_EXTERN zip_source_t * +zip_source_buffer_fragment(zip_t *za, const zip_buffer_fragment_t *fragments, zip_uint64_t nfragments, int freep) { + if (za == NULL) { + return NULL; + } + + return zip_source_buffer_fragment_with_attributes_create(fragments, nfragments, freep, NULL, &za->error); +} + + +ZIP_EXTERN zip_source_t * +zip_source_buffer_fragment_create(const zip_buffer_fragment_t *fragments, zip_uint64_t nfragments, int freep, zip_error_t *error) { + return zip_source_buffer_fragment_with_attributes_create(fragments, nfragments, freep, NULL, error); +} + +zip_source_t * +zip_source_buffer_fragment_with_attributes_create(const zip_buffer_fragment_t *fragments, zip_uint64_t nfragments, int freep, zip_file_attributes_t *attributes, zip_error_t *error) { + struct read_data *ctx; + zip_source_t *zs; + buffer_t *buffer; + + if (fragments == NULL && nfragments > 0) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + if ((buffer = buffer_new(fragments, nfragments, freep, error)) == NULL) { + return NULL; + } + + if ((ctx = (struct read_data *)malloc(sizeof(*ctx))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + buffer_free(buffer); + return NULL; + } + + ctx->in = buffer; + ctx->out = NULL; + ctx->mtime = time(NULL); + if (attributes) { + memcpy(&ctx->attributes, attributes, sizeof(ctx->attributes)); + } + else { + zip_file_attributes_init(&ctx->attributes); + } + zip_error_init(&ctx->error); + + if ((zs = zip_source_function_create(read_data, ctx, error)) == NULL) { + buffer_free(ctx->in); + free(ctx); + return NULL; + } + + return zs; +} + + +zip_source_t * +zip_source_buffer_with_attributes(zip_t *za, const void *data, zip_uint64_t len, int freep, zip_file_attributes_t *attributes) { + return zip_source_buffer_with_attributes_create(data, len, freep, attributes, &za->error); +} + +static zip_int64_t +read_data(void *state, void *data, zip_uint64_t len, zip_source_cmd_t cmd) { + struct read_data *ctx = (struct read_data *)state; + + switch (cmd) { + case ZIP_SOURCE_BEGIN_WRITE: + if ((ctx->out = buffer_new(NULL, 0, 0, &ctx->error)) == NULL) { + return -1; + } + ctx->out->offset = 0; + ctx->out->current_fragment = 0; + return 0; + + case ZIP_SOURCE_BEGIN_WRITE_CLONING: + if ((ctx->out = buffer_clone(ctx->in, len, &ctx->error)) == NULL) { + return -1; + } + ctx->out->offset = len; + ctx->out->current_fragment = ctx->out->nfragments; + return 0; + + case ZIP_SOURCE_CLOSE: + return 0; + + case ZIP_SOURCE_COMMIT_WRITE: + buffer_free(ctx->in); + ctx->in = ctx->out; + ctx->out = NULL; + return 0; + + case ZIP_SOURCE_ERROR: + return zip_error_to_data(&ctx->error, data, len); + + case ZIP_SOURCE_FREE: + buffer_free(ctx->in); + buffer_free(ctx->out); + free(ctx); + return 0; + + case ZIP_SOURCE_GET_FILE_ATTRIBUTES: { + if (len < sizeof(ctx->attributes)) { + zip_error_set(&ctx->error, ZIP_ER_INVAL, 0); + return -1; + } + + memcpy(data, &ctx->attributes, sizeof(ctx->attributes)); + + return sizeof(ctx->attributes); + } + + case ZIP_SOURCE_OPEN: + ctx->in->offset = 0; + ctx->in->current_fragment = 0; + return 0; + + case ZIP_SOURCE_READ: + if (len > ZIP_INT64_MAX) { + zip_error_set(&ctx->error, ZIP_ER_INVAL, 0); + return -1; + } + return buffer_read(ctx->in, data, len); + + case ZIP_SOURCE_REMOVE: { + buffer_t *empty = buffer_new(NULL, 0, 0, &ctx->error); + if (empty == NULL) { + return -1; + } + + buffer_free(ctx->in); + ctx->in = empty; + return 0; + } + + case ZIP_SOURCE_ROLLBACK_WRITE: + buffer_free(ctx->out); + ctx->out = NULL; + return 0; + + case ZIP_SOURCE_SEEK: + return buffer_seek(ctx->in, data, len, &ctx->error); + + case ZIP_SOURCE_SEEK_WRITE: + return buffer_seek(ctx->out, data, len, &ctx->error); + + case ZIP_SOURCE_STAT: { + zip_stat_t *st; + + if (len < sizeof(*st)) { + zip_error_set(&ctx->error, ZIP_ER_INVAL, 0); + return -1; + } + + st = (zip_stat_t *)data; + + zip_stat_init(st); + st->mtime = ctx->mtime; + st->size = ctx->in->size; + st->comp_size = st->size; + st->comp_method = ZIP_CM_STORE; + st->encryption_method = ZIP_EM_NONE; + st->valid = ZIP_STAT_MTIME | ZIP_STAT_SIZE | ZIP_STAT_COMP_SIZE | ZIP_STAT_COMP_METHOD | ZIP_STAT_ENCRYPTION_METHOD; + + return sizeof(*st); + } + + case ZIP_SOURCE_SUPPORTS: + return zip_source_make_command_bitmap(ZIP_SOURCE_GET_FILE_ATTRIBUTES, ZIP_SOURCE_OPEN, ZIP_SOURCE_READ, ZIP_SOURCE_CLOSE, ZIP_SOURCE_STAT, ZIP_SOURCE_ERROR, ZIP_SOURCE_FREE, ZIP_SOURCE_SEEK, ZIP_SOURCE_TELL, ZIP_SOURCE_BEGIN_WRITE, ZIP_SOURCE_BEGIN_WRITE_CLONING, ZIP_SOURCE_COMMIT_WRITE, ZIP_SOURCE_REMOVE, ZIP_SOURCE_ROLLBACK_WRITE, ZIP_SOURCE_SEEK_WRITE, ZIP_SOURCE_TELL_WRITE, ZIP_SOURCE_WRITE, -1); + + case ZIP_SOURCE_TELL: + if (ctx->in->offset > ZIP_INT64_MAX) { + zip_error_set(&ctx->error, ZIP_ER_TELL, EOVERFLOW); + return -1; + } + return (zip_int64_t)ctx->in->offset; + + + case ZIP_SOURCE_TELL_WRITE: + if (ctx->out->offset > ZIP_INT64_MAX) { + zip_error_set(&ctx->error, ZIP_ER_TELL, EOVERFLOW); + return -1; + } + return (zip_int64_t)ctx->out->offset; + + case ZIP_SOURCE_WRITE: + if (len > ZIP_INT64_MAX) { + zip_error_set(&ctx->error, ZIP_ER_INVAL, 0); + return -1; + } + return buffer_write(ctx->out, data, len, &ctx->error); + + default: + zip_error_set(&ctx->error, ZIP_ER_OPNOTSUPP, 0); + return -1; + } +} + + +static buffer_t * +buffer_clone(buffer_t *buffer, zip_uint64_t offset, zip_error_t *error) { + zip_uint64_t fragment, fragment_offset, waste; + buffer_t *clone; + + if (offset == 0) { + return buffer_new(NULL, 0, 1, error); + } + + if (offset > buffer->size) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + if (buffer->shared_buffer != NULL) { + zip_error_set(error, ZIP_ER_INUSE, 0); + return NULL; + } + + fragment = buffer_find_fragment(buffer, offset); + fragment_offset = offset - buffer->fragment_offsets[fragment]; + + if (fragment_offset == 0) { + fragment--; + fragment_offset = buffer->fragments[fragment].length; + } + + waste = buffer->fragments[fragment].length - fragment_offset; + if (waste > offset) { + zip_error_set(error, ZIP_ER_OPNOTSUPP, 0); + return NULL; + } + + if ((clone = buffer_new(buffer->fragments, fragment + 1, 0, error)) == NULL) { + return NULL; + } + +#ifndef __clang_analyzer__ + /* clone->fragments can't be null, since it was created with at least one fragment */ + clone->fragments[clone->nfragments - 1].length = fragment_offset; +#endif + clone->fragment_offsets[clone->nfragments] = offset; + clone->size = offset; + + clone->first_owned_fragment = ZIP_MIN(buffer->first_owned_fragment, clone->nfragments - 1); + + buffer->shared_buffer = clone; + clone->shared_buffer = buffer; + buffer->shared_fragments = clone->nfragments; + clone->shared_fragments = fragment + 1; + + return clone; +} + + +static zip_uint64_t +buffer_find_fragment(const buffer_t *buffer, zip_uint64_t offset) { + zip_uint64_t low, high, mid; + + low = 0; + high = buffer->nfragments - 1; + + while (low < high) { + mid = (high - low) / 2 + low; + if (buffer->fragment_offsets[mid] > offset) { + high = mid - 1; + } + else if (mid == buffer->nfragments || buffer->fragment_offsets[mid + 1] > offset) { + return mid; + } + else { + low = mid + 1; + } + } + + return low; +} + + +static void +buffer_free(buffer_t *buffer) { + zip_uint64_t i; + + if (buffer == NULL) { + return; + } + + if (buffer->shared_buffer != NULL) { + buffer->shared_buffer->shared_buffer = NULL; + buffer->shared_buffer->shared_fragments = 0; + + buffer->first_owned_fragment = ZIP_MAX(buffer->first_owned_fragment, buffer->shared_fragments); + } + + for (i = buffer->first_owned_fragment; i < buffer->nfragments; i++) { + free(buffer->fragments[i].data); + } + free(buffer->fragments); + free(buffer->fragment_offsets); + free(buffer); +} + + +static bool +buffer_grow_fragments(buffer_t *buffer, zip_uint64_t capacity, zip_error_t *error) { + zip_buffer_fragment_t *fragments; + zip_uint64_t *offsets; + + if (capacity < buffer->fragments_capacity) { + return true; + } + + if ((fragments = realloc(buffer->fragments, sizeof(buffer->fragments[0]) * capacity)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return false; + } + buffer->fragments = fragments; + if ((offsets = realloc(buffer->fragment_offsets, sizeof(buffer->fragment_offsets[0]) * (capacity + 1))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return false; + } + buffer->fragment_offsets = offsets; + buffer->fragments_capacity = capacity; + + return true; +} + + +static buffer_t * +buffer_new(const zip_buffer_fragment_t *fragments, zip_uint64_t nfragments, int free_data, zip_error_t *error) { + buffer_t *buffer; + + if ((buffer = malloc(sizeof(*buffer))) == NULL) { + return NULL; + } + + buffer->offset = 0; + buffer->first_owned_fragment = 0; + buffer->size = 0; + buffer->fragments = NULL; + buffer->fragment_offsets = NULL; + buffer->nfragments = 0; + buffer->fragments_capacity = 0; + buffer->shared_buffer = NULL; + buffer->shared_fragments = 0; + + if (nfragments == 0) { + if ((buffer->fragment_offsets = malloc(sizeof(buffer->fragment_offsets[0]))) == NULL) { + free(buffer); + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + buffer->fragment_offsets[0] = 0; + } + else { + zip_uint64_t i, j, offset; + + if (!buffer_grow_fragments(buffer, nfragments, NULL)) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + buffer_free(buffer); + return NULL; + } + + offset = 0; + for (i = 0, j = 0; i < nfragments; i++) { + if (fragments[i].length == 0) { + continue; + } + if (fragments[i].data == NULL) { + zip_error_set(error, ZIP_ER_INVAL, 0); + buffer_free(buffer); + return NULL; + } + buffer->fragments[j].data = fragments[i].data; + buffer->fragments[j].length = fragments[i].length; + buffer->fragment_offsets[i] = offset; + offset += fragments[i].length; + j++; + } + buffer->nfragments = j; + buffer->first_owned_fragment = free_data ? 0 : buffer->nfragments; + buffer->fragment_offsets[buffer->nfragments] = offset; + buffer->size = offset; + } + + return buffer; +} + +static zip_int64_t +buffer_read(buffer_t *buffer, zip_uint8_t *data, zip_uint64_t length) { + zip_uint64_t n, i, fragment_offset; + + length = ZIP_MIN(length, buffer->size - buffer->offset); + + if (length == 0) { + return 0; + } + if (length > ZIP_INT64_MAX) { + return -1; + } + + i = buffer->current_fragment; + fragment_offset = buffer->offset - buffer->fragment_offsets[i]; + n = 0; + while (n < length) { + zip_uint64_t left = ZIP_MIN(length - n, buffer->fragments[i].length - fragment_offset); + + memcpy(data + n, buffer->fragments[i].data + fragment_offset, left); + + if (left == buffer->fragments[i].length - fragment_offset) { + i++; + } + n += left; + fragment_offset = 0; + } + + buffer->offset += n; + buffer->current_fragment = i; + return (zip_int64_t)n; +} + + +static int +buffer_seek(buffer_t *buffer, void *data, zip_uint64_t len, zip_error_t *error) { + zip_int64_t new_offset = zip_source_seek_compute_offset(buffer->offset, buffer->size, data, len, error); + + if (new_offset < 0) { + return -1; + } + + buffer->offset = (zip_uint64_t)new_offset; + buffer->current_fragment = buffer_find_fragment(buffer, buffer->offset); + return 0; +} + + +static zip_int64_t +buffer_write(buffer_t *buffer, const zip_uint8_t *data, zip_uint64_t length, zip_error_t *error) { + zip_uint64_t n, i, fragment_offset, capacity; + + if (buffer->offset + length + WRITE_FRAGMENT_SIZE - 1 < length) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return -1; + } + + /* grow buffer if needed */ + capacity = buffer_capacity(buffer); + if (buffer->offset + length > capacity) { + zip_uint64_t needed_fragments = buffer->nfragments + (length - (capacity - buffer->offset) + WRITE_FRAGMENT_SIZE - 1) / WRITE_FRAGMENT_SIZE; + + if (needed_fragments > buffer->fragments_capacity) { + zip_uint64_t new_capacity = buffer->fragments_capacity; + + if (new_capacity == 0) { + new_capacity = 16; + } + while (new_capacity < needed_fragments) { + new_capacity *= 2; + } + + if (!buffer_grow_fragments(buffer, new_capacity, error)) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return -1; + } + } + + while (buffer->nfragments < needed_fragments) { + if ((buffer->fragments[buffer->nfragments].data = malloc(WRITE_FRAGMENT_SIZE)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return -1; + } + buffer->fragments[buffer->nfragments].length = WRITE_FRAGMENT_SIZE; + buffer->nfragments++; + capacity += WRITE_FRAGMENT_SIZE; + buffer->fragment_offsets[buffer->nfragments] = capacity; + } + } + + i = buffer->current_fragment; + fragment_offset = buffer->offset - buffer->fragment_offsets[i]; + n = 0; + while (n < length) { + zip_uint64_t left = ZIP_MIN(length - n, buffer->fragments[i].length - fragment_offset); + + memcpy(buffer->fragments[i].data + fragment_offset, data + n, left); + + if (left == buffer->fragments[i].length - fragment_offset) { + i++; + } + n += left; + fragment_offset = 0; + } + + buffer->offset += n; + buffer->current_fragment = i; + if (buffer->offset > buffer->size) { + buffer->size = buffer->offset; + } + + return (zip_int64_t)n; +} diff --git a/Source/Libraries/libzip/zip_source_call.c b/Source/Libraries/libzip/zip_source_call.c new file mode 100644 index 0000000..66b13d6 --- /dev/null +++ b/Source/Libraries/libzip/zip_source_call.c @@ -0,0 +1,68 @@ +/* + zip_source_call.c -- invoke callback command on zip_source + Copyright (C) 2009-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +zip_int64_t +_zip_source_call(zip_source_t *src, void *data, zip_uint64_t length, zip_source_cmd_t command) { + zip_int64_t ret; + + if ((src->supports & ZIP_SOURCE_MAKE_COMMAND_BITMASK(command)) == 0) { + zip_error_set(&src->error, ZIP_ER_OPNOTSUPP, 0); + return -1; + } + + if (src->src == NULL) { + ret = src->cb.f(src->ud, data, length, command); + } + else { + ret = src->cb.l(src->src, src->ud, data, length, command); + } + + if (ret < 0) { + if (command != ZIP_SOURCE_ERROR && command != ZIP_SOURCE_SUPPORTS) { + int e[2]; + + if (_zip_source_call(src, e, sizeof(e), ZIP_SOURCE_ERROR) < 0) { + zip_error_set(&src->error, ZIP_ER_INTERNAL, 0); + } + else { + zip_error_set(&src->error, e[0], e[1]); + } + } + } + + return ret; +} diff --git a/Source/Libraries/libzip/zip_source_close.c b/Source/Libraries/libzip/zip_source_close.c new file mode 100644 index 0000000..264e4b0 --- /dev/null +++ b/Source/Libraries/libzip/zip_source_close.c @@ -0,0 +1,57 @@ +/* + zip_source_close.c -- close zip_source (stop reading) + Copyright (C) 2009-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +int +zip_source_close(zip_source_t *src) { + if (!ZIP_SOURCE_IS_OPEN_READING(src)) { + zip_error_set(&src->error, ZIP_ER_INVAL, 0); + return -1; + } + + src->open_count--; + if (src->open_count == 0) { + _zip_source_call(src, NULL, 0, ZIP_SOURCE_CLOSE); + + if (ZIP_SOURCE_IS_LAYERED(src)) { + if (zip_source_close(src->src) < 0) { + zip_error_set(&src->error, ZIP_ER_INTERNAL, 0); + } + } + } + + return 0; +} diff --git a/Source/Libraries/libzip/zip_source_commit_write.c b/Source/Libraries/libzip/zip_source_commit_write.c new file mode 100644 index 0000000..ec8cd8b --- /dev/null +++ b/Source/Libraries/libzip/zip_source_commit_write.c @@ -0,0 +1,63 @@ +/* + zip_source_commit_write.c -- commit changes to file + Copyright (C) 2014-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_source_commit_write(zip_source_t *src) { + if (!ZIP_SOURCE_IS_OPEN_WRITING(src)) { + zip_error_set(&src->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (src->open_count > 1) { + zip_error_set(&src->error, ZIP_ER_INUSE, 0); + return -1; + } + else if (ZIP_SOURCE_IS_OPEN_READING(src)) { + if (zip_source_close(src) < 0) { + return -1; + } + } + + if (_zip_source_call(src, NULL, 0, ZIP_SOURCE_COMMIT_WRITE) < 0) { + src->write_state = ZIP_SOURCE_WRITE_FAILED; + return -1; + } + + src->write_state = ZIP_SOURCE_WRITE_CLOSED; + + return 0; +} diff --git a/Source/Libraries/libzip/zip_source_compress.c b/Source/Libraries/libzip/zip_source_compress.c new file mode 100644 index 0000000..35a022c --- /dev/null +++ b/Source/Libraries/libzip/zip_source_compress.c @@ -0,0 +1,398 @@ +/* + zip_source_compress.c -- (de)compression routines + Copyright (C) 2017-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +struct context { + zip_error_t error; + + bool end_of_input; + bool end_of_stream; + bool can_store; + bool is_stored; /* only valid if end_of_stream is true */ + bool compress; + zip_int32_t method; + + zip_uint64_t size; + zip_int64_t first_read; + zip_uint8_t buffer[BUFSIZE]; + + zip_compression_algorithm_t *algorithm; + void *ud; +}; + + +struct implementation { + zip_uint16_t method; + zip_compression_algorithm_t *compress; + zip_compression_algorithm_t *decompress; +}; + +static struct implementation implementations[] = { + {ZIP_CM_DEFLATE, &zip_algorithm_deflate_compress, &zip_algorithm_deflate_decompress}, +#if defined(HAVE_LIBBZ2) + {ZIP_CM_BZIP2, &zip_algorithm_bzip2_compress, &zip_algorithm_bzip2_decompress}, +#endif +#if defined(HAVE_LIBLZMA) + {ZIP_CM_LZMA, &zip_algorithm_xz_compress, &zip_algorithm_xz_decompress}, + /* Disabled - because 7z isn't able to unpack ZIP+LZMA2 + archives made this way - and vice versa. + + {ZIP_CM_LZMA2, &zip_algorithm_xz_compress, &zip_algorithm_xz_decompress}, + */ + {ZIP_CM_XZ, &zip_algorithm_xz_compress, &zip_algorithm_xz_decompress}, +#endif +#if defined(HAVE_LIBZSTD) + {ZIP_CM_ZSTD, &zip_algorithm_zstd_compress, &zip_algorithm_zstd_decompress}, +#endif + +}; + +static size_t implementations_size = sizeof(implementations) / sizeof(implementations[0]); + +static zip_source_t *compression_source_new(zip_t *za, zip_source_t *src, zip_int32_t method, bool compress, int compression_flags); +static zip_int64_t compress_callback(zip_source_t *, void *, void *, zip_uint64_t, zip_source_cmd_t); +static void context_free(struct context *ctx); +static struct context *context_new(zip_int32_t method, bool compress, int compression_flags, zip_compression_algorithm_t *algorithm); +static zip_int64_t compress_read(zip_source_t *, struct context *, void *, zip_uint64_t); + +zip_compression_algorithm_t * +_zip_get_compression_algorithm(zip_int32_t method, bool compress) { + size_t i; + zip_uint16_t real_method = ZIP_CM_ACTUAL(method); + + for (i = 0; i < implementations_size; i++) { + if (implementations[i].method == real_method) { + if (compress) { + return implementations[i].compress; + } + else { + return implementations[i].decompress; + } + } + } + + return NULL; +} + +ZIP_EXTERN int +zip_compression_method_supported(zip_int32_t method, int compress) { + if (method == ZIP_CM_STORE) { + return 1; + } + return _zip_get_compression_algorithm(method, compress) != NULL; +} + +zip_source_t * +zip_source_compress(zip_t *za, zip_source_t *src, zip_int32_t method, int compression_flags) { + return compression_source_new(za, src, method, true, compression_flags); +} + +zip_source_t * +zip_source_decompress(zip_t *za, zip_source_t *src, zip_int32_t method) { + return compression_source_new(za, src, method, false, 0); +} + + +static zip_source_t * +compression_source_new(zip_t *za, zip_source_t *src, zip_int32_t method, bool compress, int compression_flags) { + struct context *ctx; + zip_source_t *s2; + zip_compression_algorithm_t *algorithm = NULL; + + if (src == NULL) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return NULL; + } + + if ((algorithm = _zip_get_compression_algorithm(method, compress)) == NULL) { + zip_error_set(&za->error, ZIP_ER_COMPNOTSUPP, 0); + return NULL; + } + + if ((ctx = context_new(method, compress, compression_flags, algorithm)) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return NULL; + } + + if ((s2 = zip_source_layered(za, src, compress_callback, ctx)) == NULL) { + context_free(ctx); + return NULL; + } + + return s2; +} + + +static struct context * +context_new(zip_int32_t method, bool compress, int compression_flags, zip_compression_algorithm_t *algorithm) { + struct context *ctx; + + if ((ctx = (struct context *)malloc(sizeof(*ctx))) == NULL) { + return NULL; + } + zip_error_init(&ctx->error); + ctx->can_store = compress ? ZIP_CM_IS_DEFAULT(method) : false; + ctx->algorithm = algorithm; + ctx->method = method; + ctx->compress = compress; + ctx->end_of_input = false; + ctx->end_of_stream = false; + ctx->is_stored = false; + + if ((ctx->ud = ctx->algorithm->allocate(ZIP_CM_ACTUAL(method), compression_flags, &ctx->error)) == NULL) { + zip_error_fini(&ctx->error); + free(ctx); + return NULL; + } + + return ctx; +} + + +static void +context_free(struct context *ctx) { + if (ctx == NULL) { + return; + } + + ctx->algorithm->deallocate(ctx->ud); + zip_error_fini(&ctx->error); + + free(ctx); +} + + +static zip_int64_t +compress_read(zip_source_t *src, struct context *ctx, void *data, zip_uint64_t len) { + zip_compression_status_t ret; + bool end; + zip_int64_t n; + zip_uint64_t out_offset; + zip_uint64_t out_len; + + if (zip_error_code_zip(&ctx->error) != ZIP_ER_OK) { + return -1; + } + + if (len == 0 || ctx->end_of_stream) { + return 0; + } + + out_offset = 0; + + end = false; + while (!end && out_offset < len) { + out_len = len - out_offset; + ret = ctx->algorithm->process(ctx->ud, (zip_uint8_t *)data + out_offset, &out_len); + + if (ret != ZIP_COMPRESSION_ERROR) { + out_offset += out_len; + } + + switch (ret) { + case ZIP_COMPRESSION_END: + ctx->end_of_stream = true; + + if (!ctx->end_of_input) { + /* TODO: garbage after stream, or compression ended before all data read */ + } + + if (ctx->first_read < 0) { + /* we got end of processed stream before reading any input data */ + zip_error_set(&ctx->error, ZIP_ER_INTERNAL, 0); + end = true; + break; + } + if (ctx->can_store && (zip_uint64_t)ctx->first_read <= out_offset) { + ctx->is_stored = true; + ctx->size = (zip_uint64_t)ctx->first_read; + memcpy(data, ctx->buffer, ctx->size); + return (zip_int64_t)ctx->size; + } + end = true; + break; + + case ZIP_COMPRESSION_OK: + break; + + case ZIP_COMPRESSION_NEED_DATA: + if (ctx->end_of_input) { + /* TODO: error: stream not ended, but no more input */ + end = true; + break; + } + + if ((n = zip_source_read(src, ctx->buffer, sizeof(ctx->buffer))) < 0) { + _zip_error_set_from_source(&ctx->error, src); + end = true; + break; + } + else if (n == 0) { + ctx->end_of_input = true; + ctx->algorithm->end_of_input(ctx->ud); + if (ctx->first_read < 0) { + ctx->first_read = 0; + } + } + else { + if (ctx->first_read >= 0) { + /* we overwrote a previously filled ctx->buffer */ + ctx->can_store = false; + } + else { + ctx->first_read = n; + } + + ctx->algorithm->input(ctx->ud, ctx->buffer, (zip_uint64_t)n); + } + break; + + case ZIP_COMPRESSION_ERROR: + /* error set by algorithm */ + if (zip_error_code_zip(&ctx->error) == ZIP_ER_OK) { + zip_error_set(&ctx->error, ZIP_ER_INTERNAL, 0); + } + end = true; + break; + } + } + + if (out_offset > 0) { + ctx->can_store = false; + ctx->size += out_offset; + return (zip_int64_t)out_offset; + } + + return (zip_error_code_zip(&ctx->error) == ZIP_ER_OK) ? 0 : -1; +} + + +static zip_int64_t +compress_callback(zip_source_t *src, void *ud, void *data, zip_uint64_t len, zip_source_cmd_t cmd) { + struct context *ctx; + + ctx = (struct context *)ud; + + switch (cmd) { + case ZIP_SOURCE_OPEN: { + zip_stat_t st; + zip_file_attributes_t attributes; + + ctx->size = 0; + ctx->end_of_input = false; + ctx->end_of_stream = false; + ctx->is_stored = false; + ctx->first_read = -1; + + if (zip_source_stat(src, &st) < 0 || zip_source_get_file_attributes(src, &attributes) < 0) { + _zip_error_set_from_source(&ctx->error, src); + return -1; + } + + if (!ctx->algorithm->start(ctx->ud, &st, &attributes)) { + return -1; + } + + return 0; + } + + case ZIP_SOURCE_READ: + return compress_read(src, ctx, data, len); + + case ZIP_SOURCE_CLOSE: + if (!ctx->algorithm->end(ctx->ud)) { + return -1; + } + return 0; + + case ZIP_SOURCE_STAT: { + zip_stat_t *st; + + st = (zip_stat_t *)data; + + if (ctx->compress) { + if (ctx->end_of_stream) { + st->comp_method = ctx->is_stored ? ZIP_CM_STORE : ZIP_CM_ACTUAL(ctx->method); + st->comp_size = ctx->size; + st->valid |= ZIP_STAT_COMP_SIZE | ZIP_STAT_COMP_METHOD; + } + else { + st->valid &= ~(ZIP_STAT_COMP_SIZE | ZIP_STAT_COMP_METHOD); + } + } + else { + st->comp_method = ZIP_CM_STORE; + st->valid |= ZIP_STAT_COMP_METHOD; + if (ctx->end_of_stream) { + st->size = ctx->size; + st->valid |= ZIP_STAT_SIZE; + } + } + } + return 0; + + case ZIP_SOURCE_ERROR: + return zip_error_to_data(&ctx->error, data, len); + + case ZIP_SOURCE_FREE: + context_free(ctx); + return 0; + + case ZIP_SOURCE_GET_FILE_ATTRIBUTES: { + zip_file_attributes_t *attributes = (zip_file_attributes_t *)data; + + if (len < sizeof(*attributes)) { + zip_error_set(&ctx->error, ZIP_ER_INVAL, 0); + return -1; + } + + attributes->valid |= ZIP_FILE_ATTRIBUTES_VERSION_NEEDED | ZIP_FILE_ATTRIBUTES_GENERAL_PURPOSE_BIT_FLAGS; + attributes->version_needed = ctx->algorithm->version_needed; + attributes->general_purpose_bit_mask = ZIP_FILE_ATTRIBUTES_GENERAL_PURPOSE_BIT_FLAGS_ALLOWED_MASK; + attributes->general_purpose_bit_flags = (ctx->is_stored ? 0 : ctx->algorithm->general_purpose_bit_flags(ctx->ud)); + + return sizeof(*attributes); + } + + case ZIP_SOURCE_SUPPORTS: + return ZIP_SOURCE_SUPPORTS_READABLE | zip_source_make_command_bitmap(ZIP_SOURCE_GET_FILE_ATTRIBUTES, -1); + + default: + zip_error_set(&ctx->error, ZIP_ER_INTERNAL, 0); + return -1; + } +} diff --git a/Source/Libraries/libzip/zip_source_crc.c b/Source/Libraries/libzip/zip_source_crc.c new file mode 100644 index 0000000..cae7363 --- /dev/null +++ b/Source/Libraries/libzip/zip_source_crc.c @@ -0,0 +1,197 @@ +/* + zip_source_crc.c -- pass-through source that calculates CRC32 and size + Copyright (C) 2009-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" + +struct crc_context { + int validate; /* whether to check CRC on EOF and return error on mismatch */ + int crc_complete; /* whether CRC was computed for complete file */ + zip_error_t error; + zip_uint64_t size; + zip_uint64_t position; /* current reading position */ + zip_uint64_t crc_position; /* how far we've computed the CRC */ + zip_uint32_t crc; +}; + +static zip_int64_t crc_read(zip_source_t *, void *, void *, zip_uint64_t, zip_source_cmd_t); + + +zip_source_t * +zip_source_crc(zip_t *za, zip_source_t *src, int validate) { + struct crc_context *ctx; + + if (src == NULL) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return NULL; + } + + if ((ctx = (struct crc_context *)malloc(sizeof(*ctx))) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return NULL; + } + + zip_error_init(&ctx->error); + ctx->validate = validate; + ctx->crc_complete = 0; + ctx->crc_position = 0; + ctx->crc = (zip_uint32_t)crc32(0, NULL, 0); + ctx->size = 0; + + return zip_source_layered(za, src, crc_read, ctx); +} + + +static zip_int64_t +crc_read(zip_source_t *src, void *_ctx, void *data, zip_uint64_t len, zip_source_cmd_t cmd) { + struct crc_context *ctx; + zip_int64_t n; + + ctx = (struct crc_context *)_ctx; + + switch (cmd) { + case ZIP_SOURCE_OPEN: + ctx->position = 0; + return 0; + + case ZIP_SOURCE_READ: + if ((n = zip_source_read(src, data, len)) < 0) { + _zip_error_set_from_source(&ctx->error, src); + return -1; + } + + if (n == 0) { + if (ctx->crc_position == ctx->position) { + ctx->crc_complete = 1; + ctx->size = ctx->position; + + if (ctx->validate) { + struct zip_stat st; + + if (zip_source_stat(src, &st) < 0) { + _zip_error_set_from_source(&ctx->error, src); + return -1; + } + + if ((st.valid & ZIP_STAT_CRC) && st.crc != ctx->crc) { + zip_error_set(&ctx->error, ZIP_ER_CRC, 0); + return -1; + } + if ((st.valid & ZIP_STAT_SIZE) && st.size != ctx->size) { + zip_error_set(&ctx->error, ZIP_ER_INCONS, 0); + return -1; + } + } + } + } + else if (!ctx->crc_complete && ctx->position <= ctx->crc_position) { + zip_uint64_t i, nn; + + for (i = ctx->crc_position - ctx->position; i < (zip_uint64_t)n; i += nn) { + nn = ZIP_MIN(UINT_MAX, (zip_uint64_t)n - i); + + ctx->crc = (zip_uint32_t)crc32(ctx->crc, (const Bytef *)data + i, (uInt)nn); + ctx->crc_position += nn; + } + } + ctx->position += (zip_uint64_t)n; + return n; + + case ZIP_SOURCE_CLOSE: + return 0; + + case ZIP_SOURCE_STAT: { + zip_stat_t *st; + + st = (zip_stat_t *)data; + + if (ctx->crc_complete) { + /* TODO: Set comp_size, comp_method, encryption_method? + After all, this only works for uncompressed data. */ + st->size = ctx->size; + st->crc = ctx->crc; + st->comp_size = ctx->size; + st->comp_method = ZIP_CM_STORE; + st->encryption_method = ZIP_EM_NONE; + st->valid |= ZIP_STAT_SIZE | ZIP_STAT_CRC | ZIP_STAT_COMP_SIZE | ZIP_STAT_COMP_METHOD | ZIP_STAT_ENCRYPTION_METHOD; + } + return 0; + } + + case ZIP_SOURCE_ERROR: + return zip_error_to_data(&ctx->error, data, len); + + case ZIP_SOURCE_FREE: + free(ctx); + return 0; + + case ZIP_SOURCE_SUPPORTS: { + zip_int64_t mask = zip_source_supports(src); + + if (mask < 0) { + _zip_error_set_from_source(&ctx->error, src); + return -1; + } + + return mask & ~zip_source_make_command_bitmap(ZIP_SOURCE_BEGIN_WRITE, ZIP_SOURCE_COMMIT_WRITE, ZIP_SOURCE_ROLLBACK_WRITE, ZIP_SOURCE_SEEK_WRITE, ZIP_SOURCE_TELL_WRITE, ZIP_SOURCE_REMOVE, ZIP_SOURCE_GET_FILE_ATTRIBUTES, -1); + } + + case ZIP_SOURCE_SEEK: { + zip_int64_t new_position; + zip_source_args_seek_t *args = ZIP_SOURCE_GET_ARGS(zip_source_args_seek_t, data, len, &ctx->error); + + if (args == NULL) { + return -1; + } + if (zip_source_seek(src, args->offset, args->whence) < 0 || (new_position = zip_source_tell(src)) < 0) { + _zip_error_set_from_source(&ctx->error, src); + return -1; + } + + ctx->position = (zip_uint64_t)new_position; + + return 0; + } + + case ZIP_SOURCE_TELL: + return (zip_int64_t)ctx->position; + + default: + zip_error_set(&ctx->error, ZIP_ER_OPNOTSUPP, 0); + return -1; + } +} diff --git a/Source/Libraries/libzip/zip_source_error.c b/Source/Libraries/libzip/zip_source_error.c new file mode 100644 index 0000000..00998e8 --- /dev/null +++ b/Source/Libraries/libzip/zip_source_error.c @@ -0,0 +1,46 @@ +/* + zip_source_error.c -- get last error from zip_source + Copyright (C) 2009-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +zip_error_t * +zip_source_error(zip_source_t *src) { + return &src->error; +} + +bool +_zip_source_had_error(zip_source_t *src) { + return zip_source_error(src)->zip_err != ZIP_ER_OK; +} diff --git a/Source/Libraries/libzip/zip_source_file_common.c b/Source/Libraries/libzip/zip_source_file_common.c new file mode 100644 index 0000000..3241436 --- /dev/null +++ b/Source/Libraries/libzip/zip_source_file_common.c @@ -0,0 +1,378 @@ +/* + zip_source_file_common.c -- create data source from file + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" + +#include "zip_source_file.h" + +static zip_int64_t read_file(void *state, void *data, zip_uint64_t len, zip_source_cmd_t cmd); + +static void +zip_source_file_stat_init(zip_source_file_stat_t *st) { + st->size = 0; + st->mtime = time(NULL); + st->exists = false; + st->regular_file = false; +} + +zip_source_t * +zip_source_file_common_new(const char *fname, void *file, zip_uint64_t start, zip_int64_t len, const zip_stat_t *st, zip_source_file_operations_t *ops, void *ops_userdata, zip_error_t *error) { + zip_source_file_context_t *ctx; + zip_source_t *zs; + zip_source_file_stat_t sb; + + if (ops == NULL) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + if (ops->close == NULL || ops->read == NULL || ops->seek == NULL || ops->stat == NULL) { + zip_error_set(error, ZIP_ER_INTERNAL, 0); + return NULL; + } + + if (ops->write != NULL && (ops->commit_write == NULL || ops->create_temp_output == NULL || ops->remove == NULL || ops->rollback_write == NULL || ops->tell == NULL)) { + zip_error_set(error, ZIP_ER_INTERNAL, 0); + return NULL; + } + + if (fname != NULL) { + if (ops->open == NULL || ops->string_duplicate == NULL) { + zip_error_set(error, ZIP_ER_INTERNAL, 0); + return NULL; + } + } + else if (file == NULL) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + if (len < 0) { + len = 0; + } + + if (start > ZIP_INT64_MAX || start + (zip_uint64_t)len < start) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + if ((ctx = (zip_source_file_context_t *)malloc(sizeof(zip_source_file_context_t))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + ctx->ops = ops; + ctx->ops_userdata = ops_userdata; + ctx->fname = NULL; + if (fname) { + if ((ctx->fname = ops->string_duplicate(ctx, fname)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + free(ctx); + return NULL; + } + } + ctx->f = file; + ctx->start = start; + ctx->len = (zip_uint64_t)len; + if (st) { + memcpy(&ctx->st, st, sizeof(ctx->st)); + ctx->st.name = NULL; + ctx->st.valid &= ~ZIP_STAT_NAME; + } + else { + zip_stat_init(&ctx->st); + } + + if (ctx->len > 0) { + ctx->st.size = ctx->len; + ctx->st.valid |= ZIP_STAT_SIZE; + } + + zip_error_init(&ctx->stat_error); + + ctx->tmpname = NULL; + ctx->fout = NULL; + + zip_error_init(&ctx->error); + zip_file_attributes_init(&ctx->attributes); + + ctx->supports = ZIP_SOURCE_SUPPORTS_READABLE | zip_source_make_command_bitmap(ZIP_SOURCE_SUPPORTS, ZIP_SOURCE_TELL, -1); + + zip_source_file_stat_init(&sb); + if (!ops->stat(ctx, &sb)) { + _zip_error_copy(error, &ctx->error); + free(ctx->fname); + free(ctx); + return NULL; + } + + if (!sb.exists) { + if (ctx->fname && ctx->start == 0 && ctx->len == 0 && ops->write != NULL) { + ctx->supports = ZIP_SOURCE_SUPPORTS_WRITABLE; + /* zip_open_from_source checks for this to detect non-existing files */ + zip_error_set(&ctx->stat_error, ZIP_ER_READ, ENOENT); + } + else { + zip_error_set(&ctx->stat_error, ZIP_ER_READ, ENOENT); + free(ctx->fname); + free(ctx); + return NULL; + } + } + else { + if ((ctx->st.valid & ZIP_STAT_MTIME) == 0) { + ctx->st.mtime = sb.mtime; + ctx->st.valid |= ZIP_STAT_MTIME; + } + if (sb.regular_file) { + ctx->supports = ZIP_SOURCE_SUPPORTS_SEEKABLE; + + if (ctx->start + ctx->len > sb.size) { + zip_error_set(error, ZIP_ER_INVAL, 0); + free(ctx->fname); + free(ctx); + return NULL; + } + + if (ctx->len == 0) { + ctx->len = sb.size - ctx->start; + ctx->st.size = ctx->len; + ctx->st.valid |= ZIP_STAT_SIZE; + + /* when using a partial file, don't allow writing */ + if (ctx->fname && start == 0 && ops->write != NULL) { + ctx->supports = ZIP_SOURCE_SUPPORTS_WRITABLE; + } + } + } + + ctx->supports |= ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_GET_FILE_ATTRIBUTES); + } + + ctx->supports |= ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_ACCEPT_EMPTY); + if (ops->create_temp_output_cloning != NULL) { + if (ctx->supports & ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_BEGIN_WRITE)) { + ctx->supports |= ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_BEGIN_WRITE_CLONING); + } + } + + if ((zs = zip_source_function_create(read_file, ctx, error)) == NULL) { + free(ctx->fname); + free(ctx); + return NULL; + } + + return zs; +} + + +static zip_int64_t +read_file(void *state, void *data, zip_uint64_t len, zip_source_cmd_t cmd) { + zip_source_file_context_t *ctx; + char *buf; + + ctx = (zip_source_file_context_t *)state; + buf = (char *)data; + + switch (cmd) { + case ZIP_SOURCE_ACCEPT_EMPTY: + return 0; + + case ZIP_SOURCE_BEGIN_WRITE: + /* write support should not be set if fname is NULL */ + if (ctx->fname == NULL) { + zip_error_set(&ctx->error, ZIP_ER_INTERNAL, 0); + return -1; + } + return ctx->ops->create_temp_output(ctx); + + case ZIP_SOURCE_BEGIN_WRITE_CLONING: + /* write support should not be set if fname is NULL */ + if (ctx->fname == NULL) { + zip_error_set(&ctx->error, ZIP_ER_INTERNAL, 0); + return -1; + } + return ctx->ops->create_temp_output_cloning(ctx, len); + + case ZIP_SOURCE_CLOSE: + if (ctx->fname) { + ctx->ops->close(ctx); + ctx->f = NULL; + } + return 0; + + case ZIP_SOURCE_COMMIT_WRITE: { + zip_int64_t ret = ctx->ops->commit_write(ctx); + ctx->fout = NULL; + if (ret == 0) { + free(ctx->tmpname); + ctx->tmpname = NULL; + } + return ret; + } + + case ZIP_SOURCE_ERROR: + return zip_error_to_data(&ctx->error, data, len); + + case ZIP_SOURCE_FREE: + free(ctx->fname); + free(ctx->tmpname); + if (ctx->f) { + ctx->ops->close(ctx); + } + free(ctx); + return 0; + + case ZIP_SOURCE_GET_FILE_ATTRIBUTES: + if (len < sizeof(ctx->attributes)) { + zip_error_set(&ctx->error, ZIP_ER_INVAL, 0); + return -1; + } + memcpy(data, &ctx->attributes, sizeof(ctx->attributes)); + return sizeof(ctx->attributes); + + case ZIP_SOURCE_OPEN: + if (ctx->fname) { + if (ctx->ops->open(ctx) == false) { + return -1; + } + } + + if (ctx->start > 0) { // TODO: rewind on re-open + if (ctx->ops->seek(ctx, ctx->f, (zip_int64_t)ctx->start, SEEK_SET) == false) { + /* TODO: skip by reading */ + return -1; + } + } + ctx->offset = 0; + return 0; + + case ZIP_SOURCE_READ: { + zip_int64_t i; + zip_uint64_t n; + + if (ctx->len > 0) { + n = ZIP_MIN(ctx->len - ctx->offset, len); + } + else { + n = len; + } + + if ((i = ctx->ops->read(ctx, buf, n)) < 0) { + zip_error_set(&ctx->error, ZIP_ER_READ, errno); + return -1; + } + ctx->offset += (zip_uint64_t)i; + + return i; + } + + case ZIP_SOURCE_REMOVE: + return ctx->ops->remove(ctx); + + case ZIP_SOURCE_ROLLBACK_WRITE: + ctx->ops->rollback_write(ctx); + ctx->fout = NULL; + free(ctx->tmpname); + ctx->tmpname = NULL; + return 0; + + case ZIP_SOURCE_SEEK: { + zip_int64_t new_offset = zip_source_seek_compute_offset(ctx->offset, ctx->len, data, len, &ctx->error); + + if (new_offset < 0) { + return -1; + } + + /* The actual offset inside the file must be representable as zip_int64_t. */ + if (new_offset > ZIP_INT64_MAX - (zip_int64_t)ctx->start) { + zip_error_set(&ctx->error, ZIP_ER_SEEK, EOVERFLOW); + return -1; + } + + ctx->offset = (zip_uint64_t)new_offset; + + if (ctx->ops->seek(ctx, ctx->f, (zip_int64_t)(ctx->offset + ctx->start), SEEK_SET) == false) { + return -1; + } + return 0; + } + + case ZIP_SOURCE_SEEK_WRITE: { + zip_source_args_seek_t *args; + + args = ZIP_SOURCE_GET_ARGS(zip_source_args_seek_t, data, len, &ctx->error); + if (args == NULL) { + return -1; + } + + if (ctx->ops->seek(ctx, ctx->fout, args->offset, args->whence) == false) { + return -1; + } + return 0; + } + + case ZIP_SOURCE_STAT: { + if (len < sizeof(ctx->st)) + return -1; + + if (zip_error_code_zip(&ctx->stat_error) != 0) { + zip_error_set(&ctx->error, zip_error_code_zip(&ctx->stat_error), zip_error_code_system(&ctx->stat_error)); + return -1; + } + + memcpy(data, &ctx->st, sizeof(ctx->st)); + return sizeof(ctx->st); + } + + case ZIP_SOURCE_SUPPORTS: + return ctx->supports; + + case ZIP_SOURCE_TELL: + return (zip_int64_t)ctx->offset; + + case ZIP_SOURCE_TELL_WRITE: + return ctx->ops->tell(ctx, ctx->fout); + + case ZIP_SOURCE_WRITE: + return ctx->ops->write(ctx, data, len); + + default: + zip_error_set(&ctx->error, ZIP_ER_OPNOTSUPP, 0); + return -1; + } +} diff --git a/Source/Libraries/libzip/zip_source_file_stdio.c b/Source/Libraries/libzip/zip_source_file_stdio.c new file mode 100644 index 0000000..1581771 --- /dev/null +++ b/Source/Libraries/libzip/zip_source_file_stdio.c @@ -0,0 +1,208 @@ +/* + zip_source_file_stdio.c -- read-only stdio file source implementation + Copyright (C) 2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +#include "zip_source_file.h" +#include "zip_source_file_stdio.h" + +#include +#include +#include +#include + +#ifdef _WIN32 +#ifndef S_IWUSR +#define S_IWUSR _S_IWRITE +#endif +#endif + +/* clang-format off */ +static zip_source_file_operations_t ops_stdio_read = { + _zip_stdio_op_close, + NULL, + NULL, + NULL, + NULL, + _zip_stdio_op_read, + NULL, + NULL, + _zip_stdio_op_seek, + _zip_stdio_op_stat, + NULL, + _zip_stdio_op_tell, + NULL +}; +/* clang-format on */ + + +ZIP_EXTERN zip_source_t * +zip_source_filep(zip_t *za, FILE *file, zip_uint64_t start, zip_int64_t len) { + if (za == NULL) { + return NULL; + } + + return zip_source_filep_create(file, start, len, &za->error); +} + + +ZIP_EXTERN zip_source_t * +zip_source_filep_create(FILE *file, zip_uint64_t start, zip_int64_t length, zip_error_t *error) { + if (file == NULL || length < -1) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + return zip_source_file_common_new(NULL, file, start, length, NULL, &ops_stdio_read, NULL, error); +} + + +void +_zip_stdio_op_close(zip_source_file_context_t *ctx) { + fclose((FILE *)ctx->f); +} + + +zip_int64_t +_zip_stdio_op_read(zip_source_file_context_t *ctx, void *buf, zip_uint64_t len) { + size_t i; + if (len > SIZE_MAX) { + len = SIZE_MAX; + } + + if ((i = fread(buf, 1, (size_t)len, ctx->f)) == 0) { + if (ferror((FILE *)ctx->f)) { + zip_error_set(&ctx->error, ZIP_ER_READ, errno); + return -1; + } + } + + return (zip_int64_t)i; +} + + +bool +_zip_stdio_op_seek(zip_source_file_context_t *ctx, void *f, zip_int64_t offset, int whence) { +#if ZIP_FSEEK_MAX > ZIP_INT64_MAX + if (offset > ZIP_FSEEK_MAX || offset < ZIP_FSEEK_MIN) { + zip_error_set(&ctx->error, ZIP_ER_SEEK, EOVERFLOW); + return false; + } +#endif + + if (fseeko((FILE *)f, (off_t)offset, whence) < 0) { + zip_error_set(&ctx->error, ZIP_ER_SEEK, errno); + return false; + } + return true; +} + + +bool +_zip_stdio_op_stat(zip_source_file_context_t *ctx, zip_source_file_stat_t *st) { + struct stat sb; + + int ret; + + if (ctx->fname) { + ret = stat(ctx->fname, &sb); + } + else { + ret = fstat(fileno((FILE *)ctx->f), &sb); + } + + if (ret < 0) { + if (errno == ENOENT) { + st->exists = false; + return true; + } + zip_error_set(&ctx->error, ZIP_ER_READ, errno); + return false; + } + + st->size = (zip_uint64_t)sb.st_size; + st->mtime = sb.st_mtime; + + st->regular_file = S_ISREG(sb.st_mode); + st->exists = true; + + /* We're using UNIX file API, even on Windows; thus, we supply external file attributes with Unix values. */ + /* TODO: This could be improved on Windows by providing Windows-specific file attributes */ + ctx->attributes.valid = ZIP_FILE_ATTRIBUTES_HOST_SYSTEM | ZIP_FILE_ATTRIBUTES_EXTERNAL_FILE_ATTRIBUTES; + ctx->attributes.host_system = ZIP_OPSYS_UNIX; + ctx->attributes.external_file_attributes = (((zip_uint32_t)sb.st_mode) << 16) | ((sb.st_mode & S_IWUSR) ? 0 : 1); + + return true; +} + + +zip_int64_t +_zip_stdio_op_tell(zip_source_file_context_t *ctx, void *f) { + off_t offset = ftello((FILE *)f); + + if (offset < 0) { + zip_error_set(&ctx->error, ZIP_ER_SEEK, errno); + } + + return offset; +} + + +/* + * fopen replacement that sets the close-on-exec flag + * some implementations support an fopen 'e' flag for that, + * but e.g. macOS doesn't. + */ +FILE * +_zip_fopen_close_on_exec(const char *name, bool writeable) { + int fd; + int flags; + FILE *fp; + + flags = O_CLOEXEC; + if (writeable) { + flags |= O_RDWR; + } + else { + flags |= O_RDONLY; + } + + /* mode argument needed on Windows */ + if ((fd = open(name, flags, 0666)) < 0) { + return NULL; + } + if ((fp = fdopen(fd, writeable ? "r+b" : "rb")) == NULL) { + return NULL; + } + return fp; +} diff --git a/Source/Libraries/libzip/zip_source_free.c b/Source/Libraries/libzip/zip_source_free.c new file mode 100644 index 0000000..2650493 --- /dev/null +++ b/Source/Libraries/libzip/zip_source_free.c @@ -0,0 +1,71 @@ +/* + zip_source_free.c -- free zip data source + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN void +zip_source_free(zip_source_t *src) { + if (src == NULL) + return; + + if (src->refcount > 0) { + src->refcount--; + } + if (src->refcount > 0) { + return; + } + + if (ZIP_SOURCE_IS_OPEN_READING(src)) { + src->open_count = 1; /* force close */ + zip_source_close(src); + } + if (ZIP_SOURCE_IS_OPEN_WRITING(src)) { + zip_source_rollback_write(src); + } + + if (src->source_archive && !src->source_closed) { + _zip_deregister_source(src->source_archive, src); + } + + (void)_zip_source_call(src, NULL, 0, ZIP_SOURCE_FREE); + + if (src->src) { + zip_source_free(src->src); + } + + free(src); +} diff --git a/Source/Libraries/libzip/zip_source_function.c b/Source/Libraries/libzip/zip_source_function.c new file mode 100644 index 0000000..5602f1d --- /dev/null +++ b/Source/Libraries/libzip/zip_source_function.c @@ -0,0 +1,98 @@ +/* + zip_source_function.c -- create zip data source from callback function + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN zip_source_t * +zip_source_function(zip_t *za, zip_source_callback zcb, void *ud) { + if (za == NULL) { + return NULL; + } + + return zip_source_function_create(zcb, ud, &za->error); +} + + +ZIP_EXTERN zip_source_t * +zip_source_function_create(zip_source_callback zcb, void *ud, zip_error_t *error) { + zip_source_t *zs; + + if ((zs = _zip_source_new(error)) == NULL) + return NULL; + + zs->cb.f = zcb; + zs->ud = ud; + + zs->supports = zcb(ud, NULL, 0, ZIP_SOURCE_SUPPORTS); + if (zs->supports < 0) { + zs->supports = ZIP_SOURCE_SUPPORTS_READABLE; + } + + return zs; +} + + +ZIP_EXTERN void +zip_source_keep(zip_source_t *src) { + src->refcount++; +} + + +zip_source_t * +_zip_source_new(zip_error_t *error) { + zip_source_t *src; + + if ((src = (zip_source_t *)malloc(sizeof(*src))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + src->src = NULL; + src->cb.f = NULL; + src->ud = NULL; + src->open_count = 0; + src->write_state = ZIP_SOURCE_WRITE_CLOSED; + src->source_closed = false; + src->source_archive = NULL; + src->refcount = 1; + zip_error_init(&src->error); + src->eof = false; + src->had_read_error = false; + src->bytes_read = 0; + + return src; +} diff --git a/Source/Libraries/libzip/zip_source_get_file_attributes.c b/Source/Libraries/libzip/zip_source_get_file_attributes.c new file mode 100644 index 0000000..734767a --- /dev/null +++ b/Source/Libraries/libzip/zip_source_get_file_attributes.c @@ -0,0 +1,106 @@ +/* + zip_source_get_file_attributes.c -- get attributes for file from source + Copyright (C) 2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +ZIP_EXTERN void +zip_file_attributes_init(zip_file_attributes_t *attributes) { + attributes->valid = 0; + attributes->version = 1; +} + +int +zip_source_get_file_attributes(zip_source_t *src, zip_file_attributes_t *attributes) { + if (src->source_closed) { + return -1; + } + if (attributes == NULL) { + zip_error_set(&src->error, ZIP_ER_INVAL, 0); + return -1; + } + + zip_file_attributes_init(attributes); + + if (src->supports & ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_GET_FILE_ATTRIBUTES)) { + if (_zip_source_call(src, attributes, sizeof(*attributes), ZIP_SOURCE_GET_FILE_ATTRIBUTES) < 0) { + return -1; + } + } + + if (ZIP_SOURCE_IS_LAYERED(src)) { + zip_file_attributes_t lower_attributes; + + if (zip_source_get_file_attributes(src->src, &lower_attributes) < 0) { + _zip_error_set_from_source(&src->error, src->src); + return -1; + } + + if ((lower_attributes.valid & ZIP_FILE_ATTRIBUTES_HOST_SYSTEM) && (attributes->valid & ZIP_FILE_ATTRIBUTES_HOST_SYSTEM) == 0) { + attributes->host_system = lower_attributes.host_system; + attributes->valid |= ZIP_FILE_ATTRIBUTES_HOST_SYSTEM; + } + if ((lower_attributes.valid & ZIP_FILE_ATTRIBUTES_ASCII) && (attributes->valid & ZIP_FILE_ATTRIBUTES_ASCII) == 0) { + attributes->ascii = lower_attributes.ascii; + attributes->valid |= ZIP_FILE_ATTRIBUTES_ASCII; + } + if ((lower_attributes.valid & ZIP_FILE_ATTRIBUTES_VERSION_NEEDED)) { + if (attributes->valid & ZIP_FILE_ATTRIBUTES_VERSION_NEEDED) { + attributes->version_needed = ZIP_MAX(lower_attributes.version_needed, attributes->version_needed); + } + else { + attributes->version_needed = lower_attributes.version_needed; + attributes->valid |= ZIP_FILE_ATTRIBUTES_VERSION_NEEDED; + } + } + if ((lower_attributes.valid & ZIP_FILE_ATTRIBUTES_EXTERNAL_FILE_ATTRIBUTES) && (attributes->valid & ZIP_FILE_ATTRIBUTES_EXTERNAL_FILE_ATTRIBUTES) == 0) { + attributes->external_file_attributes = lower_attributes.external_file_attributes; + attributes->valid |= ZIP_FILE_ATTRIBUTES_EXTERNAL_FILE_ATTRIBUTES; + } + if ((lower_attributes.valid & ZIP_FILE_ATTRIBUTES_GENERAL_PURPOSE_BIT_FLAGS)) { + if (attributes->valid & ZIP_FILE_ATTRIBUTES_GENERAL_PURPOSE_BIT_FLAGS) { + /* only take from lower level what is not defined at current level */ + lower_attributes.general_purpose_bit_mask &= ~attributes->general_purpose_bit_mask; + + attributes->general_purpose_bit_flags |= lower_attributes.general_purpose_bit_flags & lower_attributes.general_purpose_bit_mask; + attributes->general_purpose_bit_mask |= lower_attributes.general_purpose_bit_mask; + } + else { + attributes->valid |= ZIP_FILE_ATTRIBUTES_GENERAL_PURPOSE_BIT_FLAGS; + attributes->general_purpose_bit_flags = lower_attributes.general_purpose_bit_flags; + attributes->general_purpose_bit_mask = lower_attributes.general_purpose_bit_mask; + } + } + } + + return 0; +} diff --git a/Source/Libraries/libzip/zip_source_is_deleted.c b/Source/Libraries/libzip/zip_source_is_deleted.c new file mode 100644 index 0000000..27c931f --- /dev/null +++ b/Source/Libraries/libzip/zip_source_is_deleted.c @@ -0,0 +1,41 @@ +/* + zip_source_is_deleted.c -- was archive was removed? + Copyright (C) 2014-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_source_is_deleted(zip_source_t *src) { + return src->write_state == ZIP_SOURCE_WRITE_REMOVED; +} diff --git a/Source/Libraries/libzip/zip_source_layered.c b/Source/Libraries/libzip/zip_source_layered.c new file mode 100644 index 0000000..a029869 --- /dev/null +++ b/Source/Libraries/libzip/zip_source_layered.c @@ -0,0 +1,67 @@ +/* + zip_source_layered.c -- create layered source + Copyright (C) 2009-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +zip_source_t * +zip_source_layered(zip_t *za, zip_source_t *src, zip_source_layered_callback cb, void *ud) { + if (za == NULL) + return NULL; + + return zip_source_layered_create(src, cb, ud, &za->error); +} + + +zip_source_t * +zip_source_layered_create(zip_source_t *src, zip_source_layered_callback cb, void *ud, zip_error_t *error) { + zip_source_t *zs; + + if ((zs = _zip_source_new(error)) == NULL) + return NULL; + + zip_source_keep(src); + zs->src = src; + zs->cb.l = cb; + zs->ud = ud; + + zs->supports = cb(src, ud, NULL, 0, ZIP_SOURCE_SUPPORTS); + if (zs->supports < 0) { + zs->supports = ZIP_SOURCE_SUPPORTS_READABLE; + } + + return zs; +} diff --git a/Source/Libraries/libzip/zip_source_open.c b/Source/Libraries/libzip/zip_source_open.c new file mode 100644 index 0000000..442f189 --- /dev/null +++ b/Source/Libraries/libzip/zip_source_open.c @@ -0,0 +1,76 @@ +/* + zip_source_open.c -- open zip_source (prepare for reading) + Copyright (C) 2009-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +ZIP_EXTERN int +zip_source_open(zip_source_t *src) { + if (src->source_closed) { + return -1; + } + if (src->write_state == ZIP_SOURCE_WRITE_REMOVED) { + zip_error_set(&src->error, ZIP_ER_DELETED, 0); + return -1; + } + + if (ZIP_SOURCE_IS_OPEN_READING(src)) { + if ((zip_source_supports(src) & ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_SEEK)) == 0) { + zip_error_set(&src->error, ZIP_ER_INUSE, 0); + return -1; + } + } + else { + if (ZIP_SOURCE_IS_LAYERED(src)) { + if (zip_source_open(src->src) < 0) { + _zip_error_set_from_source(&src->error, src->src); + return -1; + } + } + + if (_zip_source_call(src, NULL, 0, ZIP_SOURCE_OPEN) < 0) { + if (ZIP_SOURCE_IS_LAYERED(src)) { + zip_source_close(src->src); + } + return -1; + } + } + + src->eof = false; + src->had_read_error = false; + _zip_error_clear(&src->error); + src->bytes_read = 0; + src->open_count++; + + return 0; +} diff --git a/Source/Libraries/libzip/zip_source_pkware_decode.c b/Source/Libraries/libzip/zip_source_pkware_decode.c new file mode 100644 index 0000000..a1c9e3a --- /dev/null +++ b/Source/Libraries/libzip/zip_source_pkware_decode.c @@ -0,0 +1,220 @@ +/* + zip_source_pkware_decode.c -- Traditional PKWARE decryption routines + Copyright (C) 2009-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +struct trad_pkware { + char *password; + zip_pkware_keys_t keys; + zip_error_t error; +}; + + +static int decrypt_header(zip_source_t *, struct trad_pkware *); +static zip_int64_t pkware_decrypt(zip_source_t *, void *, void *, zip_uint64_t, zip_source_cmd_t); +static struct trad_pkware *trad_pkware_new(const char *password, zip_error_t *error); +static void trad_pkware_free(struct trad_pkware *); + + +zip_source_t * +zip_source_pkware_decode(zip_t *za, zip_source_t *src, zip_uint16_t em, int flags, const char *password) { + struct trad_pkware *ctx; + zip_source_t *s2; + + if (password == NULL || src == NULL || em != ZIP_EM_TRAD_PKWARE) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return NULL; + } + if (flags & ZIP_CODEC_ENCODE) { + zip_error_set(&za->error, ZIP_ER_ENCRNOTSUPP, 0); + return NULL; + } + + if ((ctx = trad_pkware_new(password, &za->error)) == NULL) { + return NULL; + } + + if ((s2 = zip_source_layered(za, src, pkware_decrypt, ctx)) == NULL) { + trad_pkware_free(ctx); + return NULL; + } + + return s2; +} + + +static int +decrypt_header(zip_source_t *src, struct trad_pkware *ctx) { + zip_uint8_t header[ZIP_CRYPTO_PKWARE_HEADERLEN]; + struct zip_stat st; + zip_int64_t n; + bool ok = false; + + if ((n = zip_source_read(src, header, ZIP_CRYPTO_PKWARE_HEADERLEN)) < 0) { + _zip_error_set_from_source(&ctx->error, src); + return -1; + } + + if (n != ZIP_CRYPTO_PKWARE_HEADERLEN) { + zip_error_set(&ctx->error, ZIP_ER_EOF, 0); + return -1; + } + + _zip_pkware_decrypt(&ctx->keys, header, header, ZIP_CRYPTO_PKWARE_HEADERLEN); + + if (zip_source_stat(src, &st)) { + /* stat failed, skip password validation */ + return 0; + } + + /* password verification - two ways: + * mtime - InfoZIP way, to avoid computing complete CRC before encrypting data + * CRC - old PKWare way + */ + + if (st.valid & ZIP_STAT_MTIME) { + unsigned short dostime, dosdate; + _zip_u2d_time(st.mtime, &dostime, &dosdate); + if (header[ZIP_CRYPTO_PKWARE_HEADERLEN - 1] == dostime >> 8) { + ok = true; + } + } + + if (st.valid & ZIP_STAT_CRC) { + if (header[ZIP_CRYPTO_PKWARE_HEADERLEN - 1] == st.crc >> 24) { + ok = true; + } + } + + if (!ok && ((st.valid & (ZIP_STAT_MTIME | ZIP_STAT_CRC)) != 0)) { + zip_error_set(&ctx->error, ZIP_ER_WRONGPASSWD, 0); + return -1; + } + + return 0; +} + + +static zip_int64_t +pkware_decrypt(zip_source_t *src, void *ud, void *data, zip_uint64_t len, zip_source_cmd_t cmd) { + struct trad_pkware *ctx; + zip_int64_t n; + + ctx = (struct trad_pkware *)ud; + + switch (cmd) { + case ZIP_SOURCE_OPEN: + _zip_pkware_keys_reset(&ctx->keys); + _zip_pkware_decrypt(&ctx->keys, NULL, (const zip_uint8_t *)ctx->password, strlen(ctx->password)); + if (decrypt_header(src, ctx) < 0) { + return -1; + } + return 0; + + case ZIP_SOURCE_READ: + if ((n = zip_source_read(src, data, len)) < 0) { + _zip_error_set_from_source(&ctx->error, src); + return -1; + } + + _zip_pkware_decrypt(&ctx->keys, (zip_uint8_t *)data, (zip_uint8_t *)data, (zip_uint64_t)n); + return n; + + case ZIP_SOURCE_CLOSE: + return 0; + + case ZIP_SOURCE_STAT: { + zip_stat_t *st; + + st = (zip_stat_t *)data; + + st->encryption_method = ZIP_EM_NONE; + st->valid |= ZIP_STAT_ENCRYPTION_METHOD; + if (st->valid & ZIP_STAT_COMP_SIZE) { + st->comp_size -= ZIP_CRYPTO_PKWARE_HEADERLEN; + } + + return 0; + } + + case ZIP_SOURCE_SUPPORTS: + return zip_source_make_command_bitmap(ZIP_SOURCE_OPEN, ZIP_SOURCE_READ, ZIP_SOURCE_CLOSE, ZIP_SOURCE_STAT, ZIP_SOURCE_ERROR, ZIP_SOURCE_FREE, -1); + + case ZIP_SOURCE_ERROR: + return zip_error_to_data(&ctx->error, data, len); + + case ZIP_SOURCE_FREE: + trad_pkware_free(ctx); + return 0; + + default: + zip_error_set(&ctx->error, ZIP_ER_INVAL, 0); + return -1; + } +} + + +static struct trad_pkware * +trad_pkware_new(const char *password, zip_error_t *error) { + struct trad_pkware *ctx; + + if ((ctx = (struct trad_pkware *)malloc(sizeof(*ctx))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + if ((ctx->password = strdup(password)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + free(ctx); + return NULL; + } + + zip_error_init(&ctx->error); + + return ctx; +} + + +static void +trad_pkware_free(struct trad_pkware *ctx) { + if (ctx == NULL) { + return; + } + + free(ctx->password); + free(ctx); +} diff --git a/Source/Libraries/libzip/zip_source_pkware_encode.c b/Source/Libraries/libzip/zip_source_pkware_encode.c new file mode 100644 index 0000000..941e64f --- /dev/null +++ b/Source/Libraries/libzip/zip_source_pkware_encode.c @@ -0,0 +1,250 @@ +/* + zip_source_pkware_encode.c -- Traditional PKWARE encryption routines + Copyright (C) 2009-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +struct trad_pkware { + char *password; + zip_pkware_keys_t keys; + zip_buffer_t *buffer; + bool eof; + zip_error_t error; +}; + + +static int encrypt_header(zip_source_t *, struct trad_pkware *); +static zip_int64_t pkware_encrypt(zip_source_t *, void *, void *, zip_uint64_t, zip_source_cmd_t); +static void trad_pkware_free(struct trad_pkware *); +static struct trad_pkware *trad_pkware_new(const char *password, zip_error_t *error); + + +zip_source_t * +zip_source_pkware_encode(zip_t *za, zip_source_t *src, zip_uint16_t em, int flags, const char *password) { + struct trad_pkware *ctx; + zip_source_t *s2; + + if (password == NULL || src == NULL || em != ZIP_EM_TRAD_PKWARE) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return NULL; + } + if (!(flags & ZIP_CODEC_ENCODE)) { + zip_error_set(&za->error, ZIP_ER_ENCRNOTSUPP, 0); + return NULL; + } + + if ((ctx = trad_pkware_new(password, &za->error)) == NULL) { + return NULL; + } + + if ((s2 = zip_source_layered(za, src, pkware_encrypt, ctx)) == NULL) { + trad_pkware_free(ctx); + return NULL; + } + + return s2; +} + + +static int +encrypt_header(zip_source_t *src, struct trad_pkware *ctx) { + struct zip_stat st; + unsigned short dostime, dosdate; + zip_uint8_t *header; + + if (zip_source_stat(src, &st) != 0) { + _zip_error_set_from_source(&ctx->error, src); + return -1; + } + + _zip_u2d_time(st.mtime, &dostime, &dosdate); + + if ((ctx->buffer = _zip_buffer_new(NULL, ZIP_CRYPTO_PKWARE_HEADERLEN)) == NULL) { + zip_error_set(&ctx->error, ZIP_ER_MEMORY, 0); + return -1; + } + + header = _zip_buffer_data(ctx->buffer); + + /* generate header from random bytes and mtime + see appnote.iz, XIII. Decryption, Step 2, last paragraph */ + // if (!zip_secure_random(header, ZIP_CRYPTO_PKWARE_HEADERLEN - 1)) { + if (0==0) { + zip_error_set(&ctx->error, ZIP_ER_INTERNAL, 0); + _zip_buffer_free(ctx->buffer); + ctx->buffer = NULL; + return -1; + } + header[ZIP_CRYPTO_PKWARE_HEADERLEN - 1] = (zip_uint8_t)((dostime >> 8) & 0xff); + + _zip_pkware_encrypt(&ctx->keys, header, header, ZIP_CRYPTO_PKWARE_HEADERLEN); + + return 0; +} + + +static zip_int64_t +pkware_encrypt(zip_source_t *src, void *ud, void *data, zip_uint64_t length, zip_source_cmd_t cmd) { + struct trad_pkware *ctx; + zip_int64_t n; + zip_uint64_t buffer_n; + + ctx = (struct trad_pkware *)ud; + + switch (cmd) { + case ZIP_SOURCE_OPEN: + ctx->eof = false; + + /* initialize keys */ + _zip_pkware_keys_reset(&ctx->keys); + _zip_pkware_encrypt(&ctx->keys, NULL, (const zip_uint8_t *)ctx->password, strlen(ctx->password)); + + if (encrypt_header(src, ctx) < 0) { + return -1; + } + return 0; + + case ZIP_SOURCE_READ: + buffer_n = 0; + + if (ctx->buffer) { + /* write header values to data */ + buffer_n = _zip_buffer_read(ctx->buffer, data, length); + data = (zip_uint8_t *)data + buffer_n; + length -= buffer_n; + + if (_zip_buffer_eof(ctx->buffer)) { + _zip_buffer_free(ctx->buffer); + ctx->buffer = NULL; + } + } + + if (ctx->eof) { + return (zip_int64_t)buffer_n; + } + + if ((n = zip_source_read(src, data, length)) < 0) { + _zip_error_set_from_source(&ctx->error, src); + return -1; + } + + _zip_pkware_encrypt(&ctx->keys, (zip_uint8_t *)data, (zip_uint8_t *)data, (zip_uint64_t)n); + + if ((zip_uint64_t)n < length) { + ctx->eof = true; + } + + return (zip_int64_t)buffer_n + n; + + case ZIP_SOURCE_CLOSE: + _zip_buffer_free(ctx->buffer); + ctx->buffer = NULL; + return 0; + + case ZIP_SOURCE_STAT: { + zip_stat_t *st; + + st = (zip_stat_t *)data; + st->encryption_method = ZIP_EM_TRAD_PKWARE; + st->valid |= ZIP_STAT_ENCRYPTION_METHOD; + if (st->valid & ZIP_STAT_COMP_SIZE) { + st->comp_size += ZIP_CRYPTO_PKWARE_HEADERLEN; + } + + return 0; + } + + case ZIP_SOURCE_GET_FILE_ATTRIBUTES: { + zip_file_attributes_t *attributes = (zip_file_attributes_t *)data; + if (length < sizeof(*attributes)) { + zip_error_set(&ctx->error, ZIP_ER_INVAL, 0); + return -1; + } + attributes->valid |= ZIP_FILE_ATTRIBUTES_VERSION_NEEDED; + attributes->version_needed = 20; + + return 0; + } + + case ZIP_SOURCE_SUPPORTS: + return zip_source_make_command_bitmap(ZIP_SOURCE_OPEN, ZIP_SOURCE_READ, ZIP_SOURCE_CLOSE, ZIP_SOURCE_STAT, ZIP_SOURCE_ERROR, ZIP_SOURCE_FREE, ZIP_SOURCE_GET_FILE_ATTRIBUTES, -1); + + case ZIP_SOURCE_ERROR: + return zip_error_to_data(&ctx->error, data, length); + + case ZIP_SOURCE_FREE: + trad_pkware_free(ctx); + return 0; + + default: + zip_error_set(&ctx->error, ZIP_ER_INVAL, 0); + return -1; + } +} + + +static struct trad_pkware * +trad_pkware_new(const char *password, zip_error_t *error) { + struct trad_pkware *ctx; + + if ((ctx = (struct trad_pkware *)malloc(sizeof(*ctx))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + if ((ctx->password = strdup(password)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + free(ctx); + return NULL; + } + ctx->buffer = NULL; + zip_error_init(&ctx->error); + + return ctx; +} + + +static void +trad_pkware_free(struct trad_pkware *ctx) { + if (ctx == NULL) { + return; + } + + free(ctx->password); + _zip_buffer_free(ctx->buffer); + zip_error_fini(&ctx->error); + free(ctx); +} diff --git a/Source/Libraries/libzip/zip_source_read.c b/Source/Libraries/libzip/zip_source_read.c new file mode 100644 index 0000000..f146ab0 --- /dev/null +++ b/Source/Libraries/libzip/zip_source_read.c @@ -0,0 +1,96 @@ +/* + zip_source_read.c -- read data from zip_source + Copyright (C) 2009-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +zip_int64_t +zip_source_read(zip_source_t *src, void *data, zip_uint64_t len) { + zip_uint64_t bytes_read; + zip_int64_t n; + + if (src->source_closed) { + return -1; + } + if (!ZIP_SOURCE_IS_OPEN_READING(src) || len > ZIP_INT64_MAX || (len > 0 && data == NULL)) { + zip_error_set(&src->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (src->had_read_error) { + return -1; + } + + if (_zip_source_eof(src)) { + return 0; + } + + if (len == 0) { + return 0; + } + + bytes_read = 0; + while (bytes_read < len) { + if ((n = _zip_source_call(src, (zip_uint8_t *)data + bytes_read, len - bytes_read, ZIP_SOURCE_READ)) < 0) { + src->had_read_error = true; + if (bytes_read == 0) { + return -1; + } + else { + return (zip_int64_t)bytes_read; + } + } + + if (n == 0) { + src->eof = 1; + break; + } + + bytes_read += (zip_uint64_t)n; + } + + if (src->bytes_read + bytes_read < src->bytes_read) { + src->bytes_read = ZIP_UINT64_MAX; + } + else { + src->bytes_read += bytes_read; + } + return (zip_int64_t)bytes_read; +} + + +bool +_zip_source_eof(zip_source_t *src) { + return src->eof; +} diff --git a/Source/Libraries/libzip/zip_source_remove.c b/Source/Libraries/libzip/zip_source_remove.c new file mode 100644 index 0000000..a6ccd7e --- /dev/null +++ b/Source/Libraries/libzip/zip_source_remove.c @@ -0,0 +1,60 @@ +/* + zip_source_remove.c -- remove empty archive + Copyright (C) 2014-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +int +zip_source_remove(zip_source_t *src) { + if (src->write_state == ZIP_SOURCE_WRITE_REMOVED) { + return 0; + } + + if (ZIP_SOURCE_IS_OPEN_READING(src)) { + if (zip_source_close(src) < 0) { + return -1; + } + } + if (src->write_state != ZIP_SOURCE_WRITE_CLOSED) { + zip_source_rollback_write(src); + } + + if (_zip_source_call(src, NULL, 0, ZIP_SOURCE_REMOVE) < 0) { + return -1; + } + + src->write_state = ZIP_SOURCE_WRITE_REMOVED; + + return 0; +} diff --git a/Source/Libraries/libzip/zip_source_rollback_write.c b/Source/Libraries/libzip/zip_source_rollback_write.c new file mode 100644 index 0000000..d21b1ff --- /dev/null +++ b/Source/Libraries/libzip/zip_source_rollback_write.c @@ -0,0 +1,46 @@ +/* + zip_source_rollback_write.c -- discard changes + Copyright (C) 2014-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN void +zip_source_rollback_write(zip_source_t *src) { + if (src->write_state != ZIP_SOURCE_WRITE_OPEN && src->write_state != ZIP_SOURCE_WRITE_FAILED) { + return; + } + + _zip_source_call(src, NULL, 0, ZIP_SOURCE_ROLLBACK_WRITE); + src->write_state = ZIP_SOURCE_WRITE_CLOSED; +} diff --git a/Source/Libraries/libzip/zip_source_seek.c b/Source/Libraries/libzip/zip_source_seek.c new file mode 100644 index 0000000..29d1e96 --- /dev/null +++ b/Source/Libraries/libzip/zip_source_seek.c @@ -0,0 +1,95 @@ +/* + zip_source_seek.c -- seek to offset + Copyright (C) 2014-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_source_seek(zip_source_t *src, zip_int64_t offset, int whence) { + zip_source_args_seek_t args; + + if (src->source_closed) { + return -1; + } + if (!ZIP_SOURCE_IS_OPEN_READING(src) || (whence != SEEK_SET && whence != SEEK_CUR && whence != SEEK_END)) { + zip_error_set(&src->error, ZIP_ER_INVAL, 0); + return -1; + } + + args.offset = offset; + args.whence = whence; + + if (_zip_source_call(src, &args, sizeof(args), ZIP_SOURCE_SEEK) < 0) { + return -1; + } + + src->eof = 0; + return 0; +} + + +zip_int64_t +zip_source_seek_compute_offset(zip_uint64_t offset, zip_uint64_t length, void *data, zip_uint64_t data_length, zip_error_t *error) { + zip_int64_t new_offset; + zip_source_args_seek_t *args = ZIP_SOURCE_GET_ARGS(zip_source_args_seek_t, data, data_length, error); + + if (args == NULL) { + return -1; + } + + switch (args->whence) { + case SEEK_CUR: + new_offset = (zip_int64_t)offset + args->offset; + break; + + case SEEK_END: + new_offset = (zip_int64_t)length + args->offset; + break; + + case SEEK_SET: + new_offset = args->offset; + break; + + default: + zip_error_set(error, ZIP_ER_INVAL, 0); + return -1; + } + + if (new_offset < 0 || (zip_uint64_t)new_offset > length) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return -1; + } + + return new_offset; +} diff --git a/Source/Libraries/libzip/zip_source_seek_write.c b/Source/Libraries/libzip/zip_source_seek_write.c new file mode 100644 index 0000000..5fa2a81 --- /dev/null +++ b/Source/Libraries/libzip/zip_source_seek_write.c @@ -0,0 +1,51 @@ +/* + zip_source_seek_write.c -- seek to offset for writing + Copyright (C) 2014-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_source_seek_write(zip_source_t *src, zip_int64_t offset, int whence) { + zip_source_args_seek_t args; + + if (!ZIP_SOURCE_IS_OPEN_WRITING(src) || (whence != SEEK_SET && whence != SEEK_CUR && whence != SEEK_END)) { + zip_error_set(&src->error, ZIP_ER_INVAL, 0); + return -1; + } + + args.offset = offset; + args.whence = whence; + + return (_zip_source_call(src, &args, sizeof(args), ZIP_SOURCE_SEEK_WRITE) < 0 ? -1 : 0); +} diff --git a/Source/Libraries/libzip/zip_source_stat.c b/Source/Libraries/libzip/zip_source_stat.c new file mode 100644 index 0000000..46eb92d --- /dev/null +++ b/Source/Libraries/libzip/zip_source_stat.c @@ -0,0 +1,62 @@ +/* + zip_source_stat.c -- get meta information from zip_source + Copyright (C) 2009-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_source_stat(zip_source_t *src, zip_stat_t *st) { + if (src->source_closed) { + return -1; + } + if (st == NULL) { + zip_error_set(&src->error, ZIP_ER_INVAL, 0); + return -1; + } + + zip_stat_init(st); + + if (ZIP_SOURCE_IS_LAYERED(src)) { + if (zip_source_stat(src->src, st) < 0) { + _zip_error_set_from_source(&src->error, src->src); + return -1; + } + } + + if (_zip_source_call(src, st, sizeof(*st), ZIP_SOURCE_STAT) < 0) { + return -1; + } + + return 0; +} diff --git a/Source/Libraries/libzip/zip_source_supports.c b/Source/Libraries/libzip/zip_source_supports.c new file mode 100644 index 0000000..b4575a7 --- /dev/null +++ b/Source/Libraries/libzip/zip_source_supports.c @@ -0,0 +1,65 @@ +/* + zip_source_supports.c -- check for supported functions + Copyright (C) 2014-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +zip_int64_t +zip_source_supports(zip_source_t *src) { + return src->supports; +} + + +ZIP_EXTERN zip_int64_t +zip_source_make_command_bitmap(zip_source_cmd_t cmd0, ...) { + zip_int64_t bitmap; + va_list ap; + + bitmap = ZIP_SOURCE_MAKE_COMMAND_BITMASK(cmd0); + + + va_start(ap, cmd0); + for (;;) { + int cmd = va_arg(ap, int); + if (cmd < 0) { + break; + } + bitmap |= ZIP_SOURCE_MAKE_COMMAND_BITMASK(cmd); + } + va_end(ap); + + return bitmap; +} diff --git a/Source/Libraries/libzip/zip_source_tell.c b/Source/Libraries/libzip/zip_source_tell.c new file mode 100644 index 0000000..b17412b --- /dev/null +++ b/Source/Libraries/libzip/zip_source_tell.c @@ -0,0 +1,57 @@ +/* + zip_source_tell.c -- report current offset + Copyright (C) 2014-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN zip_int64_t +zip_source_tell(zip_source_t *src) { + if (src->source_closed) { + return -1; + } + if (!ZIP_SOURCE_IS_OPEN_READING(src)) { + zip_error_set(&src->error, ZIP_ER_INVAL, 0); + return -1; + } + + if ((src->supports & (ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_TELL) | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_SEEK))) == 0) { + if (src->bytes_read > ZIP_INT64_MAX) { + zip_error_set(&src->error, ZIP_ER_TELL, EOVERFLOW); + return -1; + } + return (zip_int64_t)src->bytes_read; + } + + return _zip_source_call(src, NULL, 0, ZIP_SOURCE_TELL); +} diff --git a/Source/Libraries/libzip/zip_source_tell_write.c b/Source/Libraries/libzip/zip_source_tell_write.c new file mode 100644 index 0000000..c09a79f --- /dev/null +++ b/Source/Libraries/libzip/zip_source_tell_write.c @@ -0,0 +1,46 @@ +/* + zip_source_tell_write.c -- report current offset for writing + Copyright (C) 2014-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN zip_int64_t +zip_source_tell_write(zip_source_t *src) { + if (!ZIP_SOURCE_IS_OPEN_WRITING(src)) { + zip_error_set(&src->error, ZIP_ER_INVAL, 0); + return -1; + } + + return _zip_source_call(src, NULL, 0, ZIP_SOURCE_TELL_WRITE); +} diff --git a/Source/Libraries/libzip/zip_source_window.c b/Source/Libraries/libzip/zip_source_window.c new file mode 100644 index 0000000..b63ba1d --- /dev/null +++ b/Source/Libraries/libzip/zip_source_window.c @@ -0,0 +1,294 @@ +/* + zip_source_window.c -- return part of lower source + Copyright (C) 2012-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +struct window { + zip_uint64_t start; /* where in file we start reading */ + zip_uint64_t end; /* where in file we stop reading */ + + /* if not NULL, read file data for this file */ + zip_t *source_archive; + zip_uint64_t source_index; + + zip_uint64_t offset; /* offset in src for next read */ + + zip_stat_t stat; + zip_file_attributes_t attributes; + zip_error_t error; + zip_int64_t supports; + bool needs_seek; +}; + +static zip_int64_t window_read(zip_source_t *, void *, void *, zip_uint64_t, zip_source_cmd_t); + + +zip_source_t * +zip_source_window(zip_t *za, zip_source_t *src, zip_uint64_t start, zip_uint64_t len) { + return _zip_source_window_new(src, start, len, NULL, 0, NULL, 0, &za->error); +} + + +zip_source_t * +_zip_source_window_new(zip_source_t *src, zip_uint64_t start, zip_uint64_t length, zip_stat_t *st, zip_file_attributes_t *attributes, zip_t *source_archive, zip_uint64_t source_index, zip_error_t *error) { + struct window *ctx; + + if (src == NULL || start + length < start || (source_archive == NULL && source_index != 0)) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + if ((ctx = (struct window *)malloc(sizeof(*ctx))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + ctx->start = start; + ctx->end = start + length; + zip_stat_init(&ctx->stat); + if (attributes != NULL) { + memcpy(&ctx->attributes, attributes, sizeof(ctx->attributes)); + } + else { + zip_file_attributes_init(&ctx->attributes); + } + ctx->source_archive = source_archive; + ctx->source_index = source_index; + zip_error_init(&ctx->error); + ctx->supports = (zip_source_supports(src) & ZIP_SOURCE_SUPPORTS_SEEKABLE) | (zip_source_make_command_bitmap(ZIP_SOURCE_GET_FILE_ATTRIBUTES, ZIP_SOURCE_SUPPORTS, ZIP_SOURCE_TELL, -1)); + ctx->needs_seek = (ctx->supports & ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_SEEK)) ? true : false; + + if (st) { + if (_zip_stat_merge(&ctx->stat, st, error) < 0) { + free(ctx); + return NULL; + } + } + + return zip_source_layered_create(src, window_read, ctx, error); +} + + +int +_zip_source_set_source_archive(zip_source_t *src, zip_t *za) { + src->source_archive = za; + return _zip_register_source(za, src); +} + + +/* called by zip_discard to avoid operating on file from closed archive */ +void +_zip_source_invalidate(zip_source_t *src) { + src->source_closed = 1; + + if (zip_error_code_zip(&src->error) == ZIP_ER_OK) { + zip_error_set(&src->error, ZIP_ER_ZIPCLOSED, 0); + } +} + + +static zip_int64_t +window_read(zip_source_t *src, void *_ctx, void *data, zip_uint64_t len, zip_source_cmd_t cmd) { + struct window *ctx; + zip_int64_t ret; + zip_uint64_t n, i; + + ctx = (struct window *)_ctx; + + switch (cmd) { + case ZIP_SOURCE_CLOSE: + return 0; + + case ZIP_SOURCE_ERROR: + return zip_error_to_data(&ctx->error, data, len); + + case ZIP_SOURCE_FREE: + free(ctx); + return 0; + + case ZIP_SOURCE_OPEN: + if (ctx->source_archive) { + zip_uint64_t offset; + + if ((offset = _zip_file_get_offset(ctx->source_archive, ctx->source_index, &ctx->error)) == 0) { + return -1; + } + if (ctx->end + offset < ctx->end) { + /* zip archive data claims end of data past zip64 limits */ + zip_error_set(&ctx->error, ZIP_ER_INCONS, 0); + return -1; + } + ctx->start += offset; + ctx->end += offset; + ctx->source_archive = NULL; + } + + if (!ctx->needs_seek) { + DEFINE_BYTE_ARRAY(b, BUFSIZE); + + if (!byte_array_init(b, BUFSIZE)) { + zip_error_set(&ctx->error, ZIP_ER_MEMORY, 0); + return -1; + } + + for (n = 0; n < ctx->start; n += (zip_uint64_t)ret) { + i = (ctx->start - n > BUFSIZE ? BUFSIZE : ctx->start - n); + if ((ret = zip_source_read(src, b, i)) < 0) { + _zip_error_set_from_source(&ctx->error, src); + byte_array_fini(b); + return -1; + } + if (ret == 0) { + zip_error_set(&ctx->error, ZIP_ER_EOF, 0); + byte_array_fini(b); + return -1; + } + } + + byte_array_fini(b); + } + + ctx->offset = ctx->start; + return 0; + + case ZIP_SOURCE_READ: + if (len > ctx->end - ctx->offset) + len = ctx->end - ctx->offset; + + if (len == 0) + return 0; + + if (ctx->needs_seek) { + if (zip_source_seek(src, (zip_int64_t)ctx->offset, SEEK_SET) < 0) { + _zip_error_set_from_source(&ctx->error, src); + return -1; + } + } + + if ((ret = zip_source_read(src, data, len)) < 0) { + zip_error_set(&ctx->error, ZIP_ER_EOF, 0); + return -1; + } + + ctx->offset += (zip_uint64_t)ret; + + if (ret == 0) { + if (ctx->offset < ctx->end) { + zip_error_set(&ctx->error, ZIP_ER_EOF, 0); + return -1; + } + } + return ret; + + case ZIP_SOURCE_SEEK: { + zip_int64_t new_offset = zip_source_seek_compute_offset(ctx->offset - ctx->start, ctx->end - ctx->start, data, len, &ctx->error); + + if (new_offset < 0) { + return -1; + } + + ctx->offset = (zip_uint64_t)new_offset + ctx->start; + return 0; + } + + case ZIP_SOURCE_STAT: { + zip_stat_t *st; + + st = (zip_stat_t *)data; + + if (_zip_stat_merge(st, &ctx->stat, &ctx->error) < 0) { + return -1; + } + return 0; + } + + case ZIP_SOURCE_GET_FILE_ATTRIBUTES: + if (len < sizeof(ctx->attributes)) { + zip_error_set(&ctx->error, ZIP_ER_INVAL, 0); + return -1; + } + + memcpy(data, &ctx->attributes, sizeof(ctx->attributes)); + return sizeof(ctx->attributes); + + case ZIP_SOURCE_SUPPORTS: + return ctx->supports; + + case ZIP_SOURCE_TELL: + return (zip_int64_t)(ctx->offset - ctx->start); + + default: + zip_error_set(&ctx->error, ZIP_ER_OPNOTSUPP, 0); + return -1; + } +} + + +void +_zip_deregister_source(zip_t *za, zip_source_t *src) { + unsigned int i; + + for (i = 0; i < za->nopen_source; i++) { + if (za->open_source[i] == src) { + za->open_source[i] = za->open_source[za->nopen_source - 1]; + za->nopen_source--; + break; + } + } +} + + +int +_zip_register_source(zip_t *za, zip_source_t *src) { + zip_source_t **open_source; + + if (za->nopen_source + 1 >= za->nopen_source_alloc) { + unsigned int n; + n = za->nopen_source_alloc + 10; + open_source = (zip_source_t **)realloc(za->open_source, n * sizeof(zip_source_t *)); + if (open_source == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + za->nopen_source_alloc = n; + za->open_source = open_source; + } + + za->open_source[za->nopen_source++] = src; + + return 0; +} diff --git a/Source/Libraries/libzip/zip_source_write.c b/Source/Libraries/libzip/zip_source_write.c new file mode 100644 index 0000000..33bf9c9 --- /dev/null +++ b/Source/Libraries/libzip/zip_source_write.c @@ -0,0 +1,46 @@ +/* + zip_source_write.c -- start a new file for writing + Copyright (C) 2014-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN zip_int64_t +zip_source_write(zip_source_t *src, const void *data, zip_uint64_t length) { + if (!ZIP_SOURCE_IS_OPEN_WRITING(src) || length > ZIP_INT64_MAX) { + zip_error_set(&src->error, ZIP_ER_INVAL, 0); + return -1; + } + + return _zip_source_call(src, (void *)data, length, ZIP_SOURCE_WRITE); +} diff --git a/Source/Libraries/libzip/zip_source_zip.c b/Source/Libraries/libzip/zip_source_zip.c new file mode 100644 index 0000000..cb62540 --- /dev/null +++ b/Source/Libraries/libzip/zip_source_zip.c @@ -0,0 +1,56 @@ +/* + zip_source_zip.c -- create data source from zip file + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN zip_source_t * +zip_source_zip(zip_t *za, zip_t *srcza, zip_uint64_t srcidx, zip_flags_t flags, zip_uint64_t start, zip_int64_t len) { + if (len < -1) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return NULL; + } + + if (len == -1) + len = 0; + + if (start == 0 && len == 0) + flags |= ZIP_FL_COMPRESSED; + else + flags &= ~ZIP_FL_COMPRESSED; + + return _zip_source_zip_new(za, srcza, srcidx, flags, start, (zip_uint64_t)len, NULL); +} diff --git a/Source/Libraries/libzip/zip_source_zip_new.c b/Source/Libraries/libzip/zip_source_zip_new.c new file mode 100644 index 0000000..ffb2bdf --- /dev/null +++ b/Source/Libraries/libzip/zip_source_zip_new.c @@ -0,0 +1,191 @@ +/* + zip_source_zip_new.c -- prepare data structures for zip_fopen/zip_source_zip + Copyright (C) 2012-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +static void _zip_file_attributes_from_dirent(zip_file_attributes_t *attributes, zip_dirent_t *de); + +zip_source_t * +_zip_source_zip_new(zip_t *za, zip_t *srcza, zip_uint64_t srcidx, zip_flags_t flags, zip_uint64_t start, zip_uint64_t len, const char *password) { + zip_source_t *src, *s2; + zip_stat_t st; + zip_file_attributes_t attributes; + zip_dirent_t *de; + bool partial_data, needs_crc, needs_decrypt, needs_decompress; + + if (za == NULL) { + return NULL; + } + + if (srcza == NULL || srcidx >= srcza->nentry) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return NULL; + } + + if ((flags & ZIP_FL_UNCHANGED) == 0 && (ZIP_ENTRY_DATA_CHANGED(srcza->entry + srcidx) || srcza->entry[srcidx].deleted)) { + zip_error_set(&za->error, ZIP_ER_CHANGED, 0); + return NULL; + } + + if (zip_stat_index(srcza, srcidx, flags | ZIP_FL_UNCHANGED, &st) < 0) { + zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); + return NULL; + } + + if (flags & ZIP_FL_ENCRYPTED) { + flags |= ZIP_FL_COMPRESSED; + } + + if ((start > 0 || len > 0) && (flags & ZIP_FL_COMPRESSED)) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return NULL; + } + + /* overflow or past end of file */ + if ((start > 0 || len > 0) && (start + len < start || start + len > st.size)) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return NULL; + } + + if (len == 0) { + len = st.size - start; + } + + partial_data = len < st.size; + needs_decrypt = ((flags & ZIP_FL_ENCRYPTED) == 0) && (st.encryption_method != ZIP_EM_NONE); + needs_decompress = ((flags & ZIP_FL_COMPRESSED) == 0) && (st.comp_method != ZIP_CM_STORE); + /* when reading the whole file, check for CRC errors */ + needs_crc = ((flags & ZIP_FL_COMPRESSED) == 0 || st.comp_method == ZIP_CM_STORE) && !partial_data; + + if (needs_decrypt) { + if (password == NULL) { + password = za->default_password; + } + if (password == NULL) { + zip_error_set(&za->error, ZIP_ER_NOPASSWD, 0); + return NULL; + } + } + + if ((de = _zip_get_dirent(srcza, srcidx, flags, &za->error)) == NULL) { + return NULL; + } + _zip_file_attributes_from_dirent(&attributes, de); + + if (st.comp_size == 0) { + return zip_source_buffer_with_attributes(za, NULL, 0, 0, &attributes); + } + + if (partial_data && !needs_decrypt && !needs_decompress) { + struct zip_stat st2; + + st2.size = len; + st2.comp_size = len; + st2.comp_method = ZIP_CM_STORE; + st2.mtime = st.mtime; + st2.valid = ZIP_STAT_SIZE | ZIP_STAT_COMP_SIZE | ZIP_STAT_COMP_METHOD | ZIP_STAT_MTIME; + + if ((src = _zip_source_window_new(srcza->src, start, len, &st2, &attributes, srcza, srcidx, &za->error)) == NULL) { + return NULL; + } + } + else { + if ((src = _zip_source_window_new(srcza->src, 0, st.comp_size, &st, &attributes, srcza, srcidx, &za->error)) == NULL) { + return NULL; + } + } + + if (_zip_source_set_source_archive(src, srcza) < 0) { + zip_source_free(src); + return NULL; + } + + /* creating a layered source calls zip_keep() on the lower layer, so we free it */ + + if (needs_decrypt) { + zip_encryption_implementation enc_impl; + + if ((enc_impl = _zip_get_encryption_implementation(st.encryption_method, ZIP_CODEC_DECODE)) == NULL) { + zip_error_set(&za->error, ZIP_ER_ENCRNOTSUPP, 0); + return NULL; + } + + s2 = enc_impl(za, src, st.encryption_method, 0, password); + zip_source_free(src); + if (s2 == NULL) { + return NULL; + } + src = s2; + } + if (needs_decompress) { + s2 = zip_source_decompress(za, src, st.comp_method); + zip_source_free(src); + if (s2 == NULL) { + return NULL; + } + src = s2; + } + if (needs_crc) { + s2 = zip_source_crc(za, src, 1); + zip_source_free(src); + if (s2 == NULL) { + return NULL; + } + src = s2; + } + + if (partial_data && (needs_decrypt || needs_decompress)) { + s2 = zip_source_window(za, src, start, len); + zip_source_free(src); + if (s2 == NULL) { + return NULL; + } + src = s2; + } + + return src; +} + +static void +_zip_file_attributes_from_dirent(zip_file_attributes_t *attributes, zip_dirent_t *de) { + zip_file_attributes_init(attributes); + attributes->valid = ZIP_FILE_ATTRIBUTES_ASCII | ZIP_FILE_ATTRIBUTES_HOST_SYSTEM | ZIP_FILE_ATTRIBUTES_EXTERNAL_FILE_ATTRIBUTES | ZIP_FILE_ATTRIBUTES_GENERAL_PURPOSE_BIT_FLAGS; + attributes->ascii = de->int_attrib & 1; + attributes->host_system = de->version_madeby >> 8; + attributes->external_file_attributes = de->ext_attrib; + attributes->general_purpose_bit_flags = de->bitflags; + attributes->general_purpose_bit_mask = ZIP_FILE_ATTRIBUTES_GENERAL_PURPOSE_BIT_FLAGS_ALLOWED_MASK; +} diff --git a/Source/Libraries/libzip/zip_stat.c b/Source/Libraries/libzip/zip_stat.c new file mode 100644 index 0000000..c328dcf --- /dev/null +++ b/Source/Libraries/libzip/zip_stat.c @@ -0,0 +1,46 @@ +/* + zip_stat.c -- get information about file by name + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_stat(zip_t *za, const char *fname, zip_flags_t flags, zip_stat_t *st) { + zip_int64_t idx; + + if ((idx = zip_name_locate(za, fname, flags)) < 0) + return -1; + + return zip_stat_index(za, (zip_uint64_t)idx, flags, st); +} diff --git a/Source/Libraries/libzip/zip_stat_index.c b/Source/Libraries/libzip/zip_stat_index.c new file mode 100644 index 0000000..62dc045 --- /dev/null +++ b/Source/Libraries/libzip/zip_stat_index.c @@ -0,0 +1,80 @@ +/* + zip_stat_index.c -- get information about file by index + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_stat_index(zip_t *za, zip_uint64_t index, zip_flags_t flags, zip_stat_t *st) { + const char *name; + zip_dirent_t *de; + + if ((de = _zip_get_dirent(za, index, flags, NULL)) == NULL) + return -1; + + if ((name = zip_get_name(za, index, flags)) == NULL) + return -1; + + + if ((flags & ZIP_FL_UNCHANGED) == 0 && ZIP_ENTRY_DATA_CHANGED(za->entry + index)) { + zip_entry_t *entry = za->entry + index; + + if (zip_source_stat(entry->source, st) < 0) { + zip_error_set(&za->error, ZIP_ER_CHANGED, 0); + return -1; + } + + if (entry->changes != NULL && entry->changes->changed & ZIP_DIRENT_LAST_MOD) { + st->mtime = de->last_mod; + st->valid |= ZIP_STAT_MTIME; + } + } + else { + zip_stat_init(st); + + st->crc = de->crc; + st->size = de->uncomp_size; + st->mtime = de->last_mod; + st->comp_size = de->comp_size; + st->comp_method = (zip_uint16_t)de->comp_method; + st->encryption_method = de->encryption_method; + st->valid = (de->crc_valid ? ZIP_STAT_CRC : 0) | ZIP_STAT_SIZE | ZIP_STAT_MTIME | ZIP_STAT_COMP_SIZE | ZIP_STAT_COMP_METHOD | ZIP_STAT_ENCRYPTION_METHOD; + } + + st->index = index; + st->name = name; + st->valid |= ZIP_STAT_INDEX | ZIP_STAT_NAME; + + return 0; +} diff --git a/Source/Libraries/libzip/zip_stat_init.c b/Source/Libraries/libzip/zip_stat_init.c new file mode 100644 index 0000000..0cf51ef --- /dev/null +++ b/Source/Libraries/libzip/zip_stat_init.c @@ -0,0 +1,83 @@ +/* + zip_stat_init.c -- initialize struct zip_stat. + Copyright (C) 2006-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN void +zip_stat_init(zip_stat_t *st) { + st->valid = 0; + st->name = NULL; + st->index = ZIP_UINT64_MAX; + st->crc = 0; + st->mtime = (time_t)-1; + st->size = 0; + st->comp_size = 0; + st->comp_method = ZIP_CM_STORE; + st->encryption_method = ZIP_EM_NONE; +} + + +int +_zip_stat_merge(zip_stat_t *dst, const zip_stat_t *src, zip_error_t *error) { + /* name is not merged, since zip_stat_t doesn't own it, and src may not be valid as long as dst */ + if (src->valid & ZIP_STAT_INDEX) { + dst->index = src->index; + } + if (src->valid & ZIP_STAT_SIZE) { + dst->size = src->size; + } + if (src->valid & ZIP_STAT_COMP_SIZE) { + dst->comp_size = src->comp_size; + } + if (src->valid & ZIP_STAT_MTIME) { + dst->mtime = src->mtime; + } + if (src->valid & ZIP_STAT_CRC) { + dst->crc = src->crc; + } + if (src->valid & ZIP_STAT_COMP_METHOD) { + dst->comp_method = src->comp_method; + } + if (src->valid & ZIP_STAT_ENCRYPTION_METHOD) { + dst->encryption_method = src->encryption_method; + } + if (src->valid & ZIP_STAT_FLAGS) { + dst->flags = src->flags; + } + dst->valid |= src->valid; + + return 0; +} diff --git a/Source/Libraries/libzip/zip_strerror.c b/Source/Libraries/libzip/zip_strerror.c new file mode 100644 index 0000000..6adec16 --- /dev/null +++ b/Source/Libraries/libzip/zip_strerror.c @@ -0,0 +1,41 @@ +/* + zip_sterror.c -- get string representation of zip error + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN const char * +zip_strerror(zip_t *za) { + return zip_error_strerror(&za->error); +} diff --git a/Source/Libraries/libzip/zip_string.c b/Source/Libraries/libzip/zip_string.c new file mode 100644 index 0000000..2c6f428 --- /dev/null +++ b/Source/Libraries/libzip/zip_string.c @@ -0,0 +1,178 @@ +/* + zip_string.c -- string handling (with encoding) + Copyright (C) 2012-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" + +zip_uint32_t +_zip_string_crc32(const zip_string_t *s) { + zip_uint32_t crc; + + crc = (zip_uint32_t)crc32(0L, Z_NULL, 0); + + if (s != NULL) + crc = (zip_uint32_t)crc32(crc, s->raw, s->length); + + return crc; +} + + +int +_zip_string_equal(const zip_string_t *a, const zip_string_t *b) { + if (a == NULL || b == NULL) + return a == b; + + if (a->length != b->length) + return 0; + + /* TODO: encoding */ + + return (memcmp(a->raw, b->raw, a->length) == 0); +} + + +void +_zip_string_free(zip_string_t *s) { + if (s == NULL) + return; + + free(s->raw); + free(s->converted); + free(s); +} + + +const zip_uint8_t * +_zip_string_get(zip_string_t *string, zip_uint32_t *lenp, zip_flags_t flags, zip_error_t *error) { + static const zip_uint8_t empty[1] = ""; + + if (string == NULL) { + if (lenp) + *lenp = 0; + return empty; + } + + if ((flags & ZIP_FL_ENC_RAW) == 0) { + /* start guessing */ + if (string->encoding == ZIP_ENCODING_UNKNOWN) + _zip_guess_encoding(string, ZIP_ENCODING_UNKNOWN); + + if (((flags & ZIP_FL_ENC_STRICT) && string->encoding != ZIP_ENCODING_ASCII && string->encoding != ZIP_ENCODING_UTF8_KNOWN) || (string->encoding == ZIP_ENCODING_CP437)) { + if (string->converted == NULL) { + if ((string->converted = _zip_cp437_to_utf8(string->raw, string->length, &string->converted_length, error)) == NULL) + return NULL; + } + if (lenp) + *lenp = string->converted_length; + return string->converted; + } + } + + if (lenp) + *lenp = string->length; + return string->raw; +} + + +zip_uint16_t +_zip_string_length(const zip_string_t *s) { + if (s == NULL) + return 0; + + return s->length; +} + + +zip_string_t * +_zip_string_new(const zip_uint8_t *raw, zip_uint16_t length, zip_flags_t flags, zip_error_t *error) { + zip_string_t *s; + zip_encoding_type_t expected_encoding; + + if (length == 0) + return NULL; + + switch (flags & ZIP_FL_ENCODING_ALL) { + case ZIP_FL_ENC_GUESS: + expected_encoding = ZIP_ENCODING_UNKNOWN; + break; + case ZIP_FL_ENC_UTF_8: + expected_encoding = ZIP_ENCODING_UTF8_KNOWN; + break; + case ZIP_FL_ENC_CP437: + expected_encoding = ZIP_ENCODING_CP437; + break; + default: + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + if ((s = (zip_string_t *)malloc(sizeof(*s))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + if ((s->raw = (zip_uint8_t *)malloc((size_t)length + 1)) == NULL) { + free(s); + return NULL; + } + + memcpy(s->raw, raw, length); + s->raw[length] = '\0'; + s->length = length; + s->encoding = ZIP_ENCODING_UNKNOWN; + s->converted = NULL; + s->converted_length = 0; + + if (expected_encoding != ZIP_ENCODING_UNKNOWN) { + if (_zip_guess_encoding(s, expected_encoding) == ZIP_ENCODING_ERROR) { + _zip_string_free(s); + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + } + + return s; +} + + +int +_zip_string_write(zip_t *za, const zip_string_t *s) { + if (s == NULL) + return 0; + + return _zip_write(za, s->raw, s->length); +} diff --git a/Source/Libraries/libzip/zip_unchange.c b/Source/Libraries/libzip/zip_unchange.c new file mode 100644 index 0000000..17e2500 --- /dev/null +++ b/Source/Libraries/libzip/zip_unchange.c @@ -0,0 +1,93 @@ +/* + zip_unchange.c -- undo changes to file in zip archive + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_unchange(zip_t *za, zip_uint64_t idx) { + return _zip_unchange(za, idx, 0); +} + + +int +_zip_unchange(zip_t *za, zip_uint64_t idx, int allow_duplicates) { + zip_int64_t i; + const char *orig_name, *changed_name; + + if (idx >= za->nentry) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (!allow_duplicates && za->entry[idx].changes && (za->entry[idx].changes->changed & ZIP_DIRENT_FILENAME)) { + if (za->entry[idx].orig != NULL) { + if ((orig_name = _zip_get_name(za, idx, ZIP_FL_UNCHANGED, &za->error)) == NULL) { + return -1; + } + + i = _zip_name_locate(za, orig_name, 0, NULL); + if (i >= 0 && (zip_uint64_t)i != idx) { + zip_error_set(&za->error, ZIP_ER_EXISTS, 0); + return -1; + } + } + else { + orig_name = NULL; + } + + if ((changed_name = _zip_get_name(za, idx, 0, &za->error)) == NULL) { + return -1; + } + + if (orig_name) { + if (_zip_hash_add(za->names, (const zip_uint8_t *)orig_name, idx, 0, &za->error) == false) { + return -1; + } + } + if (_zip_hash_delete(za->names, (const zip_uint8_t *)changed_name, &za->error) == false) { + _zip_hash_delete(za->names, (const zip_uint8_t *)orig_name, NULL); + return -1; + } + } + + _zip_dirent_free(za->entry[idx].changes); + za->entry[idx].changes = NULL; + + _zip_unchange_data(za->entry + idx); + + return 0; +} diff --git a/Source/Libraries/libzip/zip_unchange_all.c b/Source/Libraries/libzip/zip_unchange_all.c new file mode 100644 index 0000000..b8bfd70 --- /dev/null +++ b/Source/Libraries/libzip/zip_unchange_all.c @@ -0,0 +1,54 @@ +/* + zip_unchange.c -- undo changes to all files in zip archive + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_unchange_all(zip_t *za) { + int ret; + zip_uint64_t i; + + if (!_zip_hash_revert(za->names, &za->error)) { + return -1; + } + + ret = 0; + for (i = 0; i < za->nentry; i++) + ret |= _zip_unchange(za, i, 1); + + ret |= zip_unchange_archive(za); + + return ret; +} diff --git a/Source/Libraries/libzip/zip_unchange_archive.c b/Source/Libraries/libzip/zip_unchange_archive.c new file mode 100644 index 0000000..ebf2bd5 --- /dev/null +++ b/Source/Libraries/libzip/zip_unchange_archive.c @@ -0,0 +1,51 @@ +/* + zip_unchange_archive.c -- undo global changes to ZIP archive + Copyright (C) 2006-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_unchange_archive(zip_t *za) { + if (za->comment_changed) { + _zip_string_free(za->comment_changes); + za->comment_changes = NULL; + za->comment_changed = 0; + } + + za->ch_flags = za->flags; + + return 0; +} diff --git a/Source/Libraries/libzip/zip_unchange_data.c b/Source/Libraries/libzip/zip_unchange_data.c new file mode 100644 index 0000000..2a393ad --- /dev/null +++ b/Source/Libraries/libzip/zip_unchange_data.c @@ -0,0 +1,53 @@ +/* + zip_unchange_data.c -- undo helper function + Copyright (C) 1999-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +void +_zip_unchange_data(zip_entry_t *ze) { + if (ze->source) { + zip_source_free(ze->source); + ze->source = NULL; + } + + if (ze->changes != NULL && (ze->changes->changed & ZIP_DIRENT_COMP_METHOD) && ze->changes->comp_method == ZIP_CM_REPLACED_DEFAULT) { + ze->changes->changed &= ~ZIP_DIRENT_COMP_METHOD; + if (ze->changes->changed == 0) { + _zip_dirent_free(ze->changes); + ze->changes = NULL; + } + } + + ze->deleted = 0; +} diff --git a/Source/Libraries/libzip/zip_utf-8.c b/Source/Libraries/libzip/zip_utf-8.c new file mode 100644 index 0000000..51a4722 --- /dev/null +++ b/Source/Libraries/libzip/zip_utf-8.c @@ -0,0 +1,226 @@ +/* + zip_utf-8.c -- UTF-8 support functions for libzip + Copyright (C) 2011-2020 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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 names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +#include + + +static const zip_uint16_t _cp437_to_unicode[256] = { + /* 0x00 - 0x0F */ + 0x0000, 0x263A, 0x263B, 0x2665, 0x2666, 0x2663, 0x2660, 0x2022, 0x25D8, 0x25CB, 0x25D9, 0x2642, 0x2640, 0x266A, 0x266B, 0x263C, + + /* 0x10 - 0x1F */ + 0x25BA, 0x25C4, 0x2195, 0x203C, 0x00B6, 0x00A7, 0x25AC, 0x21A8, 0x2191, 0x2193, 0x2192, 0x2190, 0x221F, 0x2194, 0x25B2, 0x25BC, + + /* 0x20 - 0x2F */ + 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002A, 0x002B, 0x002C, 0x002D, 0x002E, 0x002F, + + /* 0x30 - 0x3F */ + 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E, 0x003F, + + /* 0x40 - 0x4F */ + 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004D, 0x004E, 0x004F, + + /* 0x50 - 0x5F */ + 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005A, 0x005B, 0x005C, 0x005D, 0x005E, 0x005F, + + /* 0x60 - 0x6F */ + 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006A, 0x006B, 0x006C, 0x006D, 0x006E, 0x006F, + + /* 0x70 - 0x7F */ + 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007A, 0x007B, 0x007C, 0x007D, 0x007E, 0x2302, + + /* 0x80 - 0x8F */ + 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5, + + /* 0x90 - 0x9F */ + 0x00C9, 0x00E6, 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x00FF, 0x00D6, 0x00DC, 0x00A2, 0x00A3, 0x00A5, 0x20A7, 0x0192, + + /* 0xA0 - 0xAF */ + 0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00F1, 0x00D1, 0x00AA, 0x00BA, 0x00BF, 0x2310, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, + + /* 0xB0 - 0xBF */ + 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, + + /* 0xC0 - 0xCF */ + 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, + + /* 0xD0 - 0xDF */ + 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, + + /* 0xE0 - 0xEF */ + 0x03B1, 0x00DF, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4, 0x03A6, 0x0398, 0x03A9, 0x03B4, 0x221E, 0x03C6, 0x03B5, 0x2229, + + /* 0xF0 - 0xFF */ + 0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, 0x25A0, 0x00A0}; + +#define UTF_8_LEN_2_MASK 0xe0 +#define UTF_8_LEN_2_MATCH 0xc0 +#define UTF_8_LEN_3_MASK 0xf0 +#define UTF_8_LEN_3_MATCH 0xe0 +#define UTF_8_LEN_4_MASK 0xf8 +#define UTF_8_LEN_4_MATCH 0xf0 +#define UTF_8_CONTINUE_MASK 0xc0 +#define UTF_8_CONTINUE_MATCH 0x80 + + +zip_encoding_type_t +_zip_guess_encoding(zip_string_t *str, zip_encoding_type_t expected_encoding) { + zip_encoding_type_t enc; + const zip_uint8_t *name; + zip_uint32_t i, j, ulen; + + if (str == NULL) + return ZIP_ENCODING_ASCII; + + name = str->raw; + + if (str->encoding != ZIP_ENCODING_UNKNOWN) + enc = str->encoding; + else { + enc = ZIP_ENCODING_ASCII; + for (i = 0; i < str->length; i++) { + if ((name[i] > 31 && name[i] < 128) || name[i] == '\r' || name[i] == '\n' || name[i] == '\t') + continue; + + enc = ZIP_ENCODING_UTF8_GUESSED; + if ((name[i] & UTF_8_LEN_2_MASK) == UTF_8_LEN_2_MATCH) + ulen = 1; + else if ((name[i] & UTF_8_LEN_3_MASK) == UTF_8_LEN_3_MATCH) + ulen = 2; + else if ((name[i] & UTF_8_LEN_4_MASK) == UTF_8_LEN_4_MATCH) + ulen = 3; + else { + enc = ZIP_ENCODING_CP437; + break; + } + + if (i + ulen >= str->length) { + enc = ZIP_ENCODING_CP437; + break; + } + + for (j = 1; j <= ulen; j++) { + if ((name[i + j] & UTF_8_CONTINUE_MASK) != UTF_8_CONTINUE_MATCH) { + enc = ZIP_ENCODING_CP437; + goto done; + } + } + i += ulen; + } + } + +done: + str->encoding = enc; + + if (expected_encoding != ZIP_ENCODING_UNKNOWN) { + if (expected_encoding == ZIP_ENCODING_UTF8_KNOWN && enc == ZIP_ENCODING_UTF8_GUESSED) + str->encoding = enc = ZIP_ENCODING_UTF8_KNOWN; + + if (expected_encoding != enc && enc != ZIP_ENCODING_ASCII) + return ZIP_ENCODING_ERROR; + } + + return enc; +} + + +static zip_uint32_t +_zip_unicode_to_utf8_len(zip_uint32_t codepoint) { + if (codepoint < 0x0080) + return 1; + if (codepoint < 0x0800) + return 2; + if (codepoint < 0x10000) + return 3; + return 4; +} + + +static zip_uint32_t +_zip_unicode_to_utf8(zip_uint32_t codepoint, zip_uint8_t *buf) { + if (codepoint < 0x0080) { + buf[0] = codepoint & 0xff; + return 1; + } + if (codepoint < 0x0800) { + buf[0] = (zip_uint8_t)(UTF_8_LEN_2_MATCH | ((codepoint >> 6) & 0x1f)); + buf[1] = (zip_uint8_t)(UTF_8_CONTINUE_MATCH | (codepoint & 0x3f)); + return 2; + } + if (codepoint < 0x10000) { + buf[0] = (zip_uint8_t)(UTF_8_LEN_3_MATCH | ((codepoint >> 12) & 0x0f)); + buf[1] = (zip_uint8_t)(UTF_8_CONTINUE_MATCH | ((codepoint >> 6) & 0x3f)); + buf[2] = (zip_uint8_t)(UTF_8_CONTINUE_MATCH | (codepoint & 0x3f)); + return 3; + } + buf[0] = (zip_uint8_t)(UTF_8_LEN_4_MATCH | ((codepoint >> 18) & 0x07)); + buf[1] = (zip_uint8_t)(UTF_8_CONTINUE_MATCH | ((codepoint >> 12) & 0x3f)); + buf[2] = (zip_uint8_t)(UTF_8_CONTINUE_MATCH | ((codepoint >> 6) & 0x3f)); + buf[3] = (zip_uint8_t)(UTF_8_CONTINUE_MATCH | (codepoint & 0x3f)); + return 4; +} + + +zip_uint8_t * +_zip_cp437_to_utf8(const zip_uint8_t *const _cp437buf, zip_uint32_t len, zip_uint32_t *utf8_lenp, zip_error_t *error) { + zip_uint8_t *cp437buf = (zip_uint8_t *)_cp437buf; + zip_uint8_t *utf8buf; + zip_uint32_t buflen, i, offset; + + if (len == 0) { + if (utf8_lenp) + *utf8_lenp = 0; + return NULL; + } + + buflen = 1; + for (i = 0; i < len; i++) + buflen += _zip_unicode_to_utf8_len(_cp437_to_unicode[cp437buf[i]]); + + if ((utf8buf = (zip_uint8_t *)malloc(buflen)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + offset = 0; + for (i = 0; i < len; i++) + offset += _zip_unicode_to_utf8(_cp437_to_unicode[cp437buf[i]], utf8buf + offset); + + utf8buf[buflen - 1] = 0; + if (utf8_lenp) + *utf8_lenp = buflen - 1; + return utf8buf; +} diff --git a/Source/Libraries/zlib/FAQ b/Source/Libraries/zlib/FAQ new file mode 100644 index 0000000..99b7cf9 --- /dev/null +++ b/Source/Libraries/zlib/FAQ @@ -0,0 +1,368 @@ + + Frequently Asked Questions about zlib + + +If your question is not there, please check the zlib home page +http://zlib.net/ which may have more recent information. +The lastest zlib FAQ is at http://zlib.net/zlib_faq.html + + + 1. Is zlib Y2K-compliant? + + Yes. zlib doesn't handle dates. + + 2. Where can I get a Windows DLL version? + + The zlib sources can be compiled without change to produce a DLL. See the + file win32/DLL_FAQ.txt in the zlib distribution. Pointers to the + precompiled DLL are found in the zlib web site at http://zlib.net/ . + + 3. Where can I get a Visual Basic interface to zlib? + + See + * http://marknelson.us/1997/01/01/zlib-engine/ + * win32/DLL_FAQ.txt in the zlib distribution + + 4. compress() returns Z_BUF_ERROR. + + Make sure that before the call of compress(), the length of the compressed + buffer is equal to the available size of the compressed buffer and not + zero. For Visual Basic, check that this parameter is passed by reference + ("as any"), not by value ("as long"). + + 5. deflate() or inflate() returns Z_BUF_ERROR. + + Before making the call, make sure that avail_in and avail_out are not zero. + When setting the parameter flush equal to Z_FINISH, also make sure that + avail_out is big enough to allow processing all pending input. Note that a + Z_BUF_ERROR is not fatal--another call to deflate() or inflate() can be + made with more input or output space. A Z_BUF_ERROR may in fact be + unavoidable depending on how the functions are used, since it is not + possible to tell whether or not there is more output pending when + strm.avail_out returns with zero. See http://zlib.net/zlib_how.html for a + heavily annotated example. + + 6. Where's the zlib documentation (man pages, etc.)? + + It's in zlib.h . Examples of zlib usage are in the files test/example.c + and test/minigzip.c, with more in examples/ . + + 7. Why don't you use GNU autoconf or libtool or ...? + + Because we would like to keep zlib as a very small and simple package. + zlib is rather portable and doesn't need much configuration. + + 8. I found a bug in zlib. + + Most of the time, such problems are due to an incorrect usage of zlib. + Please try to reproduce the problem with a small program and send the + corresponding source to us at zlib@gzip.org . Do not send multi-megabyte + data files without prior agreement. + + 9. Why do I get "undefined reference to gzputc"? + + If "make test" produces something like + + example.o(.text+0x154): undefined reference to `gzputc' + + check that you don't have old files libz.* in /usr/lib, /usr/local/lib or + /usr/X11R6/lib. Remove any old versions, then do "make install". + +10. I need a Delphi interface to zlib. + + See the contrib/delphi directory in the zlib distribution. + +11. Can zlib handle .zip archives? + + Not by itself, no. See the directory contrib/minizip in the zlib + distribution. + +12. Can zlib handle .Z files? + + No, sorry. You have to spawn an uncompress or gunzip subprocess, or adapt + the code of uncompress on your own. + +13. How can I make a Unix shared library? + + By default a shared (and a static) library is built for Unix. So: + + make distclean + ./configure + make + +14. How do I install a shared zlib library on Unix? + + After the above, then: + + make install + + However, many flavors of Unix come with a shared zlib already installed. + Before going to the trouble of compiling a shared version of zlib and + trying to install it, you may want to check if it's already there! If you + can #include , it's there. The -lz option will probably link to + it. You can check the version at the top of zlib.h or with the + ZLIB_VERSION symbol defined in zlib.h . + +15. I have a question about OttoPDF. + + We are not the authors of OttoPDF. The real author is on the OttoPDF web + site: Joel Hainley, jhainley@myndkryme.com. + +16. Can zlib decode Flate data in an Adobe PDF file? + + Yes. See http://www.pdflib.com/ . To modify PDF forms, see + http://sourceforge.net/projects/acroformtool/ . + +17. Why am I getting this "register_frame_info not found" error on Solaris? + + After installing zlib 1.1.4 on Solaris 2.6, running applications using zlib + generates an error such as: + + ld.so.1: rpm: fatal: relocation error: file /usr/local/lib/libz.so: + symbol __register_frame_info: referenced symbol not found + + The symbol __register_frame_info is not part of zlib, it is generated by + the C compiler (cc or gcc). You must recompile applications using zlib + which have this problem. This problem is specific to Solaris. See + http://www.sunfreeware.com for Solaris versions of zlib and applications + using zlib. + +18. Why does gzip give an error on a file I make with compress/deflate? + + The compress and deflate functions produce data in the zlib format, which + is different and incompatible with the gzip format. The gz* functions in + zlib on the other hand use the gzip format. Both the zlib and gzip formats + use the same compressed data format internally, but have different headers + and trailers around the compressed data. + +19. Ok, so why are there two different formats? + + The gzip format was designed to retain the directory information about a + single file, such as the name and last modification date. The zlib format + on the other hand was designed for in-memory and communication channel + applications, and has a much more compact header and trailer and uses a + faster integrity check than gzip. + +20. Well that's nice, but how do I make a gzip file in memory? + + You can request that deflate write the gzip format instead of the zlib + format using deflateInit2(). You can also request that inflate decode the + gzip format using inflateInit2(). Read zlib.h for more details. + +21. Is zlib thread-safe? + + Yes. However any library routines that zlib uses and any application- + provided memory allocation routines must also be thread-safe. zlib's gz* + functions use stdio library routines, and most of zlib's functions use the + library memory allocation routines by default. zlib's *Init* functions + allow for the application to provide custom memory allocation routines. + + Of course, you should only operate on any given zlib or gzip stream from a + single thread at a time. + +22. Can I use zlib in my commercial application? + + Yes. Please read the license in zlib.h. + +23. Is zlib under the GNU license? + + No. Please read the license in zlib.h. + +24. The license says that altered source versions must be "plainly marked". So + what exactly do I need to do to meet that requirement? + + You need to change the ZLIB_VERSION and ZLIB_VERNUM #defines in zlib.h. In + particular, the final version number needs to be changed to "f", and an + identification string should be appended to ZLIB_VERSION. Version numbers + x.x.x.f are reserved for modifications to zlib by others than the zlib + maintainers. For example, if the version of the base zlib you are altering + is "1.2.3.4", then in zlib.h you should change ZLIB_VERNUM to 0x123f, and + ZLIB_VERSION to something like "1.2.3.f-zachary-mods-v3". You can also + update the version strings in deflate.c and inftrees.c. + + For altered source distributions, you should also note the origin and + nature of the changes in zlib.h, as well as in ChangeLog and README, along + with the dates of the alterations. The origin should include at least your + name (or your company's name), and an email address to contact for help or + issues with the library. + + Note that distributing a compiled zlib library along with zlib.h and + zconf.h is also a source distribution, and so you should change + ZLIB_VERSION and ZLIB_VERNUM and note the origin and nature of the changes + in zlib.h as you would for a full source distribution. + +25. Will zlib work on a big-endian or little-endian architecture, and can I + exchange compressed data between them? + + Yes and yes. + +26. Will zlib work on a 64-bit machine? + + Yes. It has been tested on 64-bit machines, and has no dependence on any + data types being limited to 32-bits in length. If you have any + difficulties, please provide a complete problem report to zlib@gzip.org + +27. Will zlib decompress data from the PKWare Data Compression Library? + + No. The PKWare DCL uses a completely different compressed data format than + does PKZIP and zlib. However, you can look in zlib's contrib/blast + directory for a possible solution to your problem. + +28. Can I access data randomly in a compressed stream? + + No, not without some preparation. If when compressing you periodically use + Z_FULL_FLUSH, carefully write all the pending data at those points, and + keep an index of those locations, then you can start decompression at those + points. You have to be careful to not use Z_FULL_FLUSH too often, since it + can significantly degrade compression. Alternatively, you can scan a + deflate stream once to generate an index, and then use that index for + random access. See examples/zran.c . + +29. Does zlib work on MVS, OS/390, CICS, etc.? + + It has in the past, but we have not heard of any recent evidence. There + were working ports of zlib 1.1.4 to MVS, but those links no longer work. + If you know of recent, successful applications of zlib on these operating + systems, please let us know. Thanks. + +30. Is there some simpler, easier to read version of inflate I can look at to + understand the deflate format? + + First off, you should read RFC 1951. Second, yes. Look in zlib's + contrib/puff directory. + +31. Does zlib infringe on any patents? + + As far as we know, no. In fact, that was originally the whole point behind + zlib. Look here for some more information: + + http://www.gzip.org/#faq11 + +32. Can zlib work with greater than 4 GB of data? + + Yes. inflate() and deflate() will process any amount of data correctly. + Each call of inflate() or deflate() is limited to input and output chunks + of the maximum value that can be stored in the compiler's "unsigned int" + type, but there is no limit to the number of chunks. Note however that the + strm.total_in and strm_total_out counters may be limited to 4 GB. These + counters are provided as a convenience and are not used internally by + inflate() or deflate(). The application can easily set up its own counters + updated after each call of inflate() or deflate() to count beyond 4 GB. + compress() and uncompress() may be limited to 4 GB, since they operate in a + single call. gzseek() and gztell() may be limited to 4 GB depending on how + zlib is compiled. See the zlibCompileFlags() function in zlib.h. + + The word "may" appears several times above since there is a 4 GB limit only + if the compiler's "long" type is 32 bits. If the compiler's "long" type is + 64 bits, then the limit is 16 exabytes. + +33. Does zlib have any security vulnerabilities? + + The only one that we are aware of is potentially in gzprintf(). If zlib is + compiled to use sprintf() or vsprintf(), then there is no protection + against a buffer overflow of an 8K string space (or other value as set by + gzbuffer()), other than the caller of gzprintf() assuring that the output + will not exceed 8K. On the other hand, if zlib is compiled to use + snprintf() or vsnprintf(), which should normally be the case, then there is + no vulnerability. The ./configure script will display warnings if an + insecure variation of sprintf() will be used by gzprintf(). Also the + zlibCompileFlags() function will return information on what variant of + sprintf() is used by gzprintf(). + + If you don't have snprintf() or vsnprintf() and would like one, you can + find a portable implementation here: + + http://www.ijs.si/software/snprintf/ + + Note that you should be using the most recent version of zlib. Versions + 1.1.3 and before were subject to a double-free vulnerability, and versions + 1.2.1 and 1.2.2 were subject to an access exception when decompressing + invalid compressed data. + +34. Is there a Java version of zlib? + + Probably what you want is to use zlib in Java. zlib is already included + as part of the Java SDK in the java.util.zip package. If you really want + a version of zlib written in the Java language, look on the zlib home + page for links: http://zlib.net/ . + +35. I get this or that compiler or source-code scanner warning when I crank it + up to maximally-pedantic. Can't you guys write proper code? + + Many years ago, we gave up attempting to avoid warnings on every compiler + in the universe. It just got to be a waste of time, and some compilers + were downright silly as well as contradicted each other. So now, we simply + make sure that the code always works. + +36. Valgrind (or some similar memory access checker) says that deflate is + performing a conditional jump that depends on an uninitialized value. + Isn't that a bug? + + No. That is intentional for performance reasons, and the output of deflate + is not affected. This only started showing up recently since zlib 1.2.x + uses malloc() by default for allocations, whereas earlier versions used + calloc(), which zeros out the allocated memory. Even though the code was + correct, versions 1.2.4 and later was changed to not stimulate these + checkers. + +37. Will zlib read the (insert any ancient or arcane format here) compressed + data format? + + Probably not. Look in the comp.compression FAQ for pointers to various + formats and associated software. + +38. How can I encrypt/decrypt zip files with zlib? + + zlib doesn't support encryption. The original PKZIP encryption is very + weak and can be broken with freely available programs. To get strong + encryption, use GnuPG, http://www.gnupg.org/ , which already includes zlib + compression. For PKZIP compatible "encryption", look at + http://www.info-zip.org/ + +39. What's the difference between the "gzip" and "deflate" HTTP 1.1 encodings? + + "gzip" is the gzip format, and "deflate" is the zlib format. They should + probably have called the second one "zlib" instead to avoid confusion with + the raw deflate compressed data format. While the HTTP 1.1 RFC 2616 + correctly points to the zlib specification in RFC 1950 for the "deflate" + transfer encoding, there have been reports of servers and browsers that + incorrectly produce or expect raw deflate data per the deflate + specification in RFC 1951, most notably Microsoft. So even though the + "deflate" transfer encoding using the zlib format would be the more + efficient approach (and in fact exactly what the zlib format was designed + for), using the "gzip" transfer encoding is probably more reliable due to + an unfortunate choice of name on the part of the HTTP 1.1 authors. + + Bottom line: use the gzip format for HTTP 1.1 encoding. + +40. Does zlib support the new "Deflate64" format introduced by PKWare? + + No. PKWare has apparently decided to keep that format proprietary, since + they have not documented it as they have previous compression formats. In + any case, the compression improvements are so modest compared to other more + modern approaches, that it's not worth the effort to implement. + +41. I'm having a problem with the zip functions in zlib, can you help? + + There are no zip functions in zlib. You are probably using minizip by + Giles Vollant, which is found in the contrib directory of zlib. It is not + part of zlib. In fact none of the stuff in contrib is part of zlib. The + files in there are not supported by the zlib authors. You need to contact + the authors of the respective contribution for help. + +42. The match.asm code in contrib is under the GNU General Public License. + Since it's part of zlib, doesn't that mean that all of zlib falls under the + GNU GPL? + + No. The files in contrib are not part of zlib. They were contributed by + other authors and are provided as a convenience to the user within the zlib + distribution. Each item in contrib has its own license. + +43. Is zlib subject to export controls? What is its ECCN? + + zlib is not subject to export controls, and so is classified as EAR99. + +44. Can you please sign these lengthy legal documents and fax them back to us + so that we can use your software in our product? + + No. Go away. Shoo. diff --git a/Source/Libraries/zlib/README b/Source/Libraries/zlib/README new file mode 100644 index 0000000..51106de --- /dev/null +++ b/Source/Libraries/zlib/README @@ -0,0 +1,115 @@ +ZLIB DATA COMPRESSION LIBRARY + +zlib 1.2.11 is a general purpose data compression library. All the code is +thread safe. The data format used by the zlib library is described by RFCs +(Request for Comments) 1950 to 1952 in the files +http://tools.ietf.org/html/rfc1950 (zlib format), rfc1951 (deflate format) and +rfc1952 (gzip format). + +All functions of the compression library are documented in the file zlib.h +(volunteer to write man pages welcome, contact zlib@gzip.org). A usage example +of the library is given in the file test/example.c which also tests that +the library is working correctly. Another example is given in the file +test/minigzip.c. The compression library itself is composed of all source +files in the root directory. + +To compile all files and run the test program, follow the instructions given at +the top of Makefile.in. In short "./configure; make test", and if that goes +well, "make install" should work for most flavors of Unix. For Windows, use +one of the special makefiles in win32/ or contrib/vstudio/ . For VMS, use +make_vms.com. + +Questions about zlib should be sent to , or to Gilles Vollant + for the Windows DLL version. The zlib home page is +http://zlib.net/ . Before reporting a problem, please check this site to +verify that you have the latest version of zlib; otherwise get the latest +version and check whether the problem still exists or not. + +PLEASE read the zlib FAQ http://zlib.net/zlib_faq.html before asking for help. + +Mark Nelson wrote an article about zlib for the Jan. 1997 +issue of Dr. Dobb's Journal; a copy of the article is available at +http://marknelson.us/1997/01/01/zlib-engine/ . + +The changes made in version 1.2.11 are documented in the file ChangeLog. + +Unsupported third party contributions are provided in directory contrib/ . + +zlib is available in Java using the java.util.zip package, documented at +http://java.sun.com/developer/technicalArticles/Programming/compression/ . + +A Perl interface to zlib written by Paul Marquess is available +at CPAN (Comprehensive Perl Archive Network) sites, including +http://search.cpan.org/~pmqs/IO-Compress-Zlib/ . + +A Python interface to zlib written by A.M. Kuchling is +available in Python 1.5 and later versions, see +http://docs.python.org/library/zlib.html . + +zlib is built into tcl: http://wiki.tcl.tk/4610 . + +An experimental package to read and write files in .zip format, written on top +of zlib by Gilles Vollant , is available in the +contrib/minizip directory of zlib. + + +Notes for some targets: + +- For Windows DLL versions, please see win32/DLL_FAQ.txt + +- For 64-bit Irix, deflate.c must be compiled without any optimization. With + -O, one libpng test fails. The test works in 32 bit mode (with the -n32 + compiler flag). The compiler bug has been reported to SGI. + +- zlib doesn't work with gcc 2.6.3 on a DEC 3000/300LX under OSF/1 2.1 it works + when compiled with cc. + +- On Digital Unix 4.0D (formely OSF/1) on AlphaServer, the cc option -std1 is + necessary to get gzprintf working correctly. This is done by configure. + +- zlib doesn't work on HP-UX 9.05 with some versions of /bin/cc. It works with + other compilers. Use "make test" to check your compiler. + +- gzdopen is not supported on RISCOS or BEOS. + +- For PalmOs, see http://palmzlib.sourceforge.net/ + + +Acknowledgments: + + The deflate format used by zlib was defined by Phil Katz. The deflate and + zlib specifications were written by L. Peter Deutsch. Thanks to all the + people who reported problems and suggested various improvements in zlib; they + are too numerous to cite here. + +Copyright notice: + + (C) 1995-2017 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + +If you use the zlib library in a product, we would appreciate *not* receiving +lengthy legal documents to sign. The sources are provided for free but without +warranty of any kind. The library has been entirely written by Jean-loup +Gailly and Mark Adler; it does not include third-party code. + +If you redistribute modified sources, we would appreciate that you include in +the file ChangeLog history information documenting your changes. Please read +the FAQ for more information on the distribution of modified source versions. diff --git a/Source/Libraries/zlib/adler32.c b/Source/Libraries/zlib/adler32.c new file mode 100644 index 0000000..d0be438 --- /dev/null +++ b/Source/Libraries/zlib/adler32.c @@ -0,0 +1,186 @@ +/* adler32.c -- compute the Adler-32 checksum of a data stream + * Copyright (C) 1995-2011, 2016 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#include "zutil.h" + +local uLong adler32_combine_ OF((uLong adler1, uLong adler2, z_off64_t len2)); + +#define BASE 65521U /* largest prime smaller than 65536 */ +#define NMAX 5552 +/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ + +#define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;} +#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); +#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); +#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); +#define DO16(buf) DO8(buf,0); DO8(buf,8); + +/* use NO_DIVIDE if your processor does not do division in hardware -- + try it both ways to see which is faster */ +#ifdef NO_DIVIDE +/* note that this assumes BASE is 65521, where 65536 % 65521 == 15 + (thank you to John Reiser for pointing this out) */ +# define CHOP(a) \ + do { \ + unsigned long tmp = a >> 16; \ + a &= 0xffffUL; \ + a += (tmp << 4) - tmp; \ + } while (0) +# define MOD28(a) \ + do { \ + CHOP(a); \ + if (a >= BASE) a -= BASE; \ + } while (0) +# define MOD(a) \ + do { \ + CHOP(a); \ + MOD28(a); \ + } while (0) +# define MOD63(a) \ + do { /* this assumes a is not negative */ \ + z_off64_t tmp = a >> 32; \ + a &= 0xffffffffL; \ + a += (tmp << 8) - (tmp << 5) + tmp; \ + tmp = a >> 16; \ + a &= 0xffffL; \ + a += (tmp << 4) - tmp; \ + tmp = a >> 16; \ + a &= 0xffffL; \ + a += (tmp << 4) - tmp; \ + if (a >= BASE) a -= BASE; \ + } while (0) +#else +# define MOD(a) a %= BASE +# define MOD28(a) a %= BASE +# define MOD63(a) a %= BASE +#endif + +/* ========================================================================= */ +uLong ZEXPORT adler32_z(adler, buf, len) + uLong adler; + const Bytef *buf; + z_size_t len; +{ + unsigned long sum2; + unsigned n; + + /* split Adler-32 into component sums */ + sum2 = (adler >> 16) & 0xffff; + adler &= 0xffff; + + /* in case user likes doing a byte at a time, keep it fast */ + if (len == 1) { + adler += buf[0]; + if (adler >= BASE) + adler -= BASE; + sum2 += adler; + if (sum2 >= BASE) + sum2 -= BASE; + return adler | (sum2 << 16); + } + + /* initial Adler-32 value (deferred check for len == 1 speed) */ + if (buf == Z_NULL) + return 1L; + + /* in case short lengths are provided, keep it somewhat fast */ + if (len < 16) { + while (len--) { + adler += *buf++; + sum2 += adler; + } + if (adler >= BASE) + adler -= BASE; + MOD28(sum2); /* only added so many BASE's */ + return adler | (sum2 << 16); + } + + /* do length NMAX blocks -- requires just one modulo operation */ + while (len >= NMAX) { + len -= NMAX; + n = NMAX / 16; /* NMAX is divisible by 16 */ + do { + DO16(buf); /* 16 sums unrolled */ + buf += 16; + } while (--n); + MOD(adler); + MOD(sum2); + } + + /* do remaining bytes (less than NMAX, still just one modulo) */ + if (len) { /* avoid modulos if none remaining */ + while (len >= 16) { + len -= 16; + DO16(buf); + buf += 16; + } + while (len--) { + adler += *buf++; + sum2 += adler; + } + MOD(adler); + MOD(sum2); + } + + /* return recombined sums */ + return adler | (sum2 << 16); +} + +/* ========================================================================= */ +uLong ZEXPORT adler32(adler, buf, len) + uLong adler; + const Bytef *buf; + uInt len; +{ + return adler32_z(adler, buf, len); +} + +/* ========================================================================= */ +local uLong adler32_combine_(adler1, adler2, len2) + uLong adler1; + uLong adler2; + z_off64_t len2; +{ + unsigned long sum1; + unsigned long sum2; + unsigned rem; + + /* for negative len, return invalid adler32 as a clue for debugging */ + if (len2 < 0) + return 0xffffffffUL; + + /* the derivation of this formula is left as an exercise for the reader */ + MOD63(len2); /* assumes len2 >= 0 */ + rem = (unsigned)len2; + sum1 = adler1 & 0xffff; + sum2 = rem * sum1; + MOD(sum2); + sum1 += (adler2 & 0xffff) + BASE - 1; + sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem; + if (sum1 >= BASE) sum1 -= BASE; + if (sum1 >= BASE) sum1 -= BASE; + if (sum2 >= ((unsigned long)BASE << 1)) sum2 -= ((unsigned long)BASE << 1); + if (sum2 >= BASE) sum2 -= BASE; + return sum1 | (sum2 << 16); +} + +/* ========================================================================= */ +uLong ZEXPORT adler32_combine(adler1, adler2, len2) + uLong adler1; + uLong adler2; + z_off_t len2; +{ + return adler32_combine_(adler1, adler2, len2); +} + +uLong ZEXPORT adler32_combine64(adler1, adler2, len2) + uLong adler1; + uLong adler2; + z_off64_t len2; +{ + return adler32_combine_(adler1, adler2, len2); +} diff --git a/Source/Libraries/zlib/compress.c b/Source/Libraries/zlib/compress.c new file mode 100644 index 0000000..e2db404 --- /dev/null +++ b/Source/Libraries/zlib/compress.c @@ -0,0 +1,86 @@ +/* compress.c -- compress a memory buffer + * Copyright (C) 1995-2005, 2014, 2016 Jean-loup Gailly, Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#define ZLIB_INTERNAL +#include "zlib.h" + +/* =========================================================================== + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least 0.1% larger than sourceLen plus + 12 bytes. Upon exit, destLen is the actual size of the compressed buffer. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ +int ZEXPORT compress2 (dest, destLen, source, sourceLen, level) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; + int level; +{ + z_stream stream; + int err; + const uInt max = (uInt)-1; + uLong left; + + left = *destLen; + *destLen = 0; + + stream.zalloc = (alloc_func)0; + stream.zfree = (free_func)0; + stream.opaque = (voidpf)0; + + err = deflateInit(&stream, level); + if (err != Z_OK) return err; + + stream.next_out = dest; + stream.avail_out = 0; + stream.next_in = (z_const Bytef *)source; + stream.avail_in = 0; + + do { + if (stream.avail_out == 0) { + stream.avail_out = left > (uLong)max ? max : (uInt)left; + left -= stream.avail_out; + } + if (stream.avail_in == 0) { + stream.avail_in = sourceLen > (uLong)max ? max : (uInt)sourceLen; + sourceLen -= stream.avail_in; + } + err = deflate(&stream, sourceLen ? Z_NO_FLUSH : Z_FINISH); + } while (err == Z_OK); + + *destLen = stream.total_out; + deflateEnd(&stream); + return err == Z_STREAM_END ? Z_OK : err; +} + +/* =========================================================================== + */ +int ZEXPORT compress (dest, destLen, source, sourceLen) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; +{ + return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION); +} + +/* =========================================================================== + If the default memLevel or windowBits for deflateInit() is changed, then + this function needs to be updated. + */ +uLong ZEXPORT compressBound (sourceLen) + uLong sourceLen; +{ + return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + + (sourceLen >> 25) + 13; +} diff --git a/Source/Libraries/zlib/crc32.c b/Source/Libraries/zlib/crc32.c new file mode 100644 index 0000000..9580440 --- /dev/null +++ b/Source/Libraries/zlib/crc32.c @@ -0,0 +1,442 @@ +/* crc32.c -- compute the CRC-32 of a data stream + * Copyright (C) 1995-2006, 2010, 2011, 2012, 2016 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + * + * Thanks to Rodney Brown for his contribution of faster + * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing + * tables for updating the shift register in one step with three exclusive-ors + * instead of four steps with four exclusive-ors. This results in about a + * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3. + */ + +/* @(#) $Id$ */ + +/* + Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore + protection on the static variables used to control the first-use generation + of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should + first call get_crc_table() to initialize the tables before allowing more than + one thread to use crc32(). + + DYNAMIC_CRC_TABLE and MAKECRCH can be #defined to write out crc32.h. + */ + +#ifdef MAKECRCH +# include +# ifndef DYNAMIC_CRC_TABLE +# define DYNAMIC_CRC_TABLE +# endif /* !DYNAMIC_CRC_TABLE */ +#endif /* MAKECRCH */ + +#include "zutil.h" /* for STDC and FAR definitions */ + +/* Definitions for doing the crc four data bytes at a time. */ +#if !defined(NOBYFOUR) && defined(Z_U4) +# define BYFOUR +#endif +#ifdef BYFOUR + local unsigned long crc32_little OF((unsigned long, + const unsigned char FAR *, z_size_t)); + local unsigned long crc32_big OF((unsigned long, + const unsigned char FAR *, z_size_t)); +# define TBLS 8 +#else +# define TBLS 1 +#endif /* BYFOUR */ + +/* Local functions for crc concatenation */ +local unsigned long gf2_matrix_times OF((unsigned long *mat, + unsigned long vec)); +local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat)); +local uLong crc32_combine_ OF((uLong crc1, uLong crc2, z_off64_t len2)); + + +#ifdef DYNAMIC_CRC_TABLE + +local volatile int crc_table_empty = 1; +local z_crc_t FAR crc_table[TBLS][256]; +local void make_crc_table OF((void)); +#ifdef MAKECRCH + local void write_table OF((FILE *, const z_crc_t FAR *)); +#endif /* MAKECRCH */ +/* + Generate tables for a byte-wise 32-bit CRC calculation on the polynomial: + x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. + + Polynomials over GF(2) are represented in binary, one bit per coefficient, + with the lowest powers in the most significant bit. Then adding polynomials + is just exclusive-or, and multiplying a polynomial by x is a right shift by + one. If we call the above polynomial p, and represent a byte as the + polynomial q, also with the lowest power in the most significant bit (so the + byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, + where a mod b means the remainder after dividing a by b. + + This calculation is done using the shift-register method of multiplying and + taking the remainder. The register is initialized to zero, and for each + incoming bit, x^32 is added mod p to the register if the bit is a one (where + x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by + x (which is shifting right by one and adding x^32 mod p if the bit shifted + out is a one). We start with the highest power (least significant bit) of + q and repeat for all eight bits of q. + + The first table is simply the CRC of all possible eight bit values. This is + all the information needed to generate CRCs on data a byte at a time for all + combinations of CRC register values and incoming bytes. The remaining tables + allow for word-at-a-time CRC calculation for both big-endian and little- + endian machines, where a word is four bytes. +*/ +local void make_crc_table() +{ + z_crc_t c; + int n, k; + z_crc_t poly; /* polynomial exclusive-or pattern */ + /* terms of polynomial defining this crc (except x^32): */ + static volatile int first = 1; /* flag to limit concurrent making */ + static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; + + /* See if another task is already doing this (not thread-safe, but better + than nothing -- significantly reduces duration of vulnerability in + case the advice about DYNAMIC_CRC_TABLE is ignored) */ + if (first) { + first = 0; + + /* make exclusive-or pattern from polynomial (0xedb88320UL) */ + poly = 0; + for (n = 0; n < (int)(sizeof(p)/sizeof(unsigned char)); n++) + poly |= (z_crc_t)1 << (31 - p[n]); + + /* generate a crc for every 8-bit value */ + for (n = 0; n < 256; n++) { + c = (z_crc_t)n; + for (k = 0; k < 8; k++) + c = c & 1 ? poly ^ (c >> 1) : c >> 1; + crc_table[0][n] = c; + } + +#ifdef BYFOUR + /* generate crc for each value followed by one, two, and three zeros, + and then the byte reversal of those as well as the first table */ + for (n = 0; n < 256; n++) { + c = crc_table[0][n]; + crc_table[4][n] = ZSWAP32(c); + for (k = 1; k < 4; k++) { + c = crc_table[0][c & 0xff] ^ (c >> 8); + crc_table[k][n] = c; + crc_table[k + 4][n] = ZSWAP32(c); + } + } +#endif /* BYFOUR */ + + crc_table_empty = 0; + } + else { /* not first */ + /* wait for the other guy to finish (not efficient, but rare) */ + while (crc_table_empty) + ; + } + +#ifdef MAKECRCH + /* write out CRC tables to crc32.h */ + { + FILE *out; + + out = fopen("crc32.h", "w"); + if (out == NULL) return; + fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n"); + fprintf(out, " * Generated automatically by crc32.c\n */\n\n"); + fprintf(out, "local const z_crc_t FAR "); + fprintf(out, "crc_table[TBLS][256] =\n{\n {\n"); + write_table(out, crc_table[0]); +# ifdef BYFOUR + fprintf(out, "#ifdef BYFOUR\n"); + for (k = 1; k < 8; k++) { + fprintf(out, " },\n {\n"); + write_table(out, crc_table[k]); + } + fprintf(out, "#endif\n"); +# endif /* BYFOUR */ + fprintf(out, " }\n};\n"); + fclose(out); + } +#endif /* MAKECRCH */ +} + +#ifdef MAKECRCH +local void write_table(out, table) + FILE *out; + const z_crc_t FAR *table; +{ + int n; + + for (n = 0; n < 256; n++) + fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", + (unsigned long)(table[n]), + n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", ")); +} +#endif /* MAKECRCH */ + +#else /* !DYNAMIC_CRC_TABLE */ +/* ======================================================================== + * Tables of CRC-32s of all single-byte values, made by make_crc_table(). + */ +#include "crc32.h" +#endif /* DYNAMIC_CRC_TABLE */ + +/* ========================================================================= + * This function can be used by asm versions of crc32() + */ +const z_crc_t FAR * ZEXPORT get_crc_table() +{ +#ifdef DYNAMIC_CRC_TABLE + if (crc_table_empty) + make_crc_table(); +#endif /* DYNAMIC_CRC_TABLE */ + return (const z_crc_t FAR *)crc_table; +} + +/* ========================================================================= */ +#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8) +#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1 + +/* ========================================================================= */ +unsigned long ZEXPORT crc32_z(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + z_size_t len; +{ + if (buf == Z_NULL) return 0UL; + +#ifdef DYNAMIC_CRC_TABLE + if (crc_table_empty) + make_crc_table(); +#endif /* DYNAMIC_CRC_TABLE */ + +#ifdef BYFOUR + if (sizeof(void *) == sizeof(ptrdiff_t)) { + z_crc_t endian; + + endian = 1; + if (*((unsigned char *)(&endian))) + return crc32_little(crc, buf, len); + else + return crc32_big(crc, buf, len); + } +#endif /* BYFOUR */ + crc = crc ^ 0xffffffffUL; + while (len >= 8) { + DO8; + len -= 8; + } + if (len) do { + DO1; + } while (--len); + return crc ^ 0xffffffffUL; +} + +/* ========================================================================= */ +unsigned long ZEXPORT crc32(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + uInt len; +{ + return crc32_z(crc, buf, len); +} + +#ifdef BYFOUR + +/* + This BYFOUR code accesses the passed unsigned char * buffer with a 32-bit + integer pointer type. This violates the strict aliasing rule, where a + compiler can assume, for optimization purposes, that two pointers to + fundamentally different types won't ever point to the same memory. This can + manifest as a problem only if one of the pointers is written to. This code + only reads from those pointers. So long as this code remains isolated in + this compilation unit, there won't be a problem. For this reason, this code + should not be copied and pasted into a compilation unit in which other code + writes to the buffer that is passed to these routines. + */ + +/* ========================================================================= */ +#define DOLIT4 c ^= *buf4++; \ + c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \ + crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24] +#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4 + +/* ========================================================================= */ +local unsigned long crc32_little(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + z_size_t len; +{ + register z_crc_t c; + register const z_crc_t FAR *buf4; + + c = (z_crc_t)crc; + c = ~c; + while (len && ((ptrdiff_t)buf & 3)) { + c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); + len--; + } + + buf4 = (const z_crc_t FAR *)(const void FAR *)buf; + while (len >= 32) { + DOLIT32; + len -= 32; + } + while (len >= 4) { + DOLIT4; + len -= 4; + } + buf = (const unsigned char FAR *)buf4; + + if (len) do { + c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); + } while (--len); + c = ~c; + return (unsigned long)c; +} + +/* ========================================================================= */ +#define DOBIG4 c ^= *buf4++; \ + c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \ + crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24] +#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4 + +/* ========================================================================= */ +local unsigned long crc32_big(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + z_size_t len; +{ + register z_crc_t c; + register const z_crc_t FAR *buf4; + + c = ZSWAP32((z_crc_t)crc); + c = ~c; + while (len && ((ptrdiff_t)buf & 3)) { + c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); + len--; + } + + buf4 = (const z_crc_t FAR *)(const void FAR *)buf; + while (len >= 32) { + DOBIG32; + len -= 32; + } + while (len >= 4) { + DOBIG4; + len -= 4; + } + buf = (const unsigned char FAR *)buf4; + + if (len) do { + c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); + } while (--len); + c = ~c; + return (unsigned long)(ZSWAP32(c)); +} + +#endif /* BYFOUR */ + +#define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */ + +/* ========================================================================= */ +local unsigned long gf2_matrix_times(mat, vec) + unsigned long *mat; + unsigned long vec; +{ + unsigned long sum; + + sum = 0; + while (vec) { + if (vec & 1) + sum ^= *mat; + vec >>= 1; + mat++; + } + return sum; +} + +/* ========================================================================= */ +local void gf2_matrix_square(square, mat) + unsigned long *square; + unsigned long *mat; +{ + int n; + + for (n = 0; n < GF2_DIM; n++) + square[n] = gf2_matrix_times(mat, mat[n]); +} + +/* ========================================================================= */ +local uLong crc32_combine_(crc1, crc2, len2) + uLong crc1; + uLong crc2; + z_off64_t len2; +{ + int n; + unsigned long row; + unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */ + unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */ + + /* degenerate case (also disallow negative lengths) */ + if (len2 <= 0) + return crc1; + + /* put operator for one zero bit in odd */ + odd[0] = 0xedb88320UL; /* CRC-32 polynomial */ + row = 1; + for (n = 1; n < GF2_DIM; n++) { + odd[n] = row; + row <<= 1; + } + + /* put operator for two zero bits in even */ + gf2_matrix_square(even, odd); + + /* put operator for four zero bits in odd */ + gf2_matrix_square(odd, even); + + /* apply len2 zeros to crc1 (first square will put the operator for one + zero byte, eight zero bits, in even) */ + do { + /* apply zeros operator for this bit of len2 */ + gf2_matrix_square(even, odd); + if (len2 & 1) + crc1 = gf2_matrix_times(even, crc1); + len2 >>= 1; + + /* if no more bits set, then done */ + if (len2 == 0) + break; + + /* another iteration of the loop with odd and even swapped */ + gf2_matrix_square(odd, even); + if (len2 & 1) + crc1 = gf2_matrix_times(odd, crc1); + len2 >>= 1; + + /* if no more bits set, then done */ + } while (len2 != 0); + + /* return combined crc */ + crc1 ^= crc2; + return crc1; +} + +/* ========================================================================= */ +uLong ZEXPORT crc32_combine(crc1, crc2, len2) + uLong crc1; + uLong crc2; + z_off_t len2; +{ + return crc32_combine_(crc1, crc2, len2); +} + +uLong ZEXPORT crc32_combine64(crc1, crc2, len2) + uLong crc1; + uLong crc2; + z_off64_t len2; +{ + return crc32_combine_(crc1, crc2, len2); +} diff --git a/Source/Libraries/zlib/deflate.c b/Source/Libraries/zlib/deflate.c new file mode 100644 index 0000000..1ec7614 --- /dev/null +++ b/Source/Libraries/zlib/deflate.c @@ -0,0 +1,2163 @@ +/* deflate.c -- compress data using the deflation algorithm + * Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * ALGORITHM + * + * The "deflation" process depends on being able to identify portions + * of the input text which are identical to earlier input (within a + * sliding window trailing behind the input currently being processed). + * + * The most straightforward technique turns out to be the fastest for + * most input files: try all possible matches and select the longest. + * The key feature of this algorithm is that insertions into the string + * dictionary are very simple and thus fast, and deletions are avoided + * completely. Insertions are performed at each input character, whereas + * string matches are performed only when the previous match ends. So it + * is preferable to spend more time in matches to allow very fast string + * insertions and avoid deletions. The matching algorithm for small + * strings is inspired from that of Rabin & Karp. A brute force approach + * is used to find longer strings when a small match has been found. + * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze + * (by Leonid Broukhis). + * A previous version of this file used a more sophisticated algorithm + * (by Fiala and Greene) which is guaranteed to run in linear amortized + * time, but has a larger average cost, uses more memory and is patented. + * However the F&G algorithm may be faster for some highly redundant + * files if the parameter max_chain_length (described below) is too large. + * + * ACKNOWLEDGEMENTS + * + * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and + * I found it in 'freeze' written by Leonid Broukhis. + * Thanks to many people for bug reports and testing. + * + * REFERENCES + * + * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification". + * Available in http://tools.ietf.org/html/rfc1951 + * + * A description of the Rabin and Karp algorithm is given in the book + * "Algorithms" by R. Sedgewick, Addison-Wesley, p252. + * + * Fiala,E.R., and Greene,D.H. + * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595 + * + */ + +/* @(#) $Id$ */ + +#include "deflate.h" + +const char deflate_copyright[] = + " deflate 1.2.11 Copyright 1995-2017 Jean-loup Gailly and Mark Adler "; +/* + If you use the zlib library in a product, an acknowledgment is welcome + in the documentation of your product. If for some reason you cannot + include such an acknowledgment, I would appreciate that you keep this + copyright string in the executable of your product. + */ + +/* =========================================================================== + * Function prototypes. + */ +typedef enum { + need_more, /* block not completed, need more input or more output */ + block_done, /* block flush performed */ + finish_started, /* finish started, need only more output at next deflate */ + finish_done /* finish done, accept no more input or output */ +} block_state; + +typedef block_state (*compress_func) OF((deflate_state *s, int flush)); +/* Compression function. Returns the block state after the call. */ + +local int deflateStateCheck OF((z_streamp strm)); +local void slide_hash OF((deflate_state *s)); +local void fill_window OF((deflate_state *s)); +local block_state deflate_stored OF((deflate_state *s, int flush)); +local block_state deflate_fast OF((deflate_state *s, int flush)); +#ifndef FASTEST +local block_state deflate_slow OF((deflate_state *s, int flush)); +#endif +local block_state deflate_rle OF((deflate_state *s, int flush)); +local block_state deflate_huff OF((deflate_state *s, int flush)); +local void lm_init OF((deflate_state *s)); +local void putShortMSB OF((deflate_state *s, uInt b)); +local void flush_pending OF((z_streamp strm)); +local unsigned read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); +#ifdef ASMV +# pragma message("Assembler code may have bugs -- use at your own risk") + void match_init OF((void)); /* asm code initialization */ + uInt longest_match OF((deflate_state *s, IPos cur_match)); +#else +local uInt longest_match OF((deflate_state *s, IPos cur_match)); +#endif + +#ifdef ZLIB_DEBUG +local void check_match OF((deflate_state *s, IPos start, IPos match, + int length)); +#endif + +/* =========================================================================== + * Local data + */ + +#define NIL 0 +/* Tail of hash chains */ + +#ifndef TOO_FAR +# define TOO_FAR 4096 +#endif +/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */ + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +typedef struct config_s { + ush good_length; /* reduce lazy search above this match length */ + ush max_lazy; /* do not perform lazy search above this match length */ + ush nice_length; /* quit search above this match length */ + ush max_chain; + compress_func func; +} config; + +#ifdef FASTEST +local const config configuration_table[2] = { +/* good lazy nice chain */ +/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ +/* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */ +#else +local const config configuration_table[10] = { +/* good lazy nice chain */ +/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ +/* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */ +/* 2 */ {4, 5, 16, 8, deflate_fast}, +/* 3 */ {4, 6, 32, 32, deflate_fast}, + +/* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */ +/* 5 */ {8, 16, 32, 32, deflate_slow}, +/* 6 */ {8, 16, 128, 128, deflate_slow}, +/* 7 */ {8, 32, 128, 256, deflate_slow}, +/* 8 */ {32, 128, 258, 1024, deflate_slow}, +/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */ +#endif + +/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4 + * For deflate_fast() (levels <= 3) good is ignored and lazy has a different + * meaning. + */ + +/* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */ +#define RANK(f) (((f) * 2) - ((f) > 4 ? 9 : 0)) + +/* =========================================================================== + * Update a hash value with the given input byte + * IN assertion: all calls to UPDATE_HASH are made with consecutive input + * characters, so that a running hash key can be computed from the previous + * key instead of complete recalculation each time. + */ +#define UPDATE_HASH(s,h,c) (h = (((h)<hash_shift) ^ (c)) & s->hash_mask) + + +/* =========================================================================== + * Insert string str in the dictionary and set match_head to the previous head + * of the hash chain (the most recent string with same hash key). Return + * the previous length of the hash chain. + * If this file is compiled with -DFASTEST, the compression level is forced + * to 1, and no hash chains are maintained. + * IN assertion: all calls to INSERT_STRING are made with consecutive input + * characters and the first MIN_MATCH bytes of str are valid (except for + * the last MIN_MATCH-1 bytes of the input file). + */ +#ifdef FASTEST +#define INSERT_STRING(s, str, match_head) \ + (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ + match_head = s->head[s->ins_h], \ + s->head[s->ins_h] = (Pos)(str)) +#else +#define INSERT_STRING(s, str, match_head) \ + (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ + match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \ + s->head[s->ins_h] = (Pos)(str)) +#endif + +/* =========================================================================== + * Initialize the hash table (avoiding 64K overflow for 16 bit systems). + * prev[] will be initialized on the fly. + */ +#define CLEAR_HASH(s) \ + s->head[s->hash_size-1] = NIL; \ + zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head)); + +/* =========================================================================== + * Slide the hash table when sliding the window down (could be avoided with 32 + * bit values at the expense of memory usage). We slide even when level == 0 to + * keep the hash table consistent if we switch back to level > 0 later. + */ +local void slide_hash(s) + deflate_state *s; +{ + unsigned n, m; + Posf *p; + uInt wsize = s->w_size; + + n = s->hash_size; + p = &s->head[n]; + do { + m = *--p; + *p = (Pos)(m >= wsize ? m - wsize : NIL); + } while (--n); + n = wsize; +#ifndef FASTEST + p = &s->prev[n]; + do { + m = *--p; + *p = (Pos)(m >= wsize ? m - wsize : NIL); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); +#endif +} + +/* ========================================================================= */ +int ZEXPORT deflateInit_(strm, level, version, stream_size) + z_streamp strm; + int level; + const char *version; + int stream_size; +{ + return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, + Z_DEFAULT_STRATEGY, version, stream_size); + /* To do: ignore strm->next_in if we use it as window */ +} + +/* ========================================================================= */ +int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, + version, stream_size) + z_streamp strm; + int level; + int method; + int windowBits; + int memLevel; + int strategy; + const char *version; + int stream_size; +{ + deflate_state *s; + int wrap = 1; + static const char my_version[] = ZLIB_VERSION; + + ushf *overlay; + /* We overlay pending_buf and d_buf+l_buf. This works since the average + * output size for (length,distance) codes is <= 24 bits. + */ + + if (version == Z_NULL || version[0] != my_version[0] || + stream_size != sizeof(z_stream)) { + return Z_VERSION_ERROR; + } + if (strm == Z_NULL) return Z_STREAM_ERROR; + + strm->msg = Z_NULL; + if (strm->zalloc == (alloc_func)0) { +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; +#endif + } + if (strm->zfree == (free_func)0) +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zfree = zcfree; +#endif + +#ifdef FASTEST + if (level != 0) level = 1; +#else + if (level == Z_DEFAULT_COMPRESSION) level = 6; +#endif + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } +#ifdef GZIP + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } +#endif + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED || (windowBits == 8 && wrap != 1)) { + return Z_STREAM_ERROR; + } + if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */ + s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state)); + if (s == Z_NULL) return Z_MEM_ERROR; + strm->state = (struct internal_state FAR *)s; + s->strm = strm; + s->status = INIT_STATE; /* to pass state test in deflateReset() */ + + s->wrap = wrap; + s->gzhead = Z_NULL; + s->w_bits = (uInt)windowBits; + s->w_size = 1 << s->w_bits; + s->w_mask = s->w_size - 1; + + s->hash_bits = (uInt)memLevel + 7; + s->hash_size = 1 << s->hash_bits; + s->hash_mask = s->hash_size - 1; + s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); + + s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte)); + s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); + s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos)); + + s->high_water = 0; /* nothing written to s->window yet */ + + s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + s->pending_buf = (uchf *) overlay; + s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L); + + if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL || + s->pending_buf == Z_NULL) { + s->status = FINISH_STATE; + strm->msg = ERR_MSG(Z_MEM_ERROR); + deflateEnd (strm); + return Z_MEM_ERROR; + } + s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + + s->level = level; + s->strategy = strategy; + s->method = (Byte)method; + + return deflateReset(strm); +} + +/* ========================================================================= + * Check for a valid deflate stream state. Return 0 if ok, 1 if not. + */ +local int deflateStateCheck (strm) + z_streamp strm; +{ + deflate_state *s; + if (strm == Z_NULL || + strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) + return 1; + s = strm->state; + if (s == Z_NULL || s->strm != strm || (s->status != INIT_STATE && +#ifdef GZIP + s->status != GZIP_STATE && +#endif + s->status != EXTRA_STATE && + s->status != NAME_STATE && + s->status != COMMENT_STATE && + s->status != HCRC_STATE && + s->status != BUSY_STATE && + s->status != FINISH_STATE)) + return 1; + return 0; +} + +/* ========================================================================= */ +int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) + z_streamp strm; + const Bytef *dictionary; + uInt dictLength; +{ + deflate_state *s; + uInt str, n; + int wrap; + unsigned avail; + z_const unsigned char *next; + + if (deflateStateCheck(strm) || dictionary == Z_NULL) + return Z_STREAM_ERROR; + s = strm->state; + wrap = s->wrap; + if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead) + return Z_STREAM_ERROR; + + /* when using zlib wrappers, compute Adler-32 for provided dictionary */ + if (wrap == 1) + strm->adler = adler32(strm->adler, dictionary, dictLength); + s->wrap = 0; /* avoid computing Adler-32 in read_buf */ + + /* if dictionary would fill window, just replace the history */ + if (dictLength >= s->w_size) { + if (wrap == 0) { /* already empty otherwise */ + CLEAR_HASH(s); + s->strstart = 0; + s->block_start = 0L; + s->insert = 0; + } + dictionary += dictLength - s->w_size; /* use the tail */ + dictLength = s->w_size; + } + + /* insert dictionary into window and hash */ + avail = strm->avail_in; + next = strm->next_in; + strm->avail_in = dictLength; + strm->next_in = (z_const Bytef *)dictionary; + fill_window(s); + while (s->lookahead >= MIN_MATCH) { + str = s->strstart; + n = s->lookahead - (MIN_MATCH-1); + do { + UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); +#ifndef FASTEST + s->prev[str & s->w_mask] = s->head[s->ins_h]; +#endif + s->head[s->ins_h] = (Pos)str; + str++; + } while (--n); + s->strstart = str; + s->lookahead = MIN_MATCH-1; + fill_window(s); + } + s->strstart += s->lookahead; + s->block_start = (long)s->strstart; + s->insert = s->lookahead; + s->lookahead = 0; + s->match_length = s->prev_length = MIN_MATCH-1; + s->match_available = 0; + strm->next_in = next; + strm->avail_in = avail; + s->wrap = wrap; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateGetDictionary (strm, dictionary, dictLength) + z_streamp strm; + Bytef *dictionary; + uInt *dictLength; +{ + deflate_state *s; + uInt len; + + if (deflateStateCheck(strm)) + return Z_STREAM_ERROR; + s = strm->state; + len = s->strstart + s->lookahead; + if (len > s->w_size) + len = s->w_size; + if (dictionary != Z_NULL && len) + zmemcpy(dictionary, s->window + s->strstart + s->lookahead - len, len); + if (dictLength != Z_NULL) + *dictLength = len; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateResetKeep (strm) + z_streamp strm; +{ + deflate_state *s; + + if (deflateStateCheck(strm)) { + return Z_STREAM_ERROR; + } + + strm->total_in = strm->total_out = 0; + strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */ + strm->data_type = Z_UNKNOWN; + + s = (deflate_state *)strm->state; + s->pending = 0; + s->pending_out = s->pending_buf; + + if (s->wrap < 0) { + s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */ + } + s->status = +#ifdef GZIP + s->wrap == 2 ? GZIP_STATE : +#endif + s->wrap ? INIT_STATE : BUSY_STATE; + strm->adler = +#ifdef GZIP + s->wrap == 2 ? crc32(0L, Z_NULL, 0) : +#endif + adler32(0L, Z_NULL, 0); + s->last_flush = Z_NO_FLUSH; + + _tr_init(s); + + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateReset (strm) + z_streamp strm; +{ + int ret; + + ret = deflateResetKeep(strm); + if (ret == Z_OK) + lm_init(strm->state); + return ret; +} + +/* ========================================================================= */ +int ZEXPORT deflateSetHeader (strm, head) + z_streamp strm; + gz_headerp head; +{ + if (deflateStateCheck(strm) || strm->state->wrap != 2) + return Z_STREAM_ERROR; + strm->state->gzhead = head; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflatePending (strm, pending, bits) + unsigned *pending; + int *bits; + z_streamp strm; +{ + if (deflateStateCheck(strm)) return Z_STREAM_ERROR; + if (pending != Z_NULL) + *pending = strm->state->pending; + if (bits != Z_NULL) + *bits = strm->state->bi_valid; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflatePrime (strm, bits, value) + z_streamp strm; + int bits; + int value; +{ + deflate_state *s; + int put; + + if (deflateStateCheck(strm)) return Z_STREAM_ERROR; + s = strm->state; + if ((Bytef *)(s->d_buf) < s->pending_out + ((Buf_size + 7) >> 3)) + return Z_BUF_ERROR; + do { + put = Buf_size - s->bi_valid; + if (put > bits) + put = bits; + s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid); + s->bi_valid += put; + _tr_flush_bits(s); + value >>= put; + bits -= put; + } while (bits); + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateParams(strm, level, strategy) + z_streamp strm; + int level; + int strategy; +{ + deflate_state *s; + compress_func func; + + if (deflateStateCheck(strm)) return Z_STREAM_ERROR; + s = strm->state; + +#ifdef FASTEST + if (level != 0) level = 1; +#else + if (level == Z_DEFAULT_COMPRESSION) level = 6; +#endif + if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { + return Z_STREAM_ERROR; + } + func = configuration_table[s->level].func; + + if ((strategy != s->strategy || func != configuration_table[level].func) && + s->high_water) { + /* Flush the last buffer: */ + int err = deflate(strm, Z_BLOCK); + if (err == Z_STREAM_ERROR) + return err; + if (strm->avail_out == 0) + return Z_BUF_ERROR; + } + if (s->level != level) { + if (s->level == 0 && s->matches != 0) { + if (s->matches == 1) + slide_hash(s); + else + CLEAR_HASH(s); + s->matches = 0; + } + s->level = level; + s->max_lazy_match = configuration_table[level].max_lazy; + s->good_match = configuration_table[level].good_length; + s->nice_match = configuration_table[level].nice_length; + s->max_chain_length = configuration_table[level].max_chain; + } + s->strategy = strategy; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain) + z_streamp strm; + int good_length; + int max_lazy; + int nice_length; + int max_chain; +{ + deflate_state *s; + + if (deflateStateCheck(strm)) return Z_STREAM_ERROR; + s = strm->state; + s->good_match = (uInt)good_length; + s->max_lazy_match = (uInt)max_lazy; + s->nice_match = nice_length; + s->max_chain_length = (uInt)max_chain; + return Z_OK; +} + +/* ========================================================================= + * For the default windowBits of 15 and memLevel of 8, this function returns + * a close to exact, as well as small, upper bound on the compressed size. + * They are coded as constants here for a reason--if the #define's are + * changed, then this function needs to be changed as well. The return + * value for 15 and 8 only works for those exact settings. + * + * For any setting other than those defaults for windowBits and memLevel, + * the value returned is a conservative worst case for the maximum expansion + * resulting from using fixed blocks instead of stored blocks, which deflate + * can emit on compressed data for some combinations of the parameters. + * + * This function could be more sophisticated to provide closer upper bounds for + * every combination of windowBits and memLevel. But even the conservative + * upper bound of about 14% expansion does not seem onerous for output buffer + * allocation. + */ +uLong ZEXPORT deflateBound(strm, sourceLen) + z_streamp strm; + uLong sourceLen; +{ + deflate_state *s; + uLong complen, wraplen; + + /* conservative upper bound for compressed data */ + complen = sourceLen + + ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5; + + /* if can't get parameters, return conservative bound plus zlib wrapper */ + if (deflateStateCheck(strm)) + return complen + 6; + + /* compute wrapper length */ + s = strm->state; + switch (s->wrap) { + case 0: /* raw deflate */ + wraplen = 0; + break; + case 1: /* zlib wrapper */ + wraplen = 6 + (s->strstart ? 4 : 0); + break; +#ifdef GZIP + case 2: /* gzip wrapper */ + wraplen = 18; + if (s->gzhead != Z_NULL) { /* user-supplied gzip header */ + Bytef *str; + if (s->gzhead->extra != Z_NULL) + wraplen += 2 + s->gzhead->extra_len; + str = s->gzhead->name; + if (str != Z_NULL) + do { + wraplen++; + } while (*str++); + str = s->gzhead->comment; + if (str != Z_NULL) + do { + wraplen++; + } while (*str++); + if (s->gzhead->hcrc) + wraplen += 2; + } + break; +#endif + default: /* for compiler happiness */ + wraplen = 6; + } + + /* if not default parameters, return conservative bound */ + if (s->w_bits != 15 || s->hash_bits != 8 + 7) + return complen + wraplen; + + /* default settings: return tight bound for that case */ + return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + + (sourceLen >> 25) + 13 - 6 + wraplen; +} + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +local void putShortMSB (s, b) + deflate_state *s; + uInt b; +{ + put_byte(s, (Byte)(b >> 8)); + put_byte(s, (Byte)(b & 0xff)); +} + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output, except for + * some deflate_stored() output, goes through this function so some + * applications may wish to modify it to avoid allocating a large + * strm->next_out buffer and copying into it. (See also read_buf()). + */ +local void flush_pending(strm) + z_streamp strm; +{ + unsigned len; + deflate_state *s = strm->state; + + _tr_flush_bits(s); + len = s->pending; + if (len > strm->avail_out) len = strm->avail_out; + if (len == 0) return; + + zmemcpy(strm->next_out, s->pending_out, len); + strm->next_out += len; + s->pending_out += len; + strm->total_out += len; + strm->avail_out -= len; + s->pending -= len; + if (s->pending == 0) { + s->pending_out = s->pending_buf; + } +} + +/* =========================================================================== + * Update the header CRC with the bytes s->pending_buf[beg..s->pending - 1]. + */ +#define HCRC_UPDATE(beg) \ + do { \ + if (s->gzhead->hcrc && s->pending > (beg)) \ + strm->adler = crc32(strm->adler, s->pending_buf + (beg), \ + s->pending - (beg)); \ + } while (0) + +/* ========================================================================= */ +int ZEXPORT deflate (strm, flush) + z_streamp strm; + int flush; +{ + int old_flush; /* value of flush param for previous deflate call */ + deflate_state *s; + + if (deflateStateCheck(strm) || flush > Z_BLOCK || flush < 0) { + return Z_STREAM_ERROR; + } + s = strm->state; + + if (strm->next_out == Z_NULL || + (strm->avail_in != 0 && strm->next_in == Z_NULL) || + (s->status == FINISH_STATE && flush != Z_FINISH)) { + ERR_RETURN(strm, Z_STREAM_ERROR); + } + if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR); + + old_flush = s->last_flush; + s->last_flush = flush; + + /* Flush as much pending output as possible */ + if (s->pending != 0) { + flush_pending(strm); + if (strm->avail_out == 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s->last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) && + flush != Z_FINISH) { + ERR_RETURN(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s->status == FINISH_STATE && strm->avail_in != 0) { + ERR_RETURN(strm, Z_BUF_ERROR); + } + + /* Write the header */ + if (s->status == INIT_STATE) { + /* zlib header */ + uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; + uInt level_flags; + + if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2) + level_flags = 0; + else if (s->level < 6) + level_flags = 1; + else if (s->level == 6) + level_flags = 2; + else + level_flags = 3; + header |= (level_flags << 6); + if (s->strstart != 0) header |= PRESET_DICT; + header += 31 - (header % 31); + + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s->strstart != 0) { + putShortMSB(s, (uInt)(strm->adler >> 16)); + putShortMSB(s, (uInt)(strm->adler & 0xffff)); + } + strm->adler = adler32(0L, Z_NULL, 0); + s->status = BUSY_STATE; + + /* Compression must start with an empty pending buffer */ + flush_pending(strm); + if (s->pending != 0) { + s->last_flush = -1; + return Z_OK; + } + } +#ifdef GZIP + if (s->status == GZIP_STATE) { + /* gzip header */ + strm->adler = crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (s->gzhead == Z_NULL) { + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s->level == 9 ? 2 : + (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s->status = BUSY_STATE; + + /* Compression must start with an empty pending buffer */ + flush_pending(strm); + if (s->pending != 0) { + s->last_flush = -1; + return Z_OK; + } + } + else { + put_byte(s, (s->gzhead->text ? 1 : 0) + + (s->gzhead->hcrc ? 2 : 0) + + (s->gzhead->extra == Z_NULL ? 0 : 4) + + (s->gzhead->name == Z_NULL ? 0 : 8) + + (s->gzhead->comment == Z_NULL ? 0 : 16) + ); + put_byte(s, (Byte)(s->gzhead->time & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff)); + put_byte(s, s->level == 9 ? 2 : + (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? + 4 : 0)); + put_byte(s, s->gzhead->os & 0xff); + if (s->gzhead->extra != Z_NULL) { + put_byte(s, s->gzhead->extra_len & 0xff); + put_byte(s, (s->gzhead->extra_len >> 8) & 0xff); + } + if (s->gzhead->hcrc) + strm->adler = crc32(strm->adler, s->pending_buf, + s->pending); + s->gzindex = 0; + s->status = EXTRA_STATE; + } + } + if (s->status == EXTRA_STATE) { + if (s->gzhead->extra != Z_NULL) { + ulg beg = s->pending; /* start of bytes to update crc */ + uInt left = (s->gzhead->extra_len & 0xffff) - s->gzindex; + while (s->pending + left > s->pending_buf_size) { + uInt copy = s->pending_buf_size - s->pending; + zmemcpy(s->pending_buf + s->pending, + s->gzhead->extra + s->gzindex, copy); + s->pending = s->pending_buf_size; + HCRC_UPDATE(beg); + s->gzindex += copy; + flush_pending(strm); + if (s->pending != 0) { + s->last_flush = -1; + return Z_OK; + } + beg = 0; + left -= copy; + } + zmemcpy(s->pending_buf + s->pending, + s->gzhead->extra + s->gzindex, left); + s->pending += left; + HCRC_UPDATE(beg); + s->gzindex = 0; + } + s->status = NAME_STATE; + } + if (s->status == NAME_STATE) { + if (s->gzhead->name != Z_NULL) { + ulg beg = s->pending; /* start of bytes to update crc */ + int val; + do { + if (s->pending == s->pending_buf_size) { + HCRC_UPDATE(beg); + flush_pending(strm); + if (s->pending != 0) { + s->last_flush = -1; + return Z_OK; + } + beg = 0; + } + val = s->gzhead->name[s->gzindex++]; + put_byte(s, val); + } while (val != 0); + HCRC_UPDATE(beg); + s->gzindex = 0; + } + s->status = COMMENT_STATE; + } + if (s->status == COMMENT_STATE) { + if (s->gzhead->comment != Z_NULL) { + ulg beg = s->pending; /* start of bytes to update crc */ + int val; + do { + if (s->pending == s->pending_buf_size) { + HCRC_UPDATE(beg); + flush_pending(strm); + if (s->pending != 0) { + s->last_flush = -1; + return Z_OK; + } + beg = 0; + } + val = s->gzhead->comment[s->gzindex++]; + put_byte(s, val); + } while (val != 0); + HCRC_UPDATE(beg); + } + s->status = HCRC_STATE; + } + if (s->status == HCRC_STATE) { + if (s->gzhead->hcrc) { + if (s->pending + 2 > s->pending_buf_size) { + flush_pending(strm); + if (s->pending != 0) { + s->last_flush = -1; + return Z_OK; + } + } + put_byte(s, (Byte)(strm->adler & 0xff)); + put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); + strm->adler = crc32(0L, Z_NULL, 0); + } + s->status = BUSY_STATE; + + /* Compression must start with an empty pending buffer */ + flush_pending(strm); + if (s->pending != 0) { + s->last_flush = -1; + return Z_OK; + } + } +#endif + + /* Start a new block or continue the current one. + */ + if (strm->avail_in != 0 || s->lookahead != 0 || + (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { + block_state bstate; + + bstate = s->level == 0 ? deflate_stored(s, flush) : + s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) : + s->strategy == Z_RLE ? deflate_rle(s, flush) : + (*(configuration_table[s->level].func))(s, flush); + + if (bstate == finish_started || bstate == finish_done) { + s->status = FINISH_STATE; + } + if (bstate == need_more || bstate == finish_started) { + if (strm->avail_out == 0) { + s->last_flush = -1; /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate == block_done) { + if (flush == Z_PARTIAL_FLUSH) { + _tr_align(s); + } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ + _tr_stored_block(s, (char*)0, 0L, 0); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush == Z_FULL_FLUSH) { + CLEAR_HASH(s); /* forget history */ + if (s->lookahead == 0) { + s->strstart = 0; + s->block_start = 0L; + s->insert = 0; + } + } + } + flush_pending(strm); + if (strm->avail_out == 0) { + s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + + if (flush != Z_FINISH) return Z_OK; + if (s->wrap <= 0) return Z_STREAM_END; + + /* Write the trailer */ +#ifdef GZIP + if (s->wrap == 2) { + put_byte(s, (Byte)(strm->adler & 0xff)); + put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); + put_byte(s, (Byte)((strm->adler >> 16) & 0xff)); + put_byte(s, (Byte)((strm->adler >> 24) & 0xff)); + put_byte(s, (Byte)(strm->total_in & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 8) & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 16) & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 24) & 0xff)); + } + else +#endif + { + putShortMSB(s, (uInt)(strm->adler >> 16)); + putShortMSB(s, (uInt)(strm->adler & 0xffff)); + } + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */ + return s->pending != 0 ? Z_OK : Z_STREAM_END; +} + +/* ========================================================================= */ +int ZEXPORT deflateEnd (strm) + z_streamp strm; +{ + int status; + + if (deflateStateCheck(strm)) return Z_STREAM_ERROR; + + status = strm->state->status; + + /* Deallocate in reverse order of allocations: */ + TRY_FREE(strm, strm->state->pending_buf); + TRY_FREE(strm, strm->state->head); + TRY_FREE(strm, strm->state->prev); + TRY_FREE(strm, strm->state->window); + + ZFREE(strm, strm->state); + strm->state = Z_NULL; + + return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK; +} + +/* ========================================================================= + * Copy the source state to the destination state. + * To simplify the source, this is not supported for 16-bit MSDOS (which + * doesn't have enough memory anyway to duplicate compression states). + */ +int ZEXPORT deflateCopy (dest, source) + z_streamp dest; + z_streamp source; +{ +#ifdef MAXSEG_64K + return Z_STREAM_ERROR; +#else + deflate_state *ds; + deflate_state *ss; + ushf *overlay; + + + if (deflateStateCheck(source) || dest == Z_NULL) { + return Z_STREAM_ERROR; + } + + ss = source->state; + + zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream)); + + ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state)); + if (ds == Z_NULL) return Z_MEM_ERROR; + dest->state = (struct internal_state FAR *) ds; + zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state)); + ds->strm = dest; + + ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); + ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos)); + ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos)); + overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2); + ds->pending_buf = (uchf *) overlay; + + if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || + ds->pending_buf == Z_NULL) { + deflateEnd (dest); + return Z_MEM_ERROR; + } + /* following zmemcpy do not work for 16-bit MSDOS */ + zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte)); + zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos)); + zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos)); + zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); + + ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); + ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush); + ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize; + + ds->l_desc.dyn_tree = ds->dyn_ltree; + ds->d_desc.dyn_tree = ds->dyn_dtree; + ds->bl_desc.dyn_tree = ds->bl_tree; + + return Z_OK; +#endif /* MAXSEG_64K */ +} + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->next_in buffer and copying from it. + * (See also flush_pending()). + */ +local unsigned read_buf(strm, buf, size) + z_streamp strm; + Bytef *buf; + unsigned size; +{ + unsigned len = strm->avail_in; + + if (len > size) len = size; + if (len == 0) return 0; + + strm->avail_in -= len; + + zmemcpy(buf, strm->next_in, len); + if (strm->state->wrap == 1) { + strm->adler = adler32(strm->adler, buf, len); + } +#ifdef GZIP + else if (strm->state->wrap == 2) { + strm->adler = crc32(strm->adler, buf, len); + } +#endif + strm->next_in += len; + strm->total_in += len; + + return len; +} + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +local void lm_init (s) + deflate_state *s; +{ + s->window_size = (ulg)2L*s->w_size; + + CLEAR_HASH(s); + + /* Set the default configuration parameters: + */ + s->max_lazy_match = configuration_table[s->level].max_lazy; + s->good_match = configuration_table[s->level].good_length; + s->nice_match = configuration_table[s->level].nice_length; + s->max_chain_length = configuration_table[s->level].max_chain; + + s->strstart = 0; + s->block_start = 0L; + s->lookahead = 0; + s->insert = 0; + s->match_length = s->prev_length = MIN_MATCH-1; + s->match_available = 0; + s->ins_h = 0; +#ifndef FASTEST +#ifdef ASMV + match_init(); /* initialize the asm code */ +#endif +#endif +} + +#ifndef FASTEST +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +#ifndef ASMV +/* For 80x86 and 680x0, an optimized version will be provided in match.asm or + * match.S. The code will be functionally equivalent. + */ +local uInt longest_match(s, cur_match) + deflate_state *s; + IPos cur_match; /* current match */ +{ + unsigned chain_length = s->max_chain_length;/* max hash chain length */ + register Bytef *scan = s->window + s->strstart; /* current string */ + register Bytef *match; /* matched string */ + register int len; /* length of current match */ + int best_len = (int)s->prev_length; /* best match length so far */ + int nice_match = s->nice_match; /* stop if match long enough */ + IPos limit = s->strstart > (IPos)MAX_DIST(s) ? + s->strstart - (IPos)MAX_DIST(s) : NIL; + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + Posf *prev = s->prev; + uInt wmask = s->w_mask; + +#ifdef UNALIGNED_OK + /* Compare two bytes at a time. Note: this is not always beneficial. + * Try with and without -DUNALIGNED_OK to check. + */ + register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1; + register ush scan_start = *(ushf*)scan; + register ush scan_end = *(ushf*)(scan+best_len-1); +#else + register Bytef *strend = s->window + s->strstart + MAX_MATCH; + register Byte scan_end1 = scan[best_len-1]; + register Byte scan_end = scan[best_len]; +#endif + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s->prev_length >= s->good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if ((uInt)nice_match > s->lookahead) nice_match = (int)s->lookahead; + + Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + Assert(cur_match < s->strstart, "no future"); + match = s->window + cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ +#if (defined(UNALIGNED_OK) && MAX_MATCH == 258) + /* This code assumes sizeof(unsigned short) == 2. Do not use + * UNALIGNED_OK if your compiler uses a different size. + */ + if (*(ushf*)(match+best_len-1) != scan_end || + *(ushf*)match != scan_start) continue; + + /* It is not necessary to compare scan[2] and match[2] since they are + * always equal when the other bytes match, given that the hash keys + * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at + * strstart+3, +5, ... up to strstart+257. We check for insufficient + * lookahead only every 4th comparison; the 128th check will be made + * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is + * necessary to put more guard bytes at the end of the window, or + * to check more often for insufficient lookahead. + */ + Assert(scan[2] == match[2], "scan[2]?"); + scan++, match++; + do { + } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + scan < strend); + /* The funny "do {}" generates better code on most compilers */ + + /* Here, scan <= window+strstart+257 */ + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + if (*scan == *match) scan++; + + len = (MAX_MATCH - 1) - (int)(strend-scan); + scan = strend - (MAX_MATCH-1); + +#else /* UNALIGNED_OK */ + + if (match[best_len] != scan_end || + match[best_len-1] != scan_end1 || + *match != *scan || + *++match != scan[1]) continue; + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2, match++; + Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + } while (*++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + scan < strend); + + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (int)(strend - scan); + scan = strend - MAX_MATCH; + +#endif /* UNALIGNED_OK */ + + if (len > best_len) { + s->match_start = cur_match; + best_len = len; + if (len >= nice_match) break; +#ifdef UNALIGNED_OK + scan_end = *(ushf*)(scan+best_len-1); +#else + scan_end1 = scan[best_len-1]; + scan_end = scan[best_len]; +#endif + } + } while ((cur_match = prev[cur_match & wmask]) > limit + && --chain_length != 0); + + if ((uInt)best_len <= s->lookahead) return (uInt)best_len; + return s->lookahead; +} +#endif /* ASMV */ + +#else /* FASTEST */ + +/* --------------------------------------------------------------------------- + * Optimized version for FASTEST only + */ +local uInt longest_match(s, cur_match) + deflate_state *s; + IPos cur_match; /* current match */ +{ + register Bytef *scan = s->window + s->strstart; /* current string */ + register Bytef *match; /* matched string */ + register int len; /* length of current match */ + register Bytef *strend = s->window + s->strstart + MAX_MATCH; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + Assert(cur_match < s->strstart, "no future"); + + match = s->window + cur_match; + + /* Return failure if the match length is less than 2: + */ + if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1; + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2, match += 2; + Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + } while (*++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + scan < strend); + + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (int)(strend - scan); + + if (len < MIN_MATCH) return MIN_MATCH - 1; + + s->match_start = cur_match; + return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead; +} + +#endif /* FASTEST */ + +#ifdef ZLIB_DEBUG + +#define EQUAL 0 +/* result of memcmp for equal strings */ + +/* =========================================================================== + * Check that the match at match_start is indeed a match. + */ +local void check_match(s, start, match, length) + deflate_state *s; + IPos start, match; + int length; +{ + /* check that the match is indeed a match */ + if (zmemcmp(s->window + match, + s->window + start, length) != EQUAL) { + fprintf(stderr, " start %u, match %u, length %d\n", + start, match, length); + do { + fprintf(stderr, "%c%c", s->window[match++], s->window[start++]); + } while (--length != 0); + z_error("invalid match"); + } + if (z_verbose > 1) { + fprintf(stderr,"\\[%d,%d]", start-match, length); + do { putc(s->window[start++], stderr); } while (--length != 0); + } +} +#else +# define check_match(s, start, match, length) +#endif /* ZLIB_DEBUG */ + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +local void fill_window(s) + deflate_state *s; +{ + unsigned n; + unsigned more; /* Amount of free space at the end of the window. */ + uInt wsize = s->w_size; + + Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); + + /* Deal with !@#$% 64K limit: */ + if (sizeof(int) <= 2) { + if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + more = wsize; + + } else if (more == (unsigned)(-1)) { + /* Very unlikely, but possible on 16 bit machine if + * strstart == 0 && lookahead == 1 (input done a byte at time) + */ + more--; + } + } + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s->strstart >= wsize+MAX_DIST(s)) { + + zmemcpy(s->window, s->window+wsize, (unsigned)wsize - more); + s->match_start -= wsize; + s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ + s->block_start -= (long) wsize; + slide_hash(s); + more += wsize; + } + if (s->strm->avail_in == 0) break; + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + Assert(more >= 2, "more < 2"); + + n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); + s->lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s->lookahead + s->insert >= MIN_MATCH) { + uInt str = s->strstart - s->insert; + s->ins_h = s->window[str]; + UPDATE_HASH(s, s->ins_h, s->window[str + 1]); +#if MIN_MATCH != 3 + Call UPDATE_HASH() MIN_MATCH-3 more times +#endif + while (s->insert) { + UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); +#ifndef FASTEST + s->prev[str & s->w_mask] = s->head[s->ins_h]; +#endif + s->head[s->ins_h] = (Pos)str; + str++; + s->insert--; + if (s->lookahead + s->insert < MIN_MATCH) + break; + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ + if (s->high_water < s->window_size) { + ulg curr = s->strstart + (ulg)(s->lookahead); + ulg init; + + if (s->high_water < curr) { + /* Previous high water mark below current data -- zero WIN_INIT + * bytes or up to end of window, whichever is less. + */ + init = s->window_size - curr; + if (init > WIN_INIT) + init = WIN_INIT; + zmemzero(s->window + curr, (unsigned)init); + s->high_water = curr + init; + } + else if (s->high_water < (ulg)curr + WIN_INIT) { + /* High water mark at or above current data, but below current data + * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up + * to end of window, whichever is less. + */ + init = (ulg)curr + WIN_INIT - s->high_water; + if (init > s->window_size - s->high_water) + init = s->window_size - s->high_water; + zmemzero(s->window + s->high_water, (unsigned)init); + s->high_water += init; + } + } + + Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, + "not enough room for search"); +} + +/* =========================================================================== + * Flush the current block, with given end-of-file flag. + * IN assertion: strstart is set to the end of the current match. + */ +#define FLUSH_BLOCK_ONLY(s, last) { \ + _tr_flush_block(s, (s->block_start >= 0L ? \ + (charf *)&s->window[(unsigned)s->block_start] : \ + (charf *)Z_NULL), \ + (ulg)((long)s->strstart - s->block_start), \ + (last)); \ + s->block_start = s->strstart; \ + flush_pending(s->strm); \ + Tracev((stderr,"[FLUSH]")); \ +} + +/* Same but force premature exit if necessary. */ +#define FLUSH_BLOCK(s, last) { \ + FLUSH_BLOCK_ONLY(s, last); \ + if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \ +} + +/* Maximum stored block length in deflate format (not including header). */ +#define MAX_STORED 65535 + +/* Minimum of a and b. */ +#define MIN(a, b) ((a) > (b) ? (b) : (a)) + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * + * In case deflateParams() is used to later switch to a non-zero compression + * level, s->matches (otherwise unused when storing) keeps track of the number + * of hash table slides to perform. If s->matches is 1, then one hash table + * slide will be done when switching. If s->matches is 2, the maximum value + * allowed here, then the hash table will be cleared, since two or more slides + * is the same as a clear. + * + * deflate_stored() is written to minimize the number of times an input byte is + * copied. It is most efficient with large input and output buffers, which + * maximizes the opportunites to have a single copy from next_in to next_out. + */ +local block_state deflate_stored(s, flush) + deflate_state *s; + int flush; +{ + /* Smallest worthy block size when not flushing or finishing. By default + * this is 32K. This can be as small as 507 bytes for memLevel == 1. For + * large input and output buffers, the stored block size will be larger. + */ + unsigned min_block = MIN(s->pending_buf_size - 5, s->w_size); + + /* Copy as many min_block or larger stored blocks directly to next_out as + * possible. If flushing, copy the remaining available input to next_out as + * stored blocks, if there is enough space. + */ + unsigned len, left, have, last = 0; + unsigned used = s->strm->avail_in; + do { + /* Set len to the maximum size block that we can copy directly with the + * available input data and output space. Set left to how much of that + * would be copied from what's left in the window. + */ + len = MAX_STORED; /* maximum deflate stored block length */ + have = (s->bi_valid + 42) >> 3; /* number of header bytes */ + if (s->strm->avail_out < have) /* need room for header */ + break; + /* maximum stored block length that will fit in avail_out: */ + have = s->strm->avail_out - have; + left = s->strstart - s->block_start; /* bytes left in window */ + if (len > (ulg)left + s->strm->avail_in) + len = left + s->strm->avail_in; /* limit len to the input */ + if (len > have) + len = have; /* limit len to the output */ + + /* If the stored block would be less than min_block in length, or if + * unable to copy all of the available input when flushing, then try + * copying to the window and the pending buffer instead. Also don't + * write an empty block when flushing -- deflate() does that. + */ + if (len < min_block && ((len == 0 && flush != Z_FINISH) || + flush == Z_NO_FLUSH || + len != left + s->strm->avail_in)) + break; + + /* Make a dummy stored block in pending to get the header bytes, + * including any pending bits. This also updates the debugging counts. + */ + last = flush == Z_FINISH && len == left + s->strm->avail_in ? 1 : 0; + _tr_stored_block(s, (char *)0, 0L, last); + + /* Replace the lengths in the dummy stored block with len. */ + s->pending_buf[s->pending - 4] = len; + s->pending_buf[s->pending - 3] = len >> 8; + s->pending_buf[s->pending - 2] = ~len; + s->pending_buf[s->pending - 1] = ~len >> 8; + + /* Write the stored block header bytes. */ + flush_pending(s->strm); + +#ifdef ZLIB_DEBUG + /* Update debugging counts for the data about to be copied. */ + s->compressed_len += len << 3; + s->bits_sent += len << 3; +#endif + + /* Copy uncompressed bytes from the window to next_out. */ + if (left) { + if (left > len) + left = len; + zmemcpy(s->strm->next_out, s->window + s->block_start, left); + s->strm->next_out += left; + s->strm->avail_out -= left; + s->strm->total_out += left; + s->block_start += left; + len -= left; + } + + /* Copy uncompressed bytes directly from next_in to next_out, updating + * the check value. + */ + if (len) { + read_buf(s->strm, s->strm->next_out, len); + s->strm->next_out += len; + s->strm->avail_out -= len; + s->strm->total_out += len; + } + } while (last == 0); + + /* Update the sliding window with the last s->w_size bytes of the copied + * data, or append all of the copied data to the existing window if less + * than s->w_size bytes were copied. Also update the number of bytes to + * insert in the hash tables, in the event that deflateParams() switches to + * a non-zero compression level. + */ + used -= s->strm->avail_in; /* number of input bytes directly copied */ + if (used) { + /* If any input was used, then no unused input remains in the window, + * therefore s->block_start == s->strstart. + */ + if (used >= s->w_size) { /* supplant the previous history */ + s->matches = 2; /* clear hash */ + zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size); + s->strstart = s->w_size; + } + else { + if (s->window_size - s->strstart <= used) { + /* Slide the window down. */ + s->strstart -= s->w_size; + zmemcpy(s->window, s->window + s->w_size, s->strstart); + if (s->matches < 2) + s->matches++; /* add a pending slide_hash() */ + } + zmemcpy(s->window + s->strstart, s->strm->next_in - used, used); + s->strstart += used; + } + s->block_start = s->strstart; + s->insert += MIN(used, s->w_size - s->insert); + } + if (s->high_water < s->strstart) + s->high_water = s->strstart; + + /* If the last block was written to next_out, then done. */ + if (last) + return finish_done; + + /* If flushing and all input has been consumed, then done. */ + if (flush != Z_NO_FLUSH && flush != Z_FINISH && + s->strm->avail_in == 0 && (long)s->strstart == s->block_start) + return block_done; + + /* Fill the window with any remaining input. */ + have = s->window_size - s->strstart - 1; + if (s->strm->avail_in > have && s->block_start >= (long)s->w_size) { + /* Slide the window down. */ + s->block_start -= s->w_size; + s->strstart -= s->w_size; + zmemcpy(s->window, s->window + s->w_size, s->strstart); + if (s->matches < 2) + s->matches++; /* add a pending slide_hash() */ + have += s->w_size; /* more space now */ + } + if (have > s->strm->avail_in) + have = s->strm->avail_in; + if (have) { + read_buf(s->strm, s->window + s->strstart, have); + s->strstart += have; + } + if (s->high_water < s->strstart) + s->high_water = s->strstart; + + /* There was not enough avail_out to write a complete worthy or flushed + * stored block to next_out. Write a stored block to pending instead, if we + * have enough input for a worthy block, or if flushing and there is enough + * room for the remaining input as a stored block in the pending buffer. + */ + have = (s->bi_valid + 42) >> 3; /* number of header bytes */ + /* maximum stored block length that will fit in pending: */ + have = MIN(s->pending_buf_size - have, MAX_STORED); + min_block = MIN(have, s->w_size); + left = s->strstart - s->block_start; + if (left >= min_block || + ((left || flush == Z_FINISH) && flush != Z_NO_FLUSH && + s->strm->avail_in == 0 && left <= have)) { + len = MIN(left, have); + last = flush == Z_FINISH && s->strm->avail_in == 0 && + len == left ? 1 : 0; + _tr_stored_block(s, (charf *)s->window + s->block_start, len, last); + s->block_start += len; + flush_pending(s->strm); + } + + /* We've done all we can with the available input and output. */ + return last ? finish_started : need_more; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +local block_state deflate_fast(s, flush) + deflate_state *s; + int flush; +{ + IPos hash_head; /* head of the hash chain */ + int bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s->lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = NIL; + if (s->lookahead >= MIN_MATCH) { + INSERT_STRING(s, s->strstart, hash_head); + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s->match_length = longest_match (s, hash_head); + /* longest_match() sets match_start */ + } + if (s->match_length >= MIN_MATCH) { + check_match(s, s->strstart, s->match_start, s->match_length); + + _tr_tally_dist(s, s->strstart - s->match_start, + s->match_length - MIN_MATCH, bflush); + + s->lookahead -= s->match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ +#ifndef FASTEST + if (s->match_length <= s->max_insert_length && + s->lookahead >= MIN_MATCH) { + s->match_length--; /* string at strstart already in table */ + do { + s->strstart++; + INSERT_STRING(s, s->strstart, hash_head); + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s->match_length != 0); + s->strstart++; + } else +#endif + { + s->strstart += s->match_length; + s->match_length = 0; + s->ins_h = s->window[s->strstart]; + UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); +#if MIN_MATCH != 3 + Call UPDATE_HASH() MIN_MATCH-3 more times +#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + } + if (bflush) FLUSH_BLOCK(s, 0); + } + s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; +} + +#ifndef FASTEST +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +local block_state deflate_slow(s, flush) + deflate_state *s; + int flush; +{ + IPos hash_head; /* head of hash chain */ + int bflush; /* set if current block must be flushed */ + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s->lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = NIL; + if (s->lookahead >= MIN_MATCH) { + INSERT_STRING(s, s->strstart, hash_head); + } + + /* Find the longest match, discarding those <= prev_length. + */ + s->prev_length = s->match_length, s->prev_match = s->match_start; + s->match_length = MIN_MATCH-1; + + if (hash_head != NIL && s->prev_length < s->max_lazy_match && + s->strstart - hash_head <= MAX_DIST(s)) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s->match_length = longest_match (s, hash_head); + /* longest_match() sets match_start */ + + if (s->match_length <= 5 && (s->strategy == Z_FILTERED +#if TOO_FAR <= 32767 + || (s->match_length == MIN_MATCH && + s->strstart - s->match_start > TOO_FAR) +#endif + )) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s->match_length = MIN_MATCH-1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) { + uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + check_match(s, s->strstart-1, s->prev_match, s->prev_length); + + _tr_tally_dist(s, s->strstart -1 - s->prev_match, + s->prev_length - MIN_MATCH, bflush); + + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s->lookahead -= s->prev_length-1; + s->prev_length -= 2; + do { + if (++s->strstart <= max_insert) { + INSERT_STRING(s, s->strstart, hash_head); + } + } while (--s->prev_length != 0); + s->match_available = 0; + s->match_length = MIN_MATCH-1; + s->strstart++; + + if (bflush) FLUSH_BLOCK(s, 0); + + } else if (s->match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + Tracevv((stderr,"%c", s->window[s->strstart-1])); + _tr_tally_lit(s, s->window[s->strstart-1], bflush); + if (bflush) { + FLUSH_BLOCK_ONLY(s, 0); + } + s->strstart++; + s->lookahead--; + if (s->strm->avail_out == 0) return need_more; + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s->match_available = 1; + s->strstart++; + s->lookahead--; + } + } + Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s->match_available) { + Tracevv((stderr,"%c", s->window[s->strstart-1])); + _tr_tally_lit(s, s->window[s->strstart-1], bflush); + s->match_available = 0; + } + s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; +} +#endif /* FASTEST */ + +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +local block_state deflate_rle(s, flush) + deflate_state *s; + int flush; +{ + int bflush; /* set if current block must be flushed */ + uInt prev; /* byte at distance one to match */ + Bytef *scan, *strend; /* scan goes up to strend for length of run */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s->lookahead <= MAX_MATCH) { + fill_window(s); + if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s->match_length = 0; + if (s->lookahead >= MIN_MATCH && s->strstart > 0) { + scan = s->window + s->strstart - 1; + prev = *scan; + if (prev == *++scan && prev == *++scan && prev == *++scan) { + strend = s->window + s->strstart + MAX_MATCH; + do { + } while (prev == *++scan && prev == *++scan && + prev == *++scan && prev == *++scan && + prev == *++scan && prev == *++scan && + prev == *++scan && prev == *++scan && + scan < strend); + s->match_length = MAX_MATCH - (uInt)(strend - scan); + if (s->match_length > s->lookahead) + s->match_length = s->lookahead; + } + Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s->match_length >= MIN_MATCH) { + check_match(s, s->strstart, s->strstart - 1, s->match_length); + + _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush); + + s->lookahead -= s->match_length; + s->strstart += s->match_length; + s->match_length = 0; + } else { + /* No match, output a literal byte */ + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + } + if (bflush) FLUSH_BLOCK(s, 0); + } + s->insert = 0; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; +} + +/* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +local block_state deflate_huff(s, flush) + deflate_state *s; + int flush; +{ + int bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s->lookahead == 0) { + fill_window(s); + if (s->lookahead == 0) { + if (flush == Z_NO_FLUSH) + return need_more; + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s->match_length = 0; + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + if (bflush) FLUSH_BLOCK(s, 0); + } + s->insert = 0; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; +} diff --git a/Source/Libraries/zlib/infback.c b/Source/Libraries/zlib/infback.c new file mode 100644 index 0000000..59679ec --- /dev/null +++ b/Source/Libraries/zlib/infback.c @@ -0,0 +1,640 @@ +/* infback.c -- inflate using a call-back interface + * Copyright (C) 1995-2016 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + This code is largely copied from inflate.c. Normally either infback.o or + inflate.o would be linked into an application--not both. The interface + with inffast.c is retained so that optimized assembler-coded versions of + inflate_fast() can be used with either inflate.c or infback.c. + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "inffast.h" + +/* function prototypes */ +local void fixedtables OF((struct inflate_state FAR *state)); + +/* + strm provides memory allocation functions in zalloc and zfree, or + Z_NULL to use the library memory allocation functions. + + windowBits is in the range 8..15, and window is a user-supplied + window and output buffer that is 2**windowBits bytes. + */ +int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size) +z_streamp strm; +int windowBits; +unsigned char FAR *window; +const char *version; +int stream_size; +{ + struct inflate_state FAR *state; + + if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || + stream_size != (int)(sizeof(z_stream))) + return Z_VERSION_ERROR; + if (strm == Z_NULL || window == Z_NULL || + windowBits < 8 || windowBits > 15) + return Z_STREAM_ERROR; + strm->msg = Z_NULL; /* in case we return an error */ + if (strm->zalloc == (alloc_func)0) { +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; +#endif + } + if (strm->zfree == (free_func)0) +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zfree = zcfree; +#endif + state = (struct inflate_state FAR *)ZALLOC(strm, 1, + sizeof(struct inflate_state)); + if (state == Z_NULL) return Z_MEM_ERROR; + Tracev((stderr, "inflate: allocated\n")); + strm->state = (struct internal_state FAR *)state; + state->dmax = 32768U; + state->wbits = (uInt)windowBits; + state->wsize = 1U << windowBits; + state->window = window; + state->wnext = 0; + state->whave = 0; + return Z_OK; +} + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +local void fixedtables(state) +struct inflate_state FAR *state; +{ +#ifdef BUILDFIXED + static int virgin = 1; + static code *lenfix, *distfix; + static code fixed[544]; + + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + unsigned sym, bits; + static code *next; + + /* literal/length table */ + sym = 0; + while (sym < 144) state->lens[sym++] = 8; + while (sym < 256) state->lens[sym++] = 9; + while (sym < 280) state->lens[sym++] = 7; + while (sym < 288) state->lens[sym++] = 8; + next = fixed; + lenfix = next; + bits = 9; + inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); + + /* distance table */ + sym = 0; + while (sym < 32) state->lens[sym++] = 5; + distfix = next; + bits = 5; + inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); + + /* do this just once */ + virgin = 0; + } +#else /* !BUILDFIXED */ +# include "inffixed.h" +#endif /* BUILDFIXED */ + state->lencode = lenfix; + state->lenbits = 9; + state->distcode = distfix; + state->distbits = 5; +} + +/* Macros for inflateBack(): */ + +/* Load returned state from inflate_fast() */ +#define LOAD() \ + do { \ + put = strm->next_out; \ + left = strm->avail_out; \ + next = strm->next_in; \ + have = strm->avail_in; \ + hold = state->hold; \ + bits = state->bits; \ + } while (0) + +/* Set state from registers for inflate_fast() */ +#define RESTORE() \ + do { \ + strm->next_out = put; \ + strm->avail_out = left; \ + strm->next_in = next; \ + strm->avail_in = have; \ + state->hold = hold; \ + state->bits = bits; \ + } while (0) + +/* Clear the input bit accumulator */ +#define INITBITS() \ + do { \ + hold = 0; \ + bits = 0; \ + } while (0) + +/* Assure that some input is available. If input is requested, but denied, + then return a Z_BUF_ERROR from inflateBack(). */ +#define PULL() \ + do { \ + if (have == 0) { \ + have = in(in_desc, &next); \ + if (have == 0) { \ + next = Z_NULL; \ + ret = Z_BUF_ERROR; \ + goto inf_leave; \ + } \ + } \ + } while (0) + +/* Get a byte of input into the bit accumulator, or return from inflateBack() + with an error if there is no input available. */ +#define PULLBYTE() \ + do { \ + PULL(); \ + have--; \ + hold += (unsigned long)(*next++) << bits; \ + bits += 8; \ + } while (0) + +/* Assure that there are at least n bits in the bit accumulator. If there is + not enough available input to do that, then return from inflateBack() with + an error. */ +#define NEEDBITS(n) \ + do { \ + while (bits < (unsigned)(n)) \ + PULLBYTE(); \ + } while (0) + +/* Return the low n bits of the bit accumulator (n < 16) */ +#define BITS(n) \ + ((unsigned)hold & ((1U << (n)) - 1)) + +/* Remove n bits from the bit accumulator */ +#define DROPBITS(n) \ + do { \ + hold >>= (n); \ + bits -= (unsigned)(n); \ + } while (0) + +/* Remove zero to seven bits as needed to go to a byte boundary */ +#define BYTEBITS() \ + do { \ + hold >>= bits & 7; \ + bits -= bits & 7; \ + } while (0) + +/* Assure that some output space is available, by writing out the window + if it's full. If the write fails, return from inflateBack() with a + Z_BUF_ERROR. */ +#define ROOM() \ + do { \ + if (left == 0) { \ + put = state->window; \ + left = state->wsize; \ + state->whave = left; \ + if (out(out_desc, put, left)) { \ + ret = Z_BUF_ERROR; \ + goto inf_leave; \ + } \ + } \ + } while (0) + +/* + strm provides the memory allocation functions and window buffer on input, + and provides information on the unused input on return. For Z_DATA_ERROR + returns, strm will also provide an error message. + + in() and out() are the call-back input and output functions. When + inflateBack() needs more input, it calls in(). When inflateBack() has + filled the window with output, or when it completes with data in the + window, it calls out() to write out the data. The application must not + change the provided input until in() is called again or inflateBack() + returns. The application must not change the window/output buffer until + inflateBack() returns. + + in() and out() are called with a descriptor parameter provided in the + inflateBack() call. This parameter can be a structure that provides the + information required to do the read or write, as well as accumulated + information on the input and output such as totals and check values. + + in() should return zero on failure. out() should return non-zero on + failure. If either in() or out() fails, than inflateBack() returns a + Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it + was in() or out() that caused in the error. Otherwise, inflateBack() + returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format + error, or Z_MEM_ERROR if it could not allocate memory for the state. + inflateBack() can also return Z_STREAM_ERROR if the input parameters + are not correct, i.e. strm is Z_NULL or the state was not initialized. + */ +int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc) +z_streamp strm; +in_func in; +void FAR *in_desc; +out_func out; +void FAR *out_desc; +{ + struct inflate_state FAR *state; + z_const unsigned char FAR *next; /* next input */ + unsigned char FAR *put; /* next output */ + unsigned have, left; /* available input and output */ + unsigned long hold; /* bit buffer */ + unsigned bits; /* bits in bit buffer */ + unsigned copy; /* number of stored or match bytes to copy */ + unsigned char FAR *from; /* where to copy match bytes from */ + code here; /* current decoding table entry */ + code last; /* parent table entry */ + unsigned len; /* length to copy for repeats, bits to drop */ + int ret; /* return code */ + static const unsigned short order[19] = /* permutation of code lengths */ + {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + + /* Check that the strm exists and that the state was initialized */ + if (strm == Z_NULL || strm->state == Z_NULL) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + + /* Reset the state */ + strm->msg = Z_NULL; + state->mode = TYPE; + state->last = 0; + state->whave = 0; + next = strm->next_in; + have = next != Z_NULL ? strm->avail_in : 0; + hold = 0; + bits = 0; + put = state->window; + left = state->wsize; + + /* Inflate until end of block marked as last */ + for (;;) + switch (state->mode) { + case TYPE: + /* determine and dispatch block type */ + if (state->last) { + BYTEBITS(); + state->mode = DONE; + break; + } + NEEDBITS(3); + state->last = BITS(1); + DROPBITS(1); + switch (BITS(2)) { + case 0: /* stored block */ + Tracev((stderr, "inflate: stored block%s\n", + state->last ? " (last)" : "")); + state->mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + Tracev((stderr, "inflate: fixed codes block%s\n", + state->last ? " (last)" : "")); + state->mode = LEN; /* decode codes */ + break; + case 2: /* dynamic block */ + Tracev((stderr, "inflate: dynamic codes block%s\n", + state->last ? " (last)" : "")); + state->mode = TABLE; + break; + case 3: + strm->msg = (char *)"invalid block type"; + state->mode = BAD; + } + DROPBITS(2); + break; + + case STORED: + /* get and verify stored block length */ + BYTEBITS(); /* go to byte boundary */ + NEEDBITS(32); + if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { + strm->msg = (char *)"invalid stored block lengths"; + state->mode = BAD; + break; + } + state->length = (unsigned)hold & 0xffff; + Tracev((stderr, "inflate: stored length %u\n", + state->length)); + INITBITS(); + + /* copy stored block from input to output */ + while (state->length != 0) { + copy = state->length; + PULL(); + ROOM(); + if (copy > have) copy = have; + if (copy > left) copy = left; + zmemcpy(put, next, copy); + have -= copy; + next += copy; + left -= copy; + put += copy; + state->length -= copy; + } + Tracev((stderr, "inflate: stored end\n")); + state->mode = TYPE; + break; + + case TABLE: + /* get dynamic table entries descriptor */ + NEEDBITS(14); + state->nlen = BITS(5) + 257; + DROPBITS(5); + state->ndist = BITS(5) + 1; + DROPBITS(5); + state->ncode = BITS(4) + 4; + DROPBITS(4); +#ifndef PKZIP_BUG_WORKAROUND + if (state->nlen > 286 || state->ndist > 30) { + strm->msg = (char *)"too many length or distance symbols"; + state->mode = BAD; + break; + } +#endif + Tracev((stderr, "inflate: table sizes ok\n")); + + /* get code length code lengths (not a typo) */ + state->have = 0; + while (state->have < state->ncode) { + NEEDBITS(3); + state->lens[order[state->have++]] = (unsigned short)BITS(3); + DROPBITS(3); + } + while (state->have < 19) + state->lens[order[state->have++]] = 0; + state->next = state->codes; + state->lencode = (code const FAR *)(state->next); + state->lenbits = 7; + ret = inflate_table(CODES, state->lens, 19, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid code lengths set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: code lengths ok\n")); + + /* get length and distance code code lengths */ + state->have = 0; + while (state->have < state->nlen + state->ndist) { + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.val < 16) { + DROPBITS(here.bits); + state->lens[state->have++] = here.val; + } + else { + if (here.val == 16) { + NEEDBITS(here.bits + 2); + DROPBITS(here.bits); + if (state->have == 0) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + len = (unsigned)(state->lens[state->have - 1]); + copy = 3 + BITS(2); + DROPBITS(2); + } + else if (here.val == 17) { + NEEDBITS(here.bits + 3); + DROPBITS(here.bits); + len = 0; + copy = 3 + BITS(3); + DROPBITS(3); + } + else { + NEEDBITS(here.bits + 7); + DROPBITS(here.bits); + len = 0; + copy = 11 + BITS(7); + DROPBITS(7); + } + if (state->have + copy > state->nlen + state->ndist) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + while (copy--) + state->lens[state->have++] = (unsigned short)len; + } + } + + /* handle error breaks in while */ + if (state->mode == BAD) break; + + /* check for end-of-block code (better have one) */ + if (state->lens[256] == 0) { + strm->msg = (char *)"invalid code -- missing end-of-block"; + state->mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state->next = state->codes; + state->lencode = (code const FAR *)(state->next); + state->lenbits = 9; + ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid literal/lengths set"; + state->mode = BAD; + break; + } + state->distcode = (code const FAR *)(state->next); + state->distbits = 6; + ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, + &(state->next), &(state->distbits), state->work); + if (ret) { + strm->msg = (char *)"invalid distances set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: codes ok\n")); + state->mode = LEN; + + case LEN: + /* use inflate_fast() if we have enough input and output */ + if (have >= 6 && left >= 258) { + RESTORE(); + if (state->whave < state->wsize) + state->whave = state->wsize - left; + inflate_fast(strm, state->wsize); + LOAD(); + break; + } + + /* get a literal, length, or end-of-block code */ + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.op && (here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->lencode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(here.bits); + state->length = (unsigned)here.val; + + /* process literal */ + if (here.op == 0) { + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", here.val)); + ROOM(); + *put++ = (unsigned char)(state->length); + left--; + state->mode = LEN; + break; + } + + /* process end of block */ + if (here.op & 32) { + Tracevv((stderr, "inflate: end of block\n")); + state->mode = TYPE; + break; + } + + /* invalid code */ + if (here.op & 64) { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + + /* length code -- get extra bits, if any */ + state->extra = (unsigned)(here.op) & 15; + if (state->extra != 0) { + NEEDBITS(state->extra); + state->length += BITS(state->extra); + DROPBITS(state->extra); + } + Tracevv((stderr, "inflate: length %u\n", state->length)); + + /* get distance code */ + for (;;) { + here = state->distcode[BITS(state->distbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if ((here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->distcode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(here.bits); + if (here.op & 64) { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + state->offset = (unsigned)here.val; + + /* get distance extra bits, if any */ + state->extra = (unsigned)(here.op) & 15; + if (state->extra != 0) { + NEEDBITS(state->extra); + state->offset += BITS(state->extra); + DROPBITS(state->extra); + } + if (state->offset > state->wsize - (state->whave < state->wsize ? + left : 0)) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } + Tracevv((stderr, "inflate: distance %u\n", state->offset)); + + /* copy match from window to output */ + do { + ROOM(); + copy = state->wsize - state->offset; + if (copy < left) { + from = put + copy; + copy = left - copy; + } + else { + from = put - state->offset; + copy = left; + } + if (copy > state->length) copy = state->length; + state->length -= copy; + left -= copy; + do { + *put++ = *from++; + } while (--copy); + } while (state->length != 0); + break; + + case DONE: + /* inflate stream terminated properly -- write leftover output */ + ret = Z_STREAM_END; + if (left < state->wsize) { + if (out(out_desc, state->window, state->wsize - left)) + ret = Z_BUF_ERROR; + } + goto inf_leave; + + case BAD: + ret = Z_DATA_ERROR; + goto inf_leave; + + default: /* can't happen, but makes compilers happy */ + ret = Z_STREAM_ERROR; + goto inf_leave; + } + + /* Return unused input */ + inf_leave: + strm->next_in = next; + strm->avail_in = have; + return ret; +} + +int ZEXPORT inflateBackEnd(strm) +z_streamp strm; +{ + if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) + return Z_STREAM_ERROR; + ZFREE(strm, strm->state); + strm->state = Z_NULL; + Tracev((stderr, "inflate: end\n")); + return Z_OK; +} diff --git a/Source/Libraries/zlib/inffast.c b/Source/Libraries/zlib/inffast.c new file mode 100644 index 0000000..0dbd1db --- /dev/null +++ b/Source/Libraries/zlib/inffast.c @@ -0,0 +1,323 @@ +/* inffast.c -- fast decoding + * Copyright (C) 1995-2017 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "inffast.h" + +#ifdef ASMINF +# pragma message("Assembler code may have bugs -- use at your own risk") +#else + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state->mode == LEN + strm->avail_in >= 6 + strm->avail_out >= 258 + start >= strm->avail_out + state->bits < 8 + + On return, state->mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm->avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm->avail_out >= 258 for each loop to avoid checking for + output space. + */ +void ZLIB_INTERNAL inflate_fast(strm, start) +z_streamp strm; +unsigned start; /* inflate()'s starting value for strm->avail_out */ +{ + struct inflate_state FAR *state; + z_const unsigned char FAR *in; /* local strm->next_in */ + z_const unsigned char FAR *last; /* have enough input while in < last */ + unsigned char FAR *out; /* local strm->next_out */ + unsigned char FAR *beg; /* inflate()'s initial strm->next_out */ + unsigned char FAR *end; /* while out < end, enough space available */ +#ifdef INFLATE_STRICT + unsigned dmax; /* maximum distance from zlib header */ +#endif + unsigned wsize; /* window size or zero if not using window */ + unsigned whave; /* valid bytes in the window */ + unsigned wnext; /* window write index */ + unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */ + unsigned long hold; /* local strm->hold */ + unsigned bits; /* local strm->bits */ + code const FAR *lcode; /* local strm->lencode */ + code const FAR *dcode; /* local strm->distcode */ + unsigned lmask; /* mask for first level of length codes */ + unsigned dmask; /* mask for first level of distance codes */ + code here; /* retrieved table entry */ + unsigned op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + unsigned len; /* match length, unused bytes */ + unsigned dist; /* match distance */ + unsigned char FAR *from; /* where to copy match from */ + + /* copy state to local variables */ + state = (struct inflate_state FAR *)strm->state; + in = strm->next_in; + last = in + (strm->avail_in - 5); + out = strm->next_out; + beg = out - (start - strm->avail_out); + end = out + (strm->avail_out - 257); +#ifdef INFLATE_STRICT + dmax = state->dmax; +#endif + wsize = state->wsize; + whave = state->whave; + wnext = state->wnext; + window = state->window; + hold = state->hold; + bits = state->bits; + lcode = state->lencode; + dcode = state->distcode; + lmask = (1U << state->lenbits) - 1; + dmask = (1U << state->distbits) - 1; + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + do { + if (bits < 15) { + hold += (unsigned long)(*in++) << bits; + bits += 8; + hold += (unsigned long)(*in++) << bits; + bits += 8; + } + here = lcode[hold & lmask]; + dolen: + op = (unsigned)(here.bits); + hold >>= op; + bits -= op; + op = (unsigned)(here.op); + if (op == 0) { /* literal */ + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", here.val)); + *out++ = (unsigned char)(here.val); + } + else if (op & 16) { /* length base */ + len = (unsigned)(here.val); + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += (unsigned long)(*in++) << bits; + bits += 8; + } + len += (unsigned)hold & ((1U << op) - 1); + hold >>= op; + bits -= op; + } + Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += (unsigned long)(*in++) << bits; + bits += 8; + hold += (unsigned long)(*in++) << bits; + bits += 8; + } + here = dcode[hold & dmask]; + dodist: + op = (unsigned)(here.bits); + hold >>= op; + bits -= op; + op = (unsigned)(here.op); + if (op & 16) { /* distance base */ + dist = (unsigned)(here.val); + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += (unsigned long)(*in++) << bits; + bits += 8; + if (bits < op) { + hold += (unsigned long)(*in++) << bits; + bits += 8; + } + } + dist += (unsigned)hold & ((1U << op) - 1); +#ifdef INFLATE_STRICT + if (dist > dmax) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#endif + hold >>= op; + bits -= op; + Tracevv((stderr, "inflate: distance %u\n", dist)); + op = (unsigned)(out - beg); /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state->sane) { + strm->msg = + (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + if (len <= op - whave) { + do { + *out++ = 0; + } while (--len); + continue; + } + len -= op - whave; + do { + *out++ = 0; + } while (--op > whave); + if (op == 0) { + from = out - dist; + do { + *out++ = *from++; + } while (--len); + continue; + } +#endif + } + from = window; + if (wnext == 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + *out++ = *from++; + } while (--op); + from = out - dist; /* rest from output */ + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + *out++ = *from++; + } while (--op); + from = window; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + *out++ = *from++; + } while (--op); + from = out - dist; /* rest from output */ + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + *out++ = *from++; + } while (--op); + from = out - dist; /* rest from output */ + } + } + while (len > 2) { + *out++ = *from++; + *out++ = *from++; + *out++ = *from++; + len -= 3; + } + if (len) { + *out++ = *from++; + if (len > 1) + *out++ = *from++; + } + } + else { + from = out - dist; /* copy direct from output */ + do { /* minimum length is three */ + *out++ = *from++; + *out++ = *from++; + *out++ = *from++; + len -= 3; + } while (len > 2); + if (len) { + *out++ = *from++; + if (len > 1) + *out++ = *from++; + } + } + } + else if ((op & 64) == 0) { /* 2nd level distance code */ + here = dcode[here.val + (hold & ((1U << op) - 1))]; + goto dodist; + } + else { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + } + else if ((op & 64) == 0) { /* 2nd level length code */ + here = lcode[here.val + (hold & ((1U << op) - 1))]; + goto dolen; + } + else if (op & 32) { /* end-of-block */ + Tracevv((stderr, "inflate: end of block\n")); + state->mode = TYPE; + break; + } + else { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + } while (in < last && out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + in -= len; + bits -= len << 3; + hold &= (1U << bits) - 1; + + /* update state and return */ + strm->next_in = in; + strm->next_out = out; + strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last)); + strm->avail_out = (unsigned)(out < end ? + 257 + (end - out) : 257 - (out - end)); + state->hold = hold; + state->bits = bits; + return; +} + +/* + inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe): + - Using bit fields for code structure + - Different op definition to avoid & for extra bits (do & for table bits) + - Three separate decoding do-loops for direct, window, and wnext == 0 + - Special case for distance > 1 copies to do overlapped load and store copy + - Explicit branch predictions (based on measured branch probabilities) + - Deferring match copy and interspersed it with decoding subsequent codes + - Swapping literal/length else + - Swapping window/direct else + - Larger unrolled copy loops (three is about right) + - Moving len -= 3 statement into middle of loop + */ + +#endif /* !ASMINF */ diff --git a/Source/Libraries/zlib/inflate.c b/Source/Libraries/zlib/inflate.c new file mode 100644 index 0000000..ac333e8 --- /dev/null +++ b/Source/Libraries/zlib/inflate.c @@ -0,0 +1,1561 @@ +/* inflate.c -- zlib decompression + * Copyright (C) 1995-2016 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * Change history: + * + * 1.2.beta0 24 Nov 2002 + * - First version -- complete rewrite of inflate to simplify code, avoid + * creation of window when not needed, minimize use of window when it is + * needed, make inffast.c even faster, implement gzip decoding, and to + * improve code readability and style over the previous zlib inflate code + * + * 1.2.beta1 25 Nov 2002 + * - Use pointers for available input and output checking in inffast.c + * - Remove input and output counters in inffast.c + * - Change inffast.c entry and loop from avail_in >= 7 to >= 6 + * - Remove unnecessary second byte pull from length extra in inffast.c + * - Unroll direct copy to three copies per loop in inffast.c + * + * 1.2.beta2 4 Dec 2002 + * - Change external routine names to reduce potential conflicts + * - Correct filename to inffixed.h for fixed tables in inflate.c + * - Make hbuf[] unsigned char to match parameter type in inflate.c + * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset) + * to avoid negation problem on Alphas (64 bit) in inflate.c + * + * 1.2.beta3 22 Dec 2002 + * - Add comments on state->bits assertion in inffast.c + * - Add comments on op field in inftrees.h + * - Fix bug in reuse of allocated window after inflateReset() + * - Remove bit fields--back to byte structure for speed + * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths + * - Change post-increments to pre-increments in inflate_fast(), PPC biased? + * - Add compile time option, POSTINC, to use post-increments instead (Intel?) + * - Make MATCH copy in inflate() much faster for when inflate_fast() not used + * - Use local copies of stream next and avail values, as well as local bit + * buffer and bit count in inflate()--for speed when inflate_fast() not used + * + * 1.2.beta4 1 Jan 2003 + * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings + * - Move a comment on output buffer sizes from inffast.c to inflate.c + * - Add comments in inffast.c to introduce the inflate_fast() routine + * - Rearrange window copies in inflate_fast() for speed and simplification + * - Unroll last copy for window match in inflate_fast() + * - Use local copies of window variables in inflate_fast() for speed + * - Pull out common wnext == 0 case for speed in inflate_fast() + * - Make op and len in inflate_fast() unsigned for consistency + * - Add FAR to lcode and dcode declarations in inflate_fast() + * - Simplified bad distance check in inflate_fast() + * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new + * source file infback.c to provide a call-back interface to inflate for + * programs like gzip and unzip -- uses window as output buffer to avoid + * window copying + * + * 1.2.beta5 1 Jan 2003 + * - Improved inflateBack() interface to allow the caller to provide initial + * input in strm. + * - Fixed stored blocks bug in inflateBack() + * + * 1.2.beta6 4 Jan 2003 + * - Added comments in inffast.c on effectiveness of POSTINC + * - Typecasting all around to reduce compiler warnings + * - Changed loops from while (1) or do {} while (1) to for (;;), again to + * make compilers happy + * - Changed type of window in inflateBackInit() to unsigned char * + * + * 1.2.beta7 27 Jan 2003 + * - Changed many types to unsigned or unsigned short to avoid warnings + * - Added inflateCopy() function + * + * 1.2.0 9 Mar 2003 + * - Changed inflateBack() interface to provide separate opaque descriptors + * for the in() and out() functions + * - Changed inflateBack() argument and in_func typedef to swap the length + * and buffer address return values for the input function + * - Check next_in and next_out for Z_NULL on entry to inflate() + * + * The history for versions after 1.2.0 are in ChangeLog in zlib distribution. + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "inffast.h" + +#ifdef MAKEFIXED +# ifndef BUILDFIXED +# define BUILDFIXED +# endif +#endif + +/* function prototypes */ +local int inflateStateCheck OF((z_streamp strm)); +local void fixedtables OF((struct inflate_state FAR *state)); +local int updatewindow OF((z_streamp strm, const unsigned char FAR *end, + unsigned copy)); +#ifdef BUILDFIXED + void makefixed OF((void)); +#endif +local unsigned syncsearch OF((unsigned FAR *have, const unsigned char FAR *buf, + unsigned len)); + +local int inflateStateCheck(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + if (strm == Z_NULL || + strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) + return 1; + state = (struct inflate_state FAR *)strm->state; + if (state == Z_NULL || state->strm != strm || + state->mode < HEAD || state->mode > SYNC) + return 1; + return 0; +} + +int ZEXPORT inflateResetKeep(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + strm->total_in = strm->total_out = state->total = 0; + strm->msg = Z_NULL; + if (state->wrap) /* to support ill-conceived Java test suite */ + strm->adler = state->wrap & 1; + state->mode = HEAD; + state->last = 0; + state->havedict = 0; + state->dmax = 32768U; + state->head = Z_NULL; + state->hold = 0; + state->bits = 0; + state->lencode = state->distcode = state->next = state->codes; + state->sane = 1; + state->back = -1; + Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +int ZEXPORT inflateReset(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + state->wsize = 0; + state->whave = 0; + state->wnext = 0; + return inflateResetKeep(strm); +} + +int ZEXPORT inflateReset2(strm, windowBits) +z_streamp strm; +int windowBits; +{ + int wrap; + struct inflate_state FAR *state; + + /* get the state */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 5; +#ifdef GUNZIP + if (windowBits < 48) + windowBits &= 15; +#endif + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) + return Z_STREAM_ERROR; + if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) { + ZFREE(strm, state->window); + state->window = Z_NULL; + } + + /* update state and reset the rest of it */ + state->wrap = wrap; + state->wbits = (unsigned)windowBits; + return inflateReset(strm); +} + +int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size) +z_streamp strm; +int windowBits; +const char *version; +int stream_size; +{ + int ret; + struct inflate_state FAR *state; + + if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || + stream_size != (int)(sizeof(z_stream))) + return Z_VERSION_ERROR; + if (strm == Z_NULL) return Z_STREAM_ERROR; + strm->msg = Z_NULL; /* in case we return an error */ + if (strm->zalloc == (alloc_func)0) { +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; +#endif + } + if (strm->zfree == (free_func)0) +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zfree = zcfree; +#endif + state = (struct inflate_state FAR *) + ZALLOC(strm, 1, sizeof(struct inflate_state)); + if (state == Z_NULL) return Z_MEM_ERROR; + Tracev((stderr, "inflate: allocated\n")); + strm->state = (struct internal_state FAR *)state; + state->strm = strm; + state->window = Z_NULL; + state->mode = HEAD; /* to pass state test in inflateReset2() */ + ret = inflateReset2(strm, windowBits); + if (ret != Z_OK) { + ZFREE(strm, state); + strm->state = Z_NULL; + } + return ret; +} + +int ZEXPORT inflateInit_(strm, version, stream_size) +z_streamp strm; +const char *version; +int stream_size; +{ + return inflateInit2_(strm, DEF_WBITS, version, stream_size); +} + +int ZEXPORT inflatePrime(strm, bits, value) +z_streamp strm; +int bits; +int value; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (bits < 0) { + state->hold = 0; + state->bits = 0; + return Z_OK; + } + if (bits > 16 || state->bits + (uInt)bits > 32) return Z_STREAM_ERROR; + value &= (1L << bits) - 1; + state->hold += (unsigned)value << state->bits; + state->bits += (uInt)bits; + return Z_OK; +} + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +local void fixedtables(state) +struct inflate_state FAR *state; +{ +#ifdef BUILDFIXED + static int virgin = 1; + static code *lenfix, *distfix; + static code fixed[544]; + + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + unsigned sym, bits; + static code *next; + + /* literal/length table */ + sym = 0; + while (sym < 144) state->lens[sym++] = 8; + while (sym < 256) state->lens[sym++] = 9; + while (sym < 280) state->lens[sym++] = 7; + while (sym < 288) state->lens[sym++] = 8; + next = fixed; + lenfix = next; + bits = 9; + inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); + + /* distance table */ + sym = 0; + while (sym < 32) state->lens[sym++] = 5; + distfix = next; + bits = 5; + inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); + + /* do this just once */ + virgin = 0; + } +#else /* !BUILDFIXED */ +# include "inffixed.h" +#endif /* BUILDFIXED */ + state->lencode = lenfix; + state->lenbits = 9; + state->distcode = distfix; + state->distbits = 5; +} + +#ifdef MAKEFIXED +#include + +/* + Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also + defines BUILDFIXED, so the tables are built on the fly. makefixed() writes + those tables to stdout, which would be piped to inffixed.h. A small program + can simply call makefixed to do this: + + void makefixed(void); + + int main(void) + { + makefixed(); + return 0; + } + + Then that can be linked with zlib built with MAKEFIXED defined and run: + + a.out > inffixed.h + */ +void makefixed() +{ + unsigned low, size; + struct inflate_state state; + + fixedtables(&state); + puts(" /* inffixed.h -- table for decoding fixed codes"); + puts(" * Generated automatically by makefixed()."); + puts(" */"); + puts(""); + puts(" /* WARNING: this file should *not* be used by applications."); + puts(" It is part of the implementation of this library and is"); + puts(" subject to change. Applications should only use zlib.h."); + puts(" */"); + puts(""); + size = 1U << 9; + printf(" static const code lenfix[%u] = {", size); + low = 0; + for (;;) { + if ((low % 7) == 0) printf("\n "); + printf("{%u,%u,%d}", (low & 127) == 99 ? 64 : state.lencode[low].op, + state.lencode[low].bits, state.lencode[low].val); + if (++low == size) break; + putchar(','); + } + puts("\n };"); + size = 1U << 5; + printf("\n static const code distfix[%u] = {", size); + low = 0; + for (;;) { + if ((low % 6) == 0) printf("\n "); + printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits, + state.distcode[low].val); + if (++low == size) break; + putchar(','); + } + puts("\n };"); +} +#endif /* MAKEFIXED */ + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +local int updatewindow(strm, end, copy) +z_streamp strm; +const Bytef *end; +unsigned copy; +{ + struct inflate_state FAR *state; + unsigned dist; + + state = (struct inflate_state FAR *)strm->state; + + /* if it hasn't been done already, allocate space for the window */ + if (state->window == Z_NULL) { + state->window = (unsigned char FAR *) + ZALLOC(strm, 1U << state->wbits, + sizeof(unsigned char)); + if (state->window == Z_NULL) return 1; + } + + /* if window not in use yet, initialize */ + if (state->wsize == 0) { + state->wsize = 1U << state->wbits; + state->wnext = 0; + state->whave = 0; + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state->wsize) { + zmemcpy(state->window, end - state->wsize, state->wsize); + state->wnext = 0; + state->whave = state->wsize; + } + else { + dist = state->wsize - state->wnext; + if (dist > copy) dist = copy; + zmemcpy(state->window + state->wnext, end - copy, dist); + copy -= dist; + if (copy) { + zmemcpy(state->window, end - copy, copy); + state->wnext = copy; + state->whave = state->wsize; + } + else { + state->wnext += dist; + if (state->wnext == state->wsize) state->wnext = 0; + if (state->whave < state->wsize) state->whave += dist; + } + } + return 0; +} + +/* Macros for inflate(): */ + +/* check function to use adler32() for zlib or crc32() for gzip */ +#ifdef GUNZIP +# define UPDATE(check, buf, len) \ + (state->flags ? crc32(check, buf, len) : adler32(check, buf, len)) +#else +# define UPDATE(check, buf, len) adler32(check, buf, len) +#endif + +/* check macros for header crc */ +#ifdef GUNZIP +# define CRC2(check, word) \ + do { \ + hbuf[0] = (unsigned char)(word); \ + hbuf[1] = (unsigned char)((word) >> 8); \ + check = crc32(check, hbuf, 2); \ + } while (0) + +# define CRC4(check, word) \ + do { \ + hbuf[0] = (unsigned char)(word); \ + hbuf[1] = (unsigned char)((word) >> 8); \ + hbuf[2] = (unsigned char)((word) >> 16); \ + hbuf[3] = (unsigned char)((word) >> 24); \ + check = crc32(check, hbuf, 4); \ + } while (0) +#endif + +/* Load registers with state in inflate() for speed */ +#define LOAD() \ + do { \ + put = strm->next_out; \ + left = strm->avail_out; \ + next = strm->next_in; \ + have = strm->avail_in; \ + hold = state->hold; \ + bits = state->bits; \ + } while (0) + +/* Restore state from registers in inflate() */ +#define RESTORE() \ + do { \ + strm->next_out = put; \ + strm->avail_out = left; \ + strm->next_in = next; \ + strm->avail_in = have; \ + state->hold = hold; \ + state->bits = bits; \ + } while (0) + +/* Clear the input bit accumulator */ +#define INITBITS() \ + do { \ + hold = 0; \ + bits = 0; \ + } while (0) + +/* Get a byte of input into the bit accumulator, or return from inflate() + if there is no input available. */ +#define PULLBYTE() \ + do { \ + if (have == 0) goto inf_leave; \ + have--; \ + hold += (unsigned long)(*next++) << bits; \ + bits += 8; \ + } while (0) + +/* Assure that there are at least n bits in the bit accumulator. If there is + not enough available input to do that, then return from inflate(). */ +#define NEEDBITS(n) \ + do { \ + while (bits < (unsigned)(n)) \ + PULLBYTE(); \ + } while (0) + +/* Return the low n bits of the bit accumulator (n < 16) */ +#define BITS(n) \ + ((unsigned)hold & ((1U << (n)) - 1)) + +/* Remove n bits from the bit accumulator */ +#define DROPBITS(n) \ + do { \ + hold >>= (n); \ + bits -= (unsigned)(n); \ + } while (0) + +/* Remove zero to seven bits as needed to go to a byte boundary */ +#define BYTEBITS() \ + do { \ + hold >>= bits & 7; \ + bits -= bits & 7; \ + } while (0) + +/* + inflate() uses a state machine to process as much input data and generate as + much output data as possible before returning. The state machine is + structured roughly as follows: + + for (;;) switch (state) { + ... + case STATEn: + if (not enough input data or output space to make progress) + return; + ... make progress ... + state = STATEm; + break; + ... + } + + so when inflate() is called again, the same case is attempted again, and + if the appropriate resources are provided, the machine proceeds to the + next state. The NEEDBITS() macro is usually the way the state evaluates + whether it can proceed or should return. NEEDBITS() does the return if + the requested bits are not available. The typical use of the BITS macros + is: + + NEEDBITS(n); + ... do something with BITS(n) ... + DROPBITS(n); + + where NEEDBITS(n) either returns from inflate() if there isn't enough + input left to load n bits into the accumulator, or it continues. BITS(n) + gives the low n bits in the accumulator. When done, DROPBITS(n) drops + the low n bits off the accumulator. INITBITS() clears the accumulator + and sets the number of available bits to zero. BYTEBITS() discards just + enough bits to put the accumulator on a byte boundary. After BYTEBITS() + and a NEEDBITS(8), then BITS(8) would return the next byte in the stream. + + NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return + if there is no input available. The decoding of variable length codes uses + PULLBYTE() directly in order to pull just enough bytes to decode the next + code, and no more. + + Some states loop until they get enough input, making sure that enough + state information is maintained to continue the loop where it left off + if NEEDBITS() returns in the loop. For example, want, need, and keep + would all have to actually be part of the saved state in case NEEDBITS() + returns: + + case STATEw: + while (want < need) { + NEEDBITS(n); + keep[want++] = BITS(n); + DROPBITS(n); + } + state = STATEx; + case STATEx: + + As shown above, if the next state is also the next case, then the break + is omitted. + + A state may also return if there is not enough output space available to + complete that state. Those states are copying stored data, writing a + literal byte, and copying a matching string. + + When returning, a "goto inf_leave" is used to update the total counters, + update the check value, and determine whether any progress has been made + during that inflate() call in order to return the proper return code. + Progress is defined as a change in either strm->avail_in or strm->avail_out. + When there is a window, goto inf_leave will update the window with the last + output written. If a goto inf_leave occurs in the middle of decompression + and there is no window currently, goto inf_leave will create one and copy + output to the window for the next call of inflate(). + + In this implementation, the flush parameter of inflate() only affects the + return code (per zlib.h). inflate() always writes as much as possible to + strm->next_out, given the space available and the provided input--the effect + documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers + the allocation of and copying into a sliding window until necessary, which + provides the effect documented in zlib.h for Z_FINISH when the entire input + stream available. So the only thing the flush parameter actually does is: + when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it + will return Z_BUF_ERROR if it has not reached the end of the stream. + */ + +int ZEXPORT inflate(strm, flush) +z_streamp strm; +int flush; +{ + struct inflate_state FAR *state; + z_const unsigned char FAR *next; /* next input */ + unsigned char FAR *put; /* next output */ + unsigned have, left; /* available input and output */ + unsigned long hold; /* bit buffer */ + unsigned bits; /* bits in bit buffer */ + unsigned in, out; /* save starting available input and output */ + unsigned copy; /* number of stored or match bytes to copy */ + unsigned char FAR *from; /* where to copy match bytes from */ + code here; /* current decoding table entry */ + code last; /* parent table entry */ + unsigned len; /* length to copy for repeats, bits to drop */ + int ret; /* return code */ +#ifdef GUNZIP + unsigned char hbuf[4]; /* buffer for gzip header crc calculation */ +#endif + static const unsigned short order[19] = /* permutation of code lengths */ + {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + + if (inflateStateCheck(strm) || strm->next_out == Z_NULL || + (strm->next_in == Z_NULL && strm->avail_in != 0)) + return Z_STREAM_ERROR; + + state = (struct inflate_state FAR *)strm->state; + if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */ + LOAD(); + in = have; + out = left; + ret = Z_OK; + for (;;) + switch (state->mode) { + case HEAD: + if (state->wrap == 0) { + state->mode = TYPEDO; + break; + } + NEEDBITS(16); +#ifdef GUNZIP + if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */ + if (state->wbits == 0) + state->wbits = 15; + state->check = crc32(0L, Z_NULL, 0); + CRC2(state->check, hold); + INITBITS(); + state->mode = FLAGS; + break; + } + state->flags = 0; /* expect zlib header */ + if (state->head != Z_NULL) + state->head->done = -1; + if (!(state->wrap & 1) || /* check if zlib header allowed */ +#else + if ( +#endif + ((BITS(8) << 8) + (hold >> 8)) % 31) { + strm->msg = (char *)"incorrect header check"; + state->mode = BAD; + break; + } + if (BITS(4) != Z_DEFLATED) { + strm->msg = (char *)"unknown compression method"; + state->mode = BAD; + break; + } + DROPBITS(4); + len = BITS(4) + 8; + if (state->wbits == 0) + state->wbits = len; + if (len > 15 || len > state->wbits) { + strm->msg = (char *)"invalid window size"; + state->mode = BAD; + break; + } + state->dmax = 1U << len; + Tracev((stderr, "inflate: zlib header ok\n")); + strm->adler = state->check = adler32(0L, Z_NULL, 0); + state->mode = hold & 0x200 ? DICTID : TYPE; + INITBITS(); + break; +#ifdef GUNZIP + case FLAGS: + NEEDBITS(16); + state->flags = (int)(hold); + if ((state->flags & 0xff) != Z_DEFLATED) { + strm->msg = (char *)"unknown compression method"; + state->mode = BAD; + break; + } + if (state->flags & 0xe000) { + strm->msg = (char *)"unknown header flags set"; + state->mode = BAD; + break; + } + if (state->head != Z_NULL) + state->head->text = (int)((hold >> 8) & 1); + if ((state->flags & 0x0200) && (state->wrap & 4)) + CRC2(state->check, hold); + INITBITS(); + state->mode = TIME; + case TIME: + NEEDBITS(32); + if (state->head != Z_NULL) + state->head->time = hold; + if ((state->flags & 0x0200) && (state->wrap & 4)) + CRC4(state->check, hold); + INITBITS(); + state->mode = OS; + case OS: + NEEDBITS(16); + if (state->head != Z_NULL) { + state->head->xflags = (int)(hold & 0xff); + state->head->os = (int)(hold >> 8); + } + if ((state->flags & 0x0200) && (state->wrap & 4)) + CRC2(state->check, hold); + INITBITS(); + state->mode = EXLEN; + case EXLEN: + if (state->flags & 0x0400) { + NEEDBITS(16); + state->length = (unsigned)(hold); + if (state->head != Z_NULL) + state->head->extra_len = (unsigned)hold; + if ((state->flags & 0x0200) && (state->wrap & 4)) + CRC2(state->check, hold); + INITBITS(); + } + else if (state->head != Z_NULL) + state->head->extra = Z_NULL; + state->mode = EXTRA; + case EXTRA: + if (state->flags & 0x0400) { + copy = state->length; + if (copy > have) copy = have; + if (copy) { + if (state->head != Z_NULL && + state->head->extra != Z_NULL) { + len = state->head->extra_len - state->length; + zmemcpy(state->head->extra + len, next, + len + copy > state->head->extra_max ? + state->head->extra_max - len : copy); + } + if ((state->flags & 0x0200) && (state->wrap & 4)) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + state->length -= copy; + } + if (state->length) goto inf_leave; + } + state->length = 0; + state->mode = NAME; + case NAME: + if (state->flags & 0x0800) { + if (have == 0) goto inf_leave; + copy = 0; + do { + len = (unsigned)(next[copy++]); + if (state->head != Z_NULL && + state->head->name != Z_NULL && + state->length < state->head->name_max) + state->head->name[state->length++] = (Bytef)len; + } while (len && copy < have); + if ((state->flags & 0x0200) && (state->wrap & 4)) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + if (len) goto inf_leave; + } + else if (state->head != Z_NULL) + state->head->name = Z_NULL; + state->length = 0; + state->mode = COMMENT; + case COMMENT: + if (state->flags & 0x1000) { + if (have == 0) goto inf_leave; + copy = 0; + do { + len = (unsigned)(next[copy++]); + if (state->head != Z_NULL && + state->head->comment != Z_NULL && + state->length < state->head->comm_max) + state->head->comment[state->length++] = (Bytef)len; + } while (len && copy < have); + if ((state->flags & 0x0200) && (state->wrap & 4)) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + if (len) goto inf_leave; + } + else if (state->head != Z_NULL) + state->head->comment = Z_NULL; + state->mode = HCRC; + case HCRC: + if (state->flags & 0x0200) { + NEEDBITS(16); + if ((state->wrap & 4) && hold != (state->check & 0xffff)) { + strm->msg = (char *)"header crc mismatch"; + state->mode = BAD; + break; + } + INITBITS(); + } + if (state->head != Z_NULL) { + state->head->hcrc = (int)((state->flags >> 9) & 1); + state->head->done = 1; + } + strm->adler = state->check = crc32(0L, Z_NULL, 0); + state->mode = TYPE; + break; +#endif + case DICTID: + NEEDBITS(32); + strm->adler = state->check = ZSWAP32(hold); + INITBITS(); + state->mode = DICT; + case DICT: + if (state->havedict == 0) { + RESTORE(); + return Z_NEED_DICT; + } + strm->adler = state->check = adler32(0L, Z_NULL, 0); + state->mode = TYPE; + case TYPE: + if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave; + case TYPEDO: + if (state->last) { + BYTEBITS(); + state->mode = CHECK; + break; + } + NEEDBITS(3); + state->last = BITS(1); + DROPBITS(1); + switch (BITS(2)) { + case 0: /* stored block */ + Tracev((stderr, "inflate: stored block%s\n", + state->last ? " (last)" : "")); + state->mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + Tracev((stderr, "inflate: fixed codes block%s\n", + state->last ? " (last)" : "")); + state->mode = LEN_; /* decode codes */ + if (flush == Z_TREES) { + DROPBITS(2); + goto inf_leave; + } + break; + case 2: /* dynamic block */ + Tracev((stderr, "inflate: dynamic codes block%s\n", + state->last ? " (last)" : "")); + state->mode = TABLE; + break; + case 3: + strm->msg = (char *)"invalid block type"; + state->mode = BAD; + } + DROPBITS(2); + break; + case STORED: + BYTEBITS(); /* go to byte boundary */ + NEEDBITS(32); + if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { + strm->msg = (char *)"invalid stored block lengths"; + state->mode = BAD; + break; + } + state->length = (unsigned)hold & 0xffff; + Tracev((stderr, "inflate: stored length %u\n", + state->length)); + INITBITS(); + state->mode = COPY_; + if (flush == Z_TREES) goto inf_leave; + case COPY_: + state->mode = COPY; + case COPY: + copy = state->length; + if (copy) { + if (copy > have) copy = have; + if (copy > left) copy = left; + if (copy == 0) goto inf_leave; + zmemcpy(put, next, copy); + have -= copy; + next += copy; + left -= copy; + put += copy; + state->length -= copy; + break; + } + Tracev((stderr, "inflate: stored end\n")); + state->mode = TYPE; + break; + case TABLE: + NEEDBITS(14); + state->nlen = BITS(5) + 257; + DROPBITS(5); + state->ndist = BITS(5) + 1; + DROPBITS(5); + state->ncode = BITS(4) + 4; + DROPBITS(4); +#ifndef PKZIP_BUG_WORKAROUND + if (state->nlen > 286 || state->ndist > 30) { + strm->msg = (char *)"too many length or distance symbols"; + state->mode = BAD; + break; + } +#endif + Tracev((stderr, "inflate: table sizes ok\n")); + state->have = 0; + state->mode = LENLENS; + case LENLENS: + while (state->have < state->ncode) { + NEEDBITS(3); + state->lens[order[state->have++]] = (unsigned short)BITS(3); + DROPBITS(3); + } + while (state->have < 19) + state->lens[order[state->have++]] = 0; + state->next = state->codes; + state->lencode = (const code FAR *)(state->next); + state->lenbits = 7; + ret = inflate_table(CODES, state->lens, 19, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid code lengths set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: code lengths ok\n")); + state->have = 0; + state->mode = CODELENS; + case CODELENS: + while (state->have < state->nlen + state->ndist) { + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.val < 16) { + DROPBITS(here.bits); + state->lens[state->have++] = here.val; + } + else { + if (here.val == 16) { + NEEDBITS(here.bits + 2); + DROPBITS(here.bits); + if (state->have == 0) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + len = state->lens[state->have - 1]; + copy = 3 + BITS(2); + DROPBITS(2); + } + else if (here.val == 17) { + NEEDBITS(here.bits + 3); + DROPBITS(here.bits); + len = 0; + copy = 3 + BITS(3); + DROPBITS(3); + } + else { + NEEDBITS(here.bits + 7); + DROPBITS(here.bits); + len = 0; + copy = 11 + BITS(7); + DROPBITS(7); + } + if (state->have + copy > state->nlen + state->ndist) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + while (copy--) + state->lens[state->have++] = (unsigned short)len; + } + } + + /* handle error breaks in while */ + if (state->mode == BAD) break; + + /* check for end-of-block code (better have one) */ + if (state->lens[256] == 0) { + strm->msg = (char *)"invalid code -- missing end-of-block"; + state->mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state->next = state->codes; + state->lencode = (const code FAR *)(state->next); + state->lenbits = 9; + ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid literal/lengths set"; + state->mode = BAD; + break; + } + state->distcode = (const code FAR *)(state->next); + state->distbits = 6; + ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, + &(state->next), &(state->distbits), state->work); + if (ret) { + strm->msg = (char *)"invalid distances set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: codes ok\n")); + state->mode = LEN_; + if (flush == Z_TREES) goto inf_leave; + case LEN_: + state->mode = LEN; + case LEN: + if (have >= 6 && left >= 258) { + RESTORE(); + inflate_fast(strm, out); + LOAD(); + if (state->mode == TYPE) + state->back = -1; + break; + } + state->back = 0; + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.op && (here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->lencode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + state->back += last.bits; + } + DROPBITS(here.bits); + state->back += here.bits; + state->length = (unsigned)here.val; + if ((int)(here.op) == 0) { + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", here.val)); + state->mode = LIT; + break; + } + if (here.op & 32) { + Tracevv((stderr, "inflate: end of block\n")); + state->back = -1; + state->mode = TYPE; + break; + } + if (here.op & 64) { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + state->extra = (unsigned)(here.op) & 15; + state->mode = LENEXT; + case LENEXT: + if (state->extra) { + NEEDBITS(state->extra); + state->length += BITS(state->extra); + DROPBITS(state->extra); + state->back += state->extra; + } + Tracevv((stderr, "inflate: length %u\n", state->length)); + state->was = state->length; + state->mode = DIST; + case DIST: + for (;;) { + here = state->distcode[BITS(state->distbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if ((here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->distcode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + state->back += last.bits; + } + DROPBITS(here.bits); + state->back += here.bits; + if (here.op & 64) { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + state->offset = (unsigned)here.val; + state->extra = (unsigned)(here.op) & 15; + state->mode = DISTEXT; + case DISTEXT: + if (state->extra) { + NEEDBITS(state->extra); + state->offset += BITS(state->extra); + DROPBITS(state->extra); + state->back += state->extra; + } +#ifdef INFLATE_STRICT + if (state->offset > state->dmax) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#endif + Tracevv((stderr, "inflate: distance %u\n", state->offset)); + state->mode = MATCH; + case MATCH: + if (left == 0) goto inf_leave; + copy = out - left; + if (state->offset > copy) { /* copy from window */ + copy = state->offset - copy; + if (copy > state->whave) { + if (state->sane) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + Trace((stderr, "inflate.c too far\n")); + copy -= state->whave; + if (copy > state->length) copy = state->length; + if (copy > left) copy = left; + left -= copy; + state->length -= copy; + do { + *put++ = 0; + } while (--copy); + if (state->length == 0) state->mode = LEN; + break; +#endif + } + if (copy > state->wnext) { + copy -= state->wnext; + from = state->window + (state->wsize - copy); + } + else + from = state->window + (state->wnext - copy); + if (copy > state->length) copy = state->length; + } + else { /* copy from output */ + from = put - state->offset; + copy = state->length; + } + if (copy > left) copy = left; + left -= copy; + state->length -= copy; + do { + *put++ = *from++; + } while (--copy); + if (state->length == 0) state->mode = LEN; + break; + case LIT: + if (left == 0) goto inf_leave; + *put++ = (unsigned char)(state->length); + left--; + state->mode = LEN; + break; + case CHECK: + if (state->wrap) { + NEEDBITS(32); + out -= left; + strm->total_out += out; + state->total += out; + if ((state->wrap & 4) && out) + strm->adler = state->check = + UPDATE(state->check, put - out, out); + out = left; + if ((state->wrap & 4) && ( +#ifdef GUNZIP + state->flags ? hold : +#endif + ZSWAP32(hold)) != state->check) { + strm->msg = (char *)"incorrect data check"; + state->mode = BAD; + break; + } + INITBITS(); + Tracev((stderr, "inflate: check matches trailer\n")); + } +#ifdef GUNZIP + state->mode = LENGTH; + case LENGTH: + if (state->wrap && state->flags) { + NEEDBITS(32); + if (hold != (state->total & 0xffffffffUL)) { + strm->msg = (char *)"incorrect length check"; + state->mode = BAD; + break; + } + INITBITS(); + Tracev((stderr, "inflate: length matches trailer\n")); + } +#endif + state->mode = DONE; + case DONE: + ret = Z_STREAM_END; + goto inf_leave; + case BAD: + ret = Z_DATA_ERROR; + goto inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + default: + return Z_STREAM_ERROR; + } + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + inf_leave: + RESTORE(); + if (state->wsize || (out != strm->avail_out && state->mode < BAD && + (state->mode < CHECK || flush != Z_FINISH))) + if (updatewindow(strm, strm->next_out, out - strm->avail_out)) { + state->mode = MEM; + return Z_MEM_ERROR; + } + in -= strm->avail_in; + out -= strm->avail_out; + strm->total_in += in; + strm->total_out += out; + state->total += out; + if ((state->wrap & 4) && out) + strm->adler = state->check = + UPDATE(state->check, strm->next_out - out, out); + strm->data_type = (int)state->bits + (state->last ? 64 : 0) + + (state->mode == TYPE ? 128 : 0) + + (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0); + if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK) + ret = Z_BUF_ERROR; + return ret; +} + +int ZEXPORT inflateEnd(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + if (inflateStateCheck(strm)) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (state->window != Z_NULL) ZFREE(strm, state->window); + ZFREE(strm, strm->state); + strm->state = Z_NULL; + Tracev((stderr, "inflate: end\n")); + return Z_OK; +} + +int ZEXPORT inflateGetDictionary(strm, dictionary, dictLength) +z_streamp strm; +Bytef *dictionary; +uInt *dictLength; +{ + struct inflate_state FAR *state; + + /* check state */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + + /* copy dictionary */ + if (state->whave && dictionary != Z_NULL) { + zmemcpy(dictionary, state->window + state->wnext, + state->whave - state->wnext); + zmemcpy(dictionary + state->whave - state->wnext, + state->window, state->wnext); + } + if (dictLength != Z_NULL) + *dictLength = state->whave; + return Z_OK; +} + +int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength) +z_streamp strm; +const Bytef *dictionary; +uInt dictLength; +{ + struct inflate_state FAR *state; + unsigned long dictid; + int ret; + + /* check state */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (state->wrap != 0 && state->mode != DICT) + return Z_STREAM_ERROR; + + /* check for correct dictionary identifier */ + if (state->mode == DICT) { + dictid = adler32(0L, Z_NULL, 0); + dictid = adler32(dictid, dictionary, dictLength); + if (dictid != state->check) + return Z_DATA_ERROR; + } + + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + ret = updatewindow(strm, dictionary + dictLength, dictLength); + if (ret) { + state->mode = MEM; + return Z_MEM_ERROR; + } + state->havedict = 1; + Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK; +} + +int ZEXPORT inflateGetHeader(strm, head) +z_streamp strm; +gz_headerp head; +{ + struct inflate_state FAR *state; + + /* check state */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if ((state->wrap & 2) == 0) return Z_STREAM_ERROR; + + /* save header structure */ + state->head = head; + head->done = 0; + return Z_OK; +} + +/* + Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found + or when out of input. When called, *have is the number of pattern bytes + found in order so far, in 0..3. On return *have is updated to the new + state. If on return *have equals four, then the pattern was found and the + return value is how many bytes were read including the last byte of the + pattern. If *have is less than four, then the pattern has not been found + yet and the return value is len. In the latter case, syncsearch() can be + called again with more data and the *have state. *have is initialized to + zero for the first call. + */ +local unsigned syncsearch(have, buf, len) +unsigned FAR *have; +const unsigned char FAR *buf; +unsigned len; +{ + unsigned got; + unsigned next; + + got = *have; + next = 0; + while (next < len && got < 4) { + if ((int)(buf[next]) == (got < 2 ? 0 : 0xff)) + got++; + else if (buf[next]) + got = 0; + else + got = 4 - got; + next++; + } + *have = got; + return next; +} + +int ZEXPORT inflateSync(strm) +z_streamp strm; +{ + unsigned len; /* number of bytes to look at or looked at */ + unsigned long in, out; /* temporary to save total_in and total_out */ + unsigned char buf[4]; /* to restore bit buffer to byte string */ + struct inflate_state FAR *state; + + /* check parameters */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR; + + /* if first time, start search in bit buffer */ + if (state->mode != SYNC) { + state->mode = SYNC; + state->hold <<= state->bits & 7; + state->bits -= state->bits & 7; + len = 0; + while (state->bits >= 8) { + buf[len++] = (unsigned char)(state->hold); + state->hold >>= 8; + state->bits -= 8; + } + state->have = 0; + syncsearch(&(state->have), buf, len); + } + + /* search available input */ + len = syncsearch(&(state->have), strm->next_in, strm->avail_in); + strm->avail_in -= len; + strm->next_in += len; + strm->total_in += len; + + /* return no joy or set up to restart inflate() on a new block */ + if (state->have != 4) return Z_DATA_ERROR; + in = strm->total_in; out = strm->total_out; + inflateReset(strm); + strm->total_in = in; strm->total_out = out; + state->mode = TYPE; + return Z_OK; +} + +/* + Returns true if inflate is currently at the end of a block generated by + Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP + implementation to provide an additional safety check. PPP uses + Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored + block. When decompressing, PPP checks that at the end of input packet, + inflate is waiting for these length bytes. + */ +int ZEXPORT inflateSyncPoint(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + return state->mode == STORED && state->bits == 0; +} + +int ZEXPORT inflateCopy(dest, source) +z_streamp dest; +z_streamp source; +{ + struct inflate_state FAR *state; + struct inflate_state FAR *copy; + unsigned char FAR *window; + unsigned wsize; + + /* check input */ + if (inflateStateCheck(source) || dest == Z_NULL) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)source->state; + + /* allocate space */ + copy = (struct inflate_state FAR *) + ZALLOC(source, 1, sizeof(struct inflate_state)); + if (copy == Z_NULL) return Z_MEM_ERROR; + window = Z_NULL; + if (state->window != Z_NULL) { + window = (unsigned char FAR *) + ZALLOC(source, 1U << state->wbits, sizeof(unsigned char)); + if (window == Z_NULL) { + ZFREE(source, copy); + return Z_MEM_ERROR; + } + } + + /* copy state */ + zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream)); + zmemcpy((voidpf)copy, (voidpf)state, sizeof(struct inflate_state)); + copy->strm = dest; + if (state->lencode >= state->codes && + state->lencode <= state->codes + ENOUGH - 1) { + copy->lencode = copy->codes + (state->lencode - state->codes); + copy->distcode = copy->codes + (state->distcode - state->codes); + } + copy->next = copy->codes + (state->next - state->codes); + if (window != Z_NULL) { + wsize = 1U << state->wbits; + zmemcpy(window, state->window, wsize); + } + copy->window = window; + dest->state = (struct internal_state FAR *)copy; + return Z_OK; +} + +int ZEXPORT inflateUndermine(strm, subvert) +z_streamp strm; +int subvert; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + state->sane = !subvert; + return Z_OK; +#else + (void)subvert; + state->sane = 1; + return Z_DATA_ERROR; +#endif +} + +int ZEXPORT inflateValidate(strm, check) +z_streamp strm; +int check; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (check) + state->wrap |= 4; + else + state->wrap &= ~4; + return Z_OK; +} + +long ZEXPORT inflateMark(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) + return -(1L << 16); + state = (struct inflate_state FAR *)strm->state; + return (long)(((unsigned long)((long)state->back)) << 16) + + (state->mode == COPY ? state->length : + (state->mode == MATCH ? state->was - state->length : 0)); +} + +unsigned long ZEXPORT inflateCodesUsed(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + if (inflateStateCheck(strm)) return (unsigned long)-1; + state = (struct inflate_state FAR *)strm->state; + return (unsigned long)(state->next - state->codes); +} diff --git a/Source/Libraries/zlib/inftrees.c b/Source/Libraries/zlib/inftrees.c new file mode 100644 index 0000000..2ea08fc --- /dev/null +++ b/Source/Libraries/zlib/inftrees.c @@ -0,0 +1,304 @@ +/* inftrees.c -- generate Huffman trees for efficient decoding + * Copyright (C) 1995-2017 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "zutil.h" +#include "inftrees.h" + +#define MAXBITS 15 + +const char inflate_copyright[] = + " inflate 1.2.11 Copyright 1995-2017 Mark Adler "; +/* + If you use the zlib library in a product, an acknowledgment is welcome + in the documentation of your product. If for some reason you cannot + include such an acknowledgment, I would appreciate that you keep this + copyright string in the executable of your product. + */ + +/* + Build a set of tables to decode the provided canonical Huffman code. + The code lengths are lens[0..codes-1]. The result starts at *table, + whose indices are 0..2^bits-1. work is a writable array of at least + lens shorts, which is used as a work area. type is the type of code + to be generated, CODES, LENS, or DISTS. On return, zero is success, + -1 is an invalid code, and +1 means that ENOUGH isn't enough. table + on return points to the next available entry's address. bits is the + requested root table index bits, and on return it is the actual root + table index bits. It will differ if the request is greater than the + longest code or if it is less than the shortest code. + */ +int ZLIB_INTERNAL inflate_table(type, lens, codes, table, bits, work) +codetype type; +unsigned short FAR *lens; +unsigned codes; +code FAR * FAR *table; +unsigned FAR *bits; +unsigned short FAR *work; +{ + unsigned len; /* a code's length in bits */ + unsigned sym; /* index of code symbols */ + unsigned min, max; /* minimum and maximum code lengths */ + unsigned root; /* number of index bits for root table */ + unsigned curr; /* number of index bits for current table */ + unsigned drop; /* code bits to drop for sub-table */ + int left; /* number of prefix codes available */ + unsigned used; /* code entries in table used */ + unsigned huff; /* Huffman code */ + unsigned incr; /* for incrementing code, index */ + unsigned fill; /* index for replicating entries */ + unsigned low; /* low bits for current root entry */ + unsigned mask; /* mask for low root bits */ + code here; /* table entry for duplication */ + code FAR *next; /* next available space in table */ + const unsigned short FAR *base; /* base value table to use */ + const unsigned short FAR *extra; /* extra bits table to use */ + unsigned match; /* use base and extra for symbol >= match */ + unsigned short count[MAXBITS+1]; /* number of codes of each length */ + unsigned short offs[MAXBITS+1]; /* offsets in table for each length */ + static const unsigned short lbase[31] = { /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; + static const unsigned short lext[31] = { /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 77, 202}; + static const unsigned short dbase[32] = { /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0}; + static const unsigned short dext[32] = { /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64}; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) + count[len] = 0; + for (sym = 0; sym < codes; sym++) + count[lens[sym]]++; + + /* bound code lengths, force root to be within code lengths */ + root = *bits; + for (max = MAXBITS; max >= 1; max--) + if (count[max] != 0) break; + if (root > max) root = max; + if (max == 0) { /* no symbols to code at all */ + here.op = (unsigned char)64; /* invalid code marker */ + here.bits = (unsigned char)1; + here.val = (unsigned short)0; + *(*table)++ = here; /* make a table to force an error */ + *(*table)++ = here; + *bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) + if (count[min] != 0) break; + if (root < min) root = min; + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) return -1; /* over-subscribed */ + } + if (left > 0 && (type == CODES || max != 1)) + return -1; /* incomplete set */ + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) + offs[len + 1] = offs[len] + count[len]; + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) + if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym; + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + switch (type) { + case CODES: + base = extra = work; /* dummy value--not used */ + match = 20; + break; + case LENS: + base = lbase; + extra = lext; + match = 257; + break; + default: /* DISTS */ + base = dbase; + extra = dext; + match = 0; + } + + /* initialize state for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = *table; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = (unsigned)(-1); /* trigger new sub-table when len > root */ + used = 1U << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type == LENS && used > ENOUGH_LENS) || + (type == DISTS && used > ENOUGH_DISTS)) + return 1; + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + here.bits = (unsigned char)(len - drop); + if (work[sym] + 1U < match) { + here.op = (unsigned char)0; + here.val = work[sym]; + } + else if (work[sym] >= match) { + here.op = (unsigned char)(extra[work[sym] - match]); + here.val = base[work[sym] - match]; + } + else { + here.op = (unsigned char)(32 + 64); /* end of block */ + here.val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1U << (len - drop); + fill = 1U << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + next[(huff >> drop) + fill] = here; + } while (fill != 0); + + /* backwards increment the len-bit code huff */ + incr = 1U << (len - 1); + while (huff & incr) + incr >>= 1; + if (incr != 0) { + huff &= incr - 1; + huff += incr; + } + else + huff = 0; + + /* go to next symbol, update count, len */ + sym++; + if (--(count[len]) == 0) { + if (len == max) break; + len = lens[work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) != low) { + /* if first time, transition to sub-tables */ + if (drop == 0) + drop = root; + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = (int)(1 << curr); + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) break; + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1U << curr; + if ((type == LENS && used > ENOUGH_LENS) || + (type == DISTS && used > ENOUGH_DISTS)) + return 1; + + /* point entry in root table to sub-table */ + low = huff & mask; + (*table)[low].op = (unsigned char)curr; + (*table)[low].bits = (unsigned char)root; + (*table)[low].val = (unsigned short)(next - *table); + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff != 0) { + here.op = (unsigned char)64; /* invalid code marker */ + here.bits = (unsigned char)(len - drop); + here.val = (unsigned short)0; + next[huff] = here; + } + + /* set return parameters */ + *table += used; + *bits = root; + return 0; +} diff --git a/Source/Libraries/zlib/trees.c b/Source/Libraries/zlib/trees.c new file mode 100644 index 0000000..50cf4b4 --- /dev/null +++ b/Source/Libraries/zlib/trees.c @@ -0,0 +1,1203 @@ +/* trees.c -- output deflated data using Huffman coding + * Copyright (C) 1995-2017 Jean-loup Gailly + * detect_data_type() function provided freely by Cosmin Truta, 2006 + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * ALGORITHM + * + * The "deflation" process uses several Huffman trees. The more + * common source values are represented by shorter bit sequences. + * + * Each code tree is stored in a compressed form which is itself + * a Huffman encoding of the lengths of all the code strings (in + * ascending order by source values). The actual code strings are + * reconstructed from the lengths in the inflate process, as described + * in the deflate specification. + * + * REFERENCES + * + * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification". + * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc + * + * Storer, James A. + * Data Compression: Methods and Theory, pp. 49-50. + * Computer Science Press, 1988. ISBN 0-7167-8156-5. + * + * Sedgewick, R. + * Algorithms, p290. + * Addison-Wesley, 1983. ISBN 0-201-06672-6. + */ + +/* @(#) $Id$ */ + +/* #define GEN_TREES_H */ + +#include "deflate.h" + +#ifdef ZLIB_DEBUG +# include +#endif + +/* =========================================================================== + * Constants + */ + +#define MAX_BL_BITS 7 +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +#define END_BLOCK 256 +/* end of block literal code */ + +#define REP_3_6 16 +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +#define REPZ_3_10 17 +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +#define REPZ_11_138 18 +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */ + = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; + +local const int extra_dbits[D_CODES] /* extra bits for each distance code */ + = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; + +local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */ + = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; + +local const uch bl_order[BL_CODES] + = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +#define DIST_CODE_LEN 512 /* see definition of array dist_code below */ + +#if defined(GEN_TREES_H) || !defined(STDC) +/* non ANSI compilers may not accept trees.h */ + +local ct_data static_ltree[L_CODES+2]; +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +local ct_data static_dtree[D_CODES]; +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +uch _dist_code[DIST_CODE_LEN]; +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +uch _length_code[MAX_MATCH-MIN_MATCH+1]; +/* length code for each normalized match length (0 == MIN_MATCH) */ + +local int base_length[LENGTH_CODES]; +/* First normalized length for each code (0 = MIN_MATCH) */ + +local int base_dist[D_CODES]; +/* First normalized distance for each code (0 = distance of 1) */ + +#else +# include "trees.h" +#endif /* GEN_TREES_H */ + +struct static_tree_desc_s { + const ct_data *static_tree; /* static tree or NULL */ + const intf *extra_bits; /* extra bits for each code or NULL */ + int extra_base; /* base index for extra_bits */ + int elems; /* max number of elements in the tree */ + int max_length; /* max bit length for the codes */ +}; + +local const static_tree_desc static_l_desc = +{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; + +local const static_tree_desc static_d_desc = +{static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; + +local const static_tree_desc static_bl_desc = +{(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; + +/* =========================================================================== + * Local (static) routines in this file. + */ + +local void tr_static_init OF((void)); +local void init_block OF((deflate_state *s)); +local void pqdownheap OF((deflate_state *s, ct_data *tree, int k)); +local void gen_bitlen OF((deflate_state *s, tree_desc *desc)); +local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count)); +local void build_tree OF((deflate_state *s, tree_desc *desc)); +local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code)); +local void send_tree OF((deflate_state *s, ct_data *tree, int max_code)); +local int build_bl_tree OF((deflate_state *s)); +local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes, + int blcodes)); +local void compress_block OF((deflate_state *s, const ct_data *ltree, + const ct_data *dtree)); +local int detect_data_type OF((deflate_state *s)); +local unsigned bi_reverse OF((unsigned value, int length)); +local void bi_windup OF((deflate_state *s)); +local void bi_flush OF((deflate_state *s)); + +#ifdef GEN_TREES_H +local void gen_trees_header OF((void)); +#endif + +#ifndef ZLIB_DEBUG +# define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len) + /* Send a code of the given tree. c and tree must not have side effects */ + +#else /* !ZLIB_DEBUG */ +# define send_code(s, c, tree) \ + { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \ + send_bits(s, tree[c].Code, tree[c].Len); } +#endif + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +#define put_short(s, w) { \ + put_byte(s, (uch)((w) & 0xff)); \ + put_byte(s, (uch)((ush)(w) >> 8)); \ +} + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +#ifdef ZLIB_DEBUG +local void send_bits OF((deflate_state *s, int value, int length)); + +local void send_bits(s, value, length) + deflate_state *s; + int value; /* value to send */ + int length; /* number of bits */ +{ + Tracevv((stderr," l %2d v %4x ", length, value)); + Assert(length > 0 && length <= 15, "invalid length"); + s->bits_sent += (ulg)length; + + /* If not enough room in bi_buf, use (valid) bits from bi_buf and + * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid)) + * unused bits in value. + */ + if (s->bi_valid > (int)Buf_size - length) { + s->bi_buf |= (ush)value << s->bi_valid; + put_short(s, s->bi_buf); + s->bi_buf = (ush)value >> (Buf_size - s->bi_valid); + s->bi_valid += length - Buf_size; + } else { + s->bi_buf |= (ush)value << s->bi_valid; + s->bi_valid += length; + } +} +#else /* !ZLIB_DEBUG */ + +#define send_bits(s, value, length) \ +{ int len = length;\ + if (s->bi_valid > (int)Buf_size - len) {\ + int val = (int)value;\ + s->bi_buf |= (ush)val << s->bi_valid;\ + put_short(s, s->bi_buf);\ + s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\ + s->bi_valid += len - Buf_size;\ + } else {\ + s->bi_buf |= (ush)(value) << s->bi_valid;\ + s->bi_valid += len;\ + }\ +} +#endif /* ZLIB_DEBUG */ + + +/* the arguments must not have side effects */ + +/* =========================================================================== + * Initialize the various 'constant' tables. + */ +local void tr_static_init() +{ +#if defined(GEN_TREES_H) || !defined(STDC) + static int static_init_done = 0; + int n; /* iterates over tree elements */ + int bits; /* bit counter */ + int length; /* length value */ + int code; /* code value */ + int dist; /* distance index */ + ush bl_count[MAX_BITS+1]; + /* number of codes at each bit length for an optimal tree */ + + if (static_init_done) return; + + /* For some embedded targets, global variables are not initialized: */ +#ifdef NO_INIT_GLOBAL_POINTERS + static_l_desc.static_tree = static_ltree; + static_l_desc.extra_bits = extra_lbits; + static_d_desc.static_tree = static_dtree; + static_d_desc.extra_bits = extra_dbits; + static_bl_desc.extra_bits = extra_blbits; +#endif + + /* Initialize the mapping length (0..255) -> length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES-1; code++) { + base_length[code] = length; + for (n = 0; n < (1< dist code (0..29) */ + dist = 0; + for (code = 0 ; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1<>= 7; /* from now on, all distances are divided by 128 */ + for ( ; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { + _dist_code[256 + dist++] = (uch)code; + } + } + Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; + n = 0; + while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; + while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; + while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; + while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n].Len = 5; + static_dtree[n].Code = bi_reverse((unsigned)n, 5); + } + static_init_done = 1; + +# ifdef GEN_TREES_H + gen_trees_header(); +# endif +#endif /* defined(GEN_TREES_H) || !defined(STDC) */ +} + +/* =========================================================================== + * Genererate the file trees.h describing the static trees. + */ +#ifdef GEN_TREES_H +# ifndef ZLIB_DEBUG +# include +# endif + +# define SEPARATOR(i, last, width) \ + ((i) == (last)? "\n};\n\n" : \ + ((i) % (width) == (width)-1 ? ",\n" : ", ")) + +void gen_trees_header() +{ + FILE *header = fopen("trees.h", "w"); + int i; + + Assert (header != NULL, "Can't open trees.h"); + fprintf(header, + "/* header created automatically with -DGEN_TREES_H */\n\n"); + + fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n"); + for (i = 0; i < L_CODES+2; i++) { + fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code, + static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5)); + } + + fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n"); + for (i = 0; i < D_CODES; i++) { + fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code, + static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5)); + } + + fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n"); + for (i = 0; i < DIST_CODE_LEN; i++) { + fprintf(header, "%2u%s", _dist_code[i], + SEPARATOR(i, DIST_CODE_LEN-1, 20)); + } + + fprintf(header, + "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n"); + for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) { + fprintf(header, "%2u%s", _length_code[i], + SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20)); + } + + fprintf(header, "local const int base_length[LENGTH_CODES] = {\n"); + for (i = 0; i < LENGTH_CODES; i++) { + fprintf(header, "%1u%s", base_length[i], + SEPARATOR(i, LENGTH_CODES-1, 20)); + } + + fprintf(header, "local const int base_dist[D_CODES] = {\n"); + for (i = 0; i < D_CODES; i++) { + fprintf(header, "%5u%s", base_dist[i], + SEPARATOR(i, D_CODES-1, 10)); + } + + fclose(header); +} +#endif /* GEN_TREES_H */ + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +void ZLIB_INTERNAL _tr_init(s) + deflate_state *s; +{ + tr_static_init(); + + s->l_desc.dyn_tree = s->dyn_ltree; + s->l_desc.stat_desc = &static_l_desc; + + s->d_desc.dyn_tree = s->dyn_dtree; + s->d_desc.stat_desc = &static_d_desc; + + s->bl_desc.dyn_tree = s->bl_tree; + s->bl_desc.stat_desc = &static_bl_desc; + + s->bi_buf = 0; + s->bi_valid = 0; +#ifdef ZLIB_DEBUG + s->compressed_len = 0L; + s->bits_sent = 0L; +#endif + + /* Initialize the first block of the first file: */ + init_block(s); +} + +/* =========================================================================== + * Initialize a new block. + */ +local void init_block(s) + deflate_state *s; +{ + int n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; + for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; + for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; + + s->dyn_ltree[END_BLOCK].Freq = 1; + s->opt_len = s->static_len = 0L; + s->last_lit = s->matches = 0; +} + +#define SMALLEST 1 +/* Index within the heap array of least frequent node in the Huffman tree */ + + +/* =========================================================================== + * Remove the smallest element from the heap and recreate the heap with + * one less element. Updates heap and heap_len. + */ +#define pqremove(s, tree, top) \ +{\ + top = s->heap[SMALLEST]; \ + s->heap[SMALLEST] = s->heap[s->heap_len--]; \ + pqdownheap(s, tree, SMALLEST); \ +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +#define smaller(tree, n, m, depth) \ + (tree[n].Freq < tree[m].Freq || \ + (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +local void pqdownheap(s, tree, k) + deflate_state *s; + ct_data *tree; /* the tree to restore */ + int k; /* node to move down */ +{ + int v = s->heap[k]; + int j = k << 1; /* left son of k */ + while (j <= s->heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s->heap_len && + smaller(tree, s->heap[j+1], s->heap[j], s->depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s->heap[j], s->depth)) break; + + /* Exchange v with the smallest son */ + s->heap[k] = s->heap[j]; k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s->heap[k] = v; +} + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +local void gen_bitlen(s, desc) + deflate_state *s; + tree_desc *desc; /* the tree descriptor */ +{ + ct_data *tree = desc->dyn_tree; + int max_code = desc->max_code; + const ct_data *stree = desc->stat_desc->static_tree; + const intf *extra = desc->stat_desc->extra_bits; + int base = desc->stat_desc->extra_base; + int max_length = desc->stat_desc->max_length; + int h; /* heap index */ + int n, m; /* iterate over the tree elements */ + int bits; /* bit length */ + int xbits; /* extra bits */ + ush f; /* frequency */ + int overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0; + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ + + for (h = s->heap_max+1; h < HEAP_SIZE; h++) { + n = s->heap[h]; + bits = tree[tree[n].Dad].Len + 1; + if (bits > max_length) bits = max_length, overflow++; + tree[n].Len = (ush)bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) continue; /* not a leaf node */ + + s->bl_count[bits]++; + xbits = 0; + if (n >= base) xbits = extra[n-base]; + f = tree[n].Freq; + s->opt_len += (ulg)f * (unsigned)(bits + xbits); + if (stree) s->static_len += (ulg)f * (unsigned)(stree[n].Len + xbits); + } + if (overflow == 0) return; + + Tracev((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length-1; + while (s->bl_count[bits] == 0) bits--; + s->bl_count[bits]--; /* move one leaf down the tree */ + s->bl_count[bits+1] += 2; /* move one overflow item as its brother */ + s->bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits != 0; bits--) { + n = s->bl_count[bits]; + while (n != 0) { + m = s->heap[--h]; + if (m > max_code) continue; + if ((unsigned) tree[m].Len != (unsigned) bits) { + Tracev((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s->opt_len += ((ulg)bits - tree[m].Len) * tree[m].Freq; + tree[m].Len = (ush)bits; + } + n--; + } + } +} + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +local void gen_codes (tree, max_code, bl_count) + ct_data *tree; /* the tree to decorate */ + int max_code; /* largest code with non zero frequency */ + ushf *bl_count; /* number of codes at each bit length */ +{ + ush next_code[MAX_BITS+1]; /* next code value for each bit length */ + unsigned code = 0; /* running code value */ + int bits; /* bit index */ + int n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + code = (code + bl_count[bits-1]) << 1; + next_code[bits] = (ush)code; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + Assert (code + bl_count[MAX_BITS]-1 == (1<dyn_tree; + const ct_data *stree = desc->stat_desc->static_tree; + int elems = desc->stat_desc->elems; + int n, m; /* iterate over heap elements */ + int max_code = -1; /* largest code with non zero frequency */ + int node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s->heap_len = 0, s->heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n].Freq != 0) { + s->heap[++(s->heap_len)] = max_code = n; + s->depth[n] = 0; + } else { + tree[n].Len = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s->heap_len < 2) { + node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0); + tree[node].Freq = 1; + s->depth[node] = 0; + s->opt_len--; if (stree) s->static_len -= stree[node].Len; + /* node is 0 or 1 so it does not have extra bits */ + } + desc->max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + pqremove(s, tree, n); /* n = node of least frequency */ + m = s->heap[SMALLEST]; /* m = node of next least frequency */ + + s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */ + s->heap[--(s->heap_max)] = m; + + /* Create a new node father of n and m */ + tree[node].Freq = tree[n].Freq + tree[m].Freq; + s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ? + s->depth[n] : s->depth[m]) + 1); + tree[n].Dad = tree[m].Dad = (ush)node; +#ifdef DUMP_BL_TREE + if (tree == s->bl_tree) { + fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)", + node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq); + } +#endif + /* and insert the new node in the heap */ + s->heap[SMALLEST] = node++; + pqdownheap(s, tree, SMALLEST); + + } while (s->heap_len >= 2); + + s->heap[--(s->heap_max)] = s->heap[SMALLEST]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, (tree_desc *)desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes ((ct_data *)tree, max_code, s->bl_count); +} + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +local void scan_tree (s, tree, max_code) + deflate_state *s; + ct_data *tree; /* the tree to be scanned */ + int max_code; /* and its largest code of non zero frequency */ +{ + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].Len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + if (nextlen == 0) max_count = 138, min_count = 3; + tree[max_code+1].Len = (ush)0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n+1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + s->bl_tree[curlen].Freq += count; + } else if (curlen != 0) { + if (curlen != prevlen) s->bl_tree[curlen].Freq++; + s->bl_tree[REP_3_6].Freq++; + } else if (count <= 10) { + s->bl_tree[REPZ_3_10].Freq++; + } else { + s->bl_tree[REPZ_11_138].Freq++; + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } +} + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +local void send_tree (s, tree, max_code) + deflate_state *s; + ct_data *tree; /* the tree to be scanned */ + int max_code; /* and its largest code of non zero frequency */ +{ + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].Len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen == 0) max_count = 138, min_count = 3; + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n+1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + do { send_code(s, curlen, s->bl_tree); } while (--count != 0); + + } else if (curlen != 0) { + if (curlen != prevlen) { + send_code(s, curlen, s->bl_tree); count--; + } + Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3); + + } else { + send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7); + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } +} + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +local int build_bl_tree(s) + deflate_state *s; +{ + int max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); + scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, (tree_desc *)(&(s->bl_desc))); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { + if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; + } + /* Update opt_len to include the bit length tree and counts */ + s->opt_len += 3*((ulg)max_blindex+1) + 5+5+4; + Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + s->opt_len, s->static_len)); + + return max_blindex; +} + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +local void send_all_trees(s, lcodes, dcodes, blcodes) + deflate_state *s; + int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + int rank; /* index in bl_order */ + + Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + "too many codes"); + Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes-1, 5); + send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); + } + Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */ + Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */ + Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + +/* =========================================================================== + * Send a stored block + */ +void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last) + deflate_state *s; + charf *buf; /* input block */ + ulg stored_len; /* length of input block */ + int last; /* one if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK<<1)+last, 3); /* send block type */ + bi_windup(s); /* align on byte boundary */ + put_short(s, (ush)stored_len); + put_short(s, (ush)~stored_len); + zmemcpy(s->pending_buf + s->pending, (Bytef *)buf, stored_len); + s->pending += stored_len; +#ifdef ZLIB_DEBUG + s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; + s->compressed_len += (stored_len + 4) << 3; + s->bits_sent += 2*16; + s->bits_sent += stored_len<<3; +#endif +} + +/* =========================================================================== + * Flush the bits in the bit buffer to pending output (leaves at most 7 bits) + */ +void ZLIB_INTERNAL _tr_flush_bits(s) + deflate_state *s; +{ + bi_flush(s); +} + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +void ZLIB_INTERNAL _tr_align(s) + deflate_state *s; +{ + send_bits(s, STATIC_TREES<<1, 3); + send_code(s, END_BLOCK, static_ltree); +#ifdef ZLIB_DEBUG + s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ +#endif + bi_flush(s); +} + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and write out the encoded block. + */ +void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) + deflate_state *s; + charf *buf; /* input block, or NULL if too old */ + ulg stored_len; /* length of input block */ + int last; /* one if this is the last block for a file */ +{ + ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + int max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s->level > 0) { + + /* Check if the file is binary or text */ + if (s->strm->data_type == Z_UNKNOWN) + s->strm->data_type = detect_data_type(s); + + /* Construct the literal and distance trees */ + build_tree(s, (tree_desc *)(&(s->l_desc))); + Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + s->static_len)); + + build_tree(s, (tree_desc *)(&(s->d_desc))); + Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s->opt_len+3+7)>>3; + static_lenb = (s->static_len+3+7)>>3; + + Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + s->last_lit)); + + if (static_lenb <= opt_lenb) opt_lenb = static_lenb; + + } else { + Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + +#ifdef FORCE_STORED + if (buf != (char*)0) { /* force stored block */ +#else + if (stored_len+4 <= opt_lenb && buf != (char*)0) { + /* 4: two words for the lengths */ +#endif + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + +#ifdef FORCE_STATIC + } else if (static_lenb >= 0) { /* force static trees */ +#else + } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) { +#endif + send_bits(s, (STATIC_TREES<<1)+last, 3); + compress_block(s, (const ct_data *)static_ltree, + (const ct_data *)static_dtree); +#ifdef ZLIB_DEBUG + s->compressed_len += 3 + s->static_len; +#endif + } else { + send_bits(s, (DYN_TREES<<1)+last, 3); + send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, + max_blindex+1); + compress_block(s, (const ct_data *)s->dyn_ltree, + (const ct_data *)s->dyn_dtree); +#ifdef ZLIB_DEBUG + s->compressed_len += 3 + s->opt_len; +#endif + } + Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); +#ifdef ZLIB_DEBUG + s->compressed_len += 7; /* align on byte boundary */ +#endif + } + Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + s->compressed_len-7*last)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +int ZLIB_INTERNAL _tr_tally (s, dist, lc) + deflate_state *s; + unsigned dist; /* distance of matched string */ + unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + s->d_buf[s->last_lit] = (ush)dist; + s->l_buf[s->last_lit++] = (uch)lc; + if (dist == 0) { + /* lc is the unmatched char */ + s->dyn_ltree[lc].Freq++; + } else { + s->matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + Assert((ush)dist < (ush)MAX_DIST(s) && + (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++; + s->dyn_dtree[d_code(dist)].Freq++; + } + +#ifdef TRUNCATE_BLOCK + /* Try to guess if it is profitable to stop the current block here */ + if ((s->last_lit & 0x1fff) == 0 && s->level > 2) { + /* Compute an upper bound for the compressed length */ + ulg out_length = (ulg)s->last_lit*8L; + ulg in_length = (ulg)((long)s->strstart - s->block_start); + int dcode; + for (dcode = 0; dcode < D_CODES; dcode++) { + out_length += (ulg)s->dyn_dtree[dcode].Freq * + (5L+extra_dbits[dcode]); + } + out_length >>= 3; + Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", + s->last_lit, in_length, out_length, + 100L - out_length*100L/in_length)); + if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1; + } +#endif + return (s->last_lit == s->lit_bufsize-1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +local void compress_block(s, ltree, dtree) + deflate_state *s; + const ct_data *ltree; /* literal tree */ + const ct_data *dtree; /* distance tree */ +{ + unsigned dist; /* distance of matched string */ + int lc; /* match length or unmatched char (if dist == 0) */ + unsigned lx = 0; /* running index in l_buf */ + unsigned code; /* the code to send */ + int extra; /* number of extra bits to send */ + + if (s->last_lit != 0) do { + dist = s->d_buf[lx]; + lc = s->l_buf[lx++]; + if (dist == 0) { + send_code(s, lc, ltree); /* send a literal byte */ + Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code+LITERALS+1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra != 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra != 0) { + dist -= (unsigned)base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + "pendingBuf overflow"); + + } while (lx < s->last_lit); + + send_code(s, END_BLOCK, ltree); +} + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +local int detect_data_type(s) + deflate_state *s; +{ + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + unsigned long black_mask = 0xf3ffc07fUL; + int n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>= 1) + if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0)) + return Z_BINARY; + + /* Check for textual ("white-listed") bytes. */ + if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0 + || s->dyn_ltree[13].Freq != 0) + return Z_TEXT; + for (n = 32; n < LITERALS; n++) + if (s->dyn_ltree[n].Freq != 0) + return Z_TEXT; + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; +} + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +local unsigned bi_reverse(code, len) + unsigned code; /* the value to invert */ + int len; /* its bit length */ +{ + register unsigned res = 0; + do { + res |= code & 1; + code >>= 1, res <<= 1; + } while (--len > 0); + return res >> 1; +} + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +local void bi_flush(s) + deflate_state *s; +{ + if (s->bi_valid == 16) { + put_short(s, s->bi_buf); + s->bi_buf = 0; + s->bi_valid = 0; + } else if (s->bi_valid >= 8) { + put_byte(s, (Byte)s->bi_buf); + s->bi_buf >>= 8; + s->bi_valid -= 8; + } +} + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +local void bi_windup(s) + deflate_state *s; +{ + if (s->bi_valid > 8) { + put_short(s, s->bi_buf); + } else if (s->bi_valid > 0) { + put_byte(s, (Byte)s->bi_buf); + } + s->bi_buf = 0; + s->bi_valid = 0; +#ifdef ZLIB_DEBUG + s->bits_sent = (s->bits_sent+7) & ~7; +#endif +} diff --git a/Source/Libraries/zlib/uncompr.c b/Source/Libraries/zlib/uncompr.c new file mode 100644 index 0000000..f03a1a8 --- /dev/null +++ b/Source/Libraries/zlib/uncompr.c @@ -0,0 +1,93 @@ +/* uncompr.c -- decompress a memory buffer + * Copyright (C) 1995-2003, 2010, 2014, 2016 Jean-loup Gailly, Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#define ZLIB_INTERNAL +#include "zlib.h" + +/* =========================================================================== + Decompresses the source buffer into the destination buffer. *sourceLen is + the byte length of the source buffer. Upon entry, *destLen is the total size + of the destination buffer, which must be large enough to hold the entire + uncompressed data. (The size of the uncompressed data must have been saved + previously by the compressor and transmitted to the decompressor by some + mechanism outside the scope of this compression library.) Upon exit, + *destLen is the size of the decompressed data and *sourceLen is the number + of source bytes consumed. Upon return, source + *sourceLen points to the + first unused input byte. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, or + Z_DATA_ERROR if the input data was corrupted, including if the input data is + an incomplete zlib stream. +*/ +int ZEXPORT uncompress2 (dest, destLen, source, sourceLen) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong *sourceLen; +{ + z_stream stream; + int err; + const uInt max = (uInt)-1; + uLong len, left; + Byte buf[1]; /* for detection of incomplete stream when *destLen == 0 */ + + len = *sourceLen; + if (*destLen) { + left = *destLen; + *destLen = 0; + } + else { + left = 1; + dest = buf; + } + + stream.next_in = (z_const Bytef *)source; + stream.avail_in = 0; + stream.zalloc = (alloc_func)0; + stream.zfree = (free_func)0; + stream.opaque = (voidpf)0; + + err = inflateInit(&stream); + if (err != Z_OK) return err; + + stream.next_out = dest; + stream.avail_out = 0; + + do { + if (stream.avail_out == 0) { + stream.avail_out = left > (uLong)max ? max : (uInt)left; + left -= stream.avail_out; + } + if (stream.avail_in == 0) { + stream.avail_in = len > (uLong)max ? max : (uInt)len; + len -= stream.avail_in; + } + err = inflate(&stream, Z_NO_FLUSH); + } while (err == Z_OK); + + *sourceLen -= len + stream.avail_in; + if (dest != buf) + *destLen = stream.total_out; + else if (stream.total_out && err == Z_BUF_ERROR) + left = 1; + + inflateEnd(&stream); + return err == Z_STREAM_END ? Z_OK : + err == Z_NEED_DICT ? Z_DATA_ERROR : + err == Z_BUF_ERROR && left + stream.avail_out ? Z_DATA_ERROR : + err; +} + +int ZEXPORT uncompress (dest, destLen, source, sourceLen) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; +{ + return uncompress2(dest, destLen, source, &sourceLen); +} diff --git a/Source/Libraries/zlib/zutil.c b/Source/Libraries/zlib/zutil.c new file mode 100644 index 0000000..a76c6b0 --- /dev/null +++ b/Source/Libraries/zlib/zutil.c @@ -0,0 +1,325 @@ +/* zutil.c -- target dependent utility functions for the compression library + * Copyright (C) 1995-2017 Jean-loup Gailly + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#include "zutil.h" +#ifndef Z_SOLO +# include "gzguts.h" +#endif + +z_const char * const z_errmsg[10] = { + (z_const char *)"need dictionary", /* Z_NEED_DICT 2 */ + (z_const char *)"stream end", /* Z_STREAM_END 1 */ + (z_const char *)"", /* Z_OK 0 */ + (z_const char *)"file error", /* Z_ERRNO (-1) */ + (z_const char *)"stream error", /* Z_STREAM_ERROR (-2) */ + (z_const char *)"data error", /* Z_DATA_ERROR (-3) */ + (z_const char *)"insufficient memory", /* Z_MEM_ERROR (-4) */ + (z_const char *)"buffer error", /* Z_BUF_ERROR (-5) */ + (z_const char *)"incompatible version",/* Z_VERSION_ERROR (-6) */ + (z_const char *)"" +}; + + +const char * ZEXPORT zlibVersion() +{ + return ZLIB_VERSION; +} + +uLong ZEXPORT zlibCompileFlags() +{ + uLong flags; + + flags = 0; + switch ((int)(sizeof(uInt))) { + case 2: break; + case 4: flags += 1; break; + case 8: flags += 2; break; + default: flags += 3; + } + switch ((int)(sizeof(uLong))) { + case 2: break; + case 4: flags += 1 << 2; break; + case 8: flags += 2 << 2; break; + default: flags += 3 << 2; + } + switch ((int)(sizeof(voidpf))) { + case 2: break; + case 4: flags += 1 << 4; break; + case 8: flags += 2 << 4; break; + default: flags += 3 << 4; + } + switch ((int)(sizeof(z_off_t))) { + case 2: break; + case 4: flags += 1 << 6; break; + case 8: flags += 2 << 6; break; + default: flags += 3 << 6; + } +#ifdef ZLIB_DEBUG + flags += 1 << 8; +#endif +#if defined(ASMV) || defined(ASMINF) + flags += 1 << 9; +#endif +#ifdef ZLIB_WINAPI + flags += 1 << 10; +#endif +#ifdef BUILDFIXED + flags += 1 << 12; +#endif +#ifdef DYNAMIC_CRC_TABLE + flags += 1 << 13; +#endif +#ifdef NO_GZCOMPRESS + flags += 1L << 16; +#endif +#ifdef NO_GZIP + flags += 1L << 17; +#endif +#ifdef PKZIP_BUG_WORKAROUND + flags += 1L << 20; +#endif +#ifdef FASTEST + flags += 1L << 21; +#endif +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifdef NO_vsnprintf + flags += 1L << 25; +# ifdef HAS_vsprintf_void + flags += 1L << 26; +# endif +# else +# ifdef HAS_vsnprintf_void + flags += 1L << 26; +# endif +# endif +#else + flags += 1L << 24; +# ifdef NO_snprintf + flags += 1L << 25; +# ifdef HAS_sprintf_void + flags += 1L << 26; +# endif +# else +# ifdef HAS_snprintf_void + flags += 1L << 26; +# endif +# endif +#endif + return flags; +} + +#ifdef ZLIB_DEBUG +#include +# ifndef verbose +# define verbose 0 +# endif +int ZLIB_INTERNAL z_verbose = verbose; + +void ZLIB_INTERNAL z_error (m) + char *m; +{ + fprintf(stderr, "%s\n", m); + exit(1); +} +#endif + +/* exported to allow conversion of error code to string for compress() and + * uncompress() + */ +const char * ZEXPORT zError(err) + int err; +{ + return ERR_MSG(err); +} + +#if defined(_WIN32_WCE) + /* The Microsoft C Run-Time Library for Windows CE doesn't have + * errno. We define it as a global variable to simplify porting. + * Its value is always 0 and should not be used. + */ + int errno = 0; +#endif + +#ifndef HAVE_MEMCPY + +void ZLIB_INTERNAL zmemcpy(dest, source, len) + Bytef* dest; + const Bytef* source; + uInt len; +{ + if (len == 0) return; + do { + *dest++ = *source++; /* ??? to be unrolled */ + } while (--len != 0); +} + +int ZLIB_INTERNAL zmemcmp(s1, s2, len) + const Bytef* s1; + const Bytef* s2; + uInt len; +{ + uInt j; + + for (j = 0; j < len; j++) { + if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1; + } + return 0; +} + +void ZLIB_INTERNAL zmemzero(dest, len) + Bytef* dest; + uInt len; +{ + if (len == 0) return; + do { + *dest++ = 0; /* ??? to be unrolled */ + } while (--len != 0); +} +#endif + +#ifndef Z_SOLO + +#ifdef SYS16BIT + +#ifdef __TURBOC__ +/* Turbo C in 16-bit mode */ + +# define MY_ZCALLOC + +/* Turbo C malloc() does not allow dynamic allocation of 64K bytes + * and farmalloc(64K) returns a pointer with an offset of 8, so we + * must fix the pointer. Warning: the pointer must be put back to its + * original form in order to free it, use zcfree(). + */ + +#define MAX_PTR 10 +/* 10*64K = 640K */ + +local int next_ptr = 0; + +typedef struct ptr_table_s { + voidpf org_ptr; + voidpf new_ptr; +} ptr_table; + +local ptr_table table[MAX_PTR]; +/* This table is used to remember the original form of pointers + * to large buffers (64K). Such pointers are normalized with a zero offset. + * Since MSDOS is not a preemptive multitasking OS, this table is not + * protected from concurrent access. This hack doesn't work anyway on + * a protected system like OS/2. Use Microsoft C instead. + */ + +voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, unsigned items, unsigned size) +{ + voidpf buf; + ulg bsize = (ulg)items*size; + + (void)opaque; + + /* If we allocate less than 65520 bytes, we assume that farmalloc + * will return a usable pointer which doesn't have to be normalized. + */ + if (bsize < 65520L) { + buf = farmalloc(bsize); + if (*(ush*)&buf != 0) return buf; + } else { + buf = farmalloc(bsize + 16L); + } + if (buf == NULL || next_ptr >= MAX_PTR) return NULL; + table[next_ptr].org_ptr = buf; + + /* Normalize the pointer to seg:0 */ + *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4; + *(ush*)&buf = 0; + table[next_ptr++].new_ptr = buf; + return buf; +} + +void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) +{ + int n; + + (void)opaque; + + if (*(ush*)&ptr != 0) { /* object < 64K */ + farfree(ptr); + return; + } + /* Find the original pointer */ + for (n = 0; n < next_ptr; n++) { + if (ptr != table[n].new_ptr) continue; + + farfree(table[n].org_ptr); + while (++n < next_ptr) { + table[n-1] = table[n]; + } + next_ptr--; + return; + } + Assert(0, "zcfree: ptr not found"); +} + +#endif /* __TURBOC__ */ + + +#ifdef M_I86 +/* Microsoft C in 16-bit mode */ + +# define MY_ZCALLOC + +#if (!defined(_MSC_VER) || (_MSC_VER <= 600)) +# define _halloc halloc +# define _hfree hfree +#endif + +voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, uInt items, uInt size) +{ + (void)opaque; + return _halloc((long)items, size); +} + +void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) +{ + (void)opaque; + _hfree(ptr); +} + +#endif /* M_I86 */ + +#endif /* SYS16BIT */ + + +#ifndef MY_ZCALLOC /* Any system without a special alloc function */ + +#ifndef STDC +extern voidp malloc OF((uInt size)); +extern voidp calloc OF((uInt items, uInt size)); +extern void free OF((voidpf ptr)); +#endif + +voidpf ZLIB_INTERNAL zcalloc (opaque, items, size) + voidpf opaque; + unsigned items; + unsigned size; +{ + (void)opaque; + return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) : + (voidpf)calloc(items, size); +} + +void ZLIB_INTERNAL zcfree (opaque, ptr) + voidpf opaque; + voidpf ptr; +{ + (void)opaque; + free(ptr); +} + +#endif /* MY_ZCALLOC */ + +#endif /* !Z_SOLO */ diff --git a/Source/Model/Classes/NMR_KeyStore.cpp b/Source/Model/Classes/NMR_KeyStore.cpp new file mode 100644 index 0000000..4ed9de0 --- /dev/null +++ b/Source/Model/Classes/NMR_KeyStore.cpp @@ -0,0 +1,222 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_KeyStore.cpp implements the KeyStore Class. +A KeyStore is an in memory representation of the 3MF file. + +--*/ + +#include "Model/Classes/NMR_KeyStore.h" +#include "Model/Classes/NMR_KeyStoreConsumer.h" +#include "Model/Classes/NMR_KeyStoreResourceDataGroup.h" +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_PackageResourceID.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_StringUtils.h" +#include +#include + +namespace NMR { + CKeyStore::CKeyStore() { + m_UUID = std::make_shared(); + } + + CKeyStore::~CKeyStore() { + clearAll(); + } + + PUUID CKeyStore::getUUID() + { + return m_UUID; + } + + void CKeyStore::setUUID(PUUID uuid) + { + m_UUID = uuid; + } + + void CKeyStore::addConsumer(PKeyStoreConsumer const & consumer) + { + std::lock_guard guard(mtx); + if (m_Consumers.size() >= XML_3MF_SECURE_CONTENT_MAXELEMENTCOUNT) + throw CNMRException(NMR_ERROR_KEYSTORETOOMANYELEMENTS); + + std::string const id = consumer->getConsumerID(); + if (m_ConsumerRefs.find(id) != m_ConsumerRefs.end()) { + throw CNMRException(NMR_ERROR_KEYSTOREDUPLICATECONSUMER); + } + m_Consumers.push_back(consumer); + m_ConsumerRefs[id] = consumer; + } + + nfUint64 CKeyStore::getConsumerCount() const + { + return m_Consumers.size(); + } + + PKeyStoreConsumer CKeyStore::getConsumer(nfUint64 index) const + { + if (index >= m_Consumers.size()) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + return m_Consumers[(size_t)index]; + } + + PKeyStoreConsumer CKeyStore::findConsumerById(std::string id) + { + auto ref = m_ConsumerRefs.find(id); + if ( ref != m_ConsumerRefs.end()) + return (*ref).second; + return nullptr; + } + + void CKeyStore::removeConsumer(NMR::PKeyStoreConsumer consumer) + { + std::lock_guard guard(mtx); + size_t n = m_ConsumerRefs.erase(consumer->getConsumerID()); + if (n > 0) { + for (auto it : m_ResourceDataGroups) { + it->removeAccessRight(consumer->getConsumerID()); + } + auto found = std::find(m_Consumers.begin(), m_Consumers.end(), consumer); + m_Consumers.erase(found); + } + } + + nfUint64 CKeyStore::getResourceDataGroupCount() const + { + return m_ResourceDataGroups.size(); + } + + PKeyStoreResourceDataGroup CKeyStore::getResourceDataGroup(nfUint64 index) const { + if (index < m_ResourceDataGroups.size()) + return m_ResourceDataGroups[(size_t)index]; + throw CNMRException(NMR_ERROR_INVALIDINDEX); + } + + void CKeyStore::addResourceDataGroup(PKeyStoreResourceDataGroup const & dataGroup) + { + std::lock_guard guard(mtx); + + if (m_ResourceDataGroups.size() >= XML_3MF_SECURE_CONTENT_MAXELEMENTCOUNT) + throw CNMRException(NMR_ERROR_KEYSTORETOOMANYELEMENTS); + + PUUID const keyUUID = dataGroup->getKeyUUID(); + if (m_ResourceDataGroupsRefs.find(keyUUID) != m_ResourceDataGroupsRefs.end()) { + throw CNMRException(NMR_ERROR_KEYSTOREDUPLICATERESOURCEDATAGROUP); + } + m_ResourceDataGroups.push_back(dataGroup); + m_ResourceDataGroupsRefs[keyUUID] = dataGroup; + } + + PKeyStoreResourceDataGroup CKeyStore::findResourceDataGroupByResourceDataPath(PPackageModelPath const & rdPath) { + auto found = findResourceData(rdPath); + if (nullptr != found) + return found->getGroup(); + return nullptr; + } + + void CKeyStore::removeResourceDataGroup(PKeyStoreResourceDataGroup rdg) { + throw CNMRException(NMR_ERROR_NOTIMPLEMENTED); + } + + nfUint64 CKeyStore::addResourceData(PKeyStoreResourceData const & rd) { + std::lock_guard guard(mtx); + + if (m_ResourceDatas.size() >= XML_3MF_SECURE_CONTENT_MAXELEMENTCOUNT) + throw CNMRException(NMR_ERROR_KEYSTORETOOMANYELEMENTS); + + if (nullptr == rd->getGroup()) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + auto found = m_ResourceDataRefs.find(rd->packagePath()); + if (found != m_ResourceDataRefs.end()) + throw CNMRException(NMR_ERROR_KEYSTOREDUPLICATERESOURCEDATA); + + m_ResourceDatas.push_back(rd); + m_ResourceDataRefs[rd->packagePath()] = rd; + return m_ResourceDatas.size() - 1; + } + + void CKeyStore::removeResourceData(NMR::PKeyStoreResourceData const & rd) { + std::lock_guard guard(mtx); + size_t n = m_ResourceDataRefs.erase(rd->packagePath()); + if (n > 0) { + auto found = std::find(m_ResourceDatas.begin(), m_ResourceDatas.end(), rd); + m_ResourceDatas.erase(found); + } + } + + nfUint64 CKeyStore::getResourceDataCount() { + return m_ResourceDatas.size(); + } + + PKeyStoreResourceData CKeyStore::getResourceData(nfUint64 index) const { + if (index < m_ResourceDatas.size()) + return m_ResourceDatas[(size_t)index]; + throw CNMRException(NMR_ERROR_INVALIDINDEX); + } + + PKeyStoreResourceData CKeyStore::findResourceData(PPackageModelPath const & path) { + auto found = m_ResourceDataRefs.find(path); + if (found != m_ResourceDataRefs.end()) + return (*found).second; + return nullptr; + } + + std::vector CKeyStore::getResourceDataByGroup(PKeyStoreResourceDataGroup const & rdg) const { + throw CNMRException(NMR_ERROR_NOTIMPLEMENTED); + } + + PKeyStoreResourceDataGroup CKeyStore::findResourceDataGroupByResourceDataPath(std::string const & rdPath) { + PKeyStoreResourceData rd = findResourceData(rdPath); + if (nullptr != rd) + return rd->getGroup(); + return nullptr; + } + + PKeyStoreResourceData CKeyStore::findResourceData(std::string const & path) { + auto found = std::find_if(m_ResourceDatas.begin(), m_ResourceDatas.end(), [&path](PKeyStoreResourceData const & rd) { + return rd->packagePath()->getPath() == path; + }); + if (found != m_ResourceDatas.end()) + return *found; + return nullptr; + } + + bool CKeyStore::empty() const { + return m_Consumers.empty() && m_ResourceDataGroups.empty(); + } + + void CKeyStore::clearAll() { + m_ConsumerRefs.clear(); + m_Consumers.clear(); + m_ResourceDataGroupsRefs.clear(); + m_ResourceDataGroups.clear(); + } + +} \ No newline at end of file diff --git a/Source/Model/Classes/NMR_KeyStoreAccessRight.cpp b/Source/Model/Classes/NMR_KeyStoreAccessRight.cpp new file mode 100644 index 0000000..0e5a878 --- /dev/null +++ b/Source/Model/Classes/NMR_KeyStoreAccessRight.cpp @@ -0,0 +1,49 @@ +#include "Model/Classes/NMR_KeyStoreAccessRight.h" +#include "Common/NMR_Exception.h" +namespace NMR { + CKeyStoreAccessRight::CKeyStoreAccessRight( + PKeyStoreConsumer const & consumer, + eKeyStoreWrapAlgorithm const algorithm, + eKeyStoreMaskGenerationFunction const mgf, + eKeyStoreMessageDigest const digest, + std::vector const & cipherValue) + :m_pConsumer(consumer), m_eAlgorithm(algorithm), m_eMgf(mgf), m_eDigest(digest), m_rgCipherValue(cipherValue) + { + if (nullptr == m_pConsumer) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + if (algorithm != eKeyStoreWrapAlgorithm::RSA_OAEP) { + throw CNMRException(NMR_ERROR_KEYSTOREUNSUPPORTEDALGORITHM); + } + + if (mgf != eKeyStoreMaskGenerationFunction::MGF1_SHA1 + && mgf != eKeyStoreMaskGenerationFunction::MGF1_SHA256) { + throw CNMRException(NMR_ERROR_KEYSTOREUNSUPPORTEDALGORITHM); + } + + if (digest != eKeyStoreMessageDigest::SHA1 + && digest != eKeyStoreMessageDigest::SHA256) + throw CNMRException(NMR_ERROR_KEYSTOREUNSUPPORTEDALGORITHM); + } + PKeyStoreConsumer CKeyStoreAccessRight::getConsumer() const { + return m_pConsumer; + } + eKeyStoreWrapAlgorithm CKeyStoreAccessRight::getAlgorithm() const { + return m_eAlgorithm; + } + eKeyStoreMaskGenerationFunction CKeyStoreAccessRight::getMgf() const { + return m_eMgf; + } + eKeyStoreMessageDigest CKeyStoreAccessRight::getDigest() const { + return m_eDigest; + } + std::vector const & CKeyStoreAccessRight::getCipherValue() const { + return m_rgCipherValue; + } + void CKeyStoreAccessRight::setCipherValue(std::vector const & cv) { + m_rgCipherValue = cv; + } + nfBool CKeyStoreAccessRight::isNew() const { + return m_rgCipherValue.empty(); + } +} \ No newline at end of file diff --git a/Source/Model/Classes/NMR_KeyStoreCEKParams.cpp b/Source/Model/Classes/NMR_KeyStoreCEKParams.cpp new file mode 100644 index 0000000..6c41421 --- /dev/null +++ b/Source/Model/Classes/NMR_KeyStoreCEKParams.cpp @@ -0,0 +1,54 @@ +#include "Model/Classes/NMR_KeyStoreCEKParams.h" + +namespace NMR { + CKeyStoreCEKParams::CKeyStoreCEKParams( + nfBool const & compression, + eKeyStoreEncryptAlgorithm const & encryptionAlgorithm, + std::vector const & iv, + std::vector const & tag, + std::vector const & aad, + nfUint64 descriptor): m_bCompression(compression), m_eAlgorithm(encryptionAlgorithm), m_rgIv(iv), m_rgTag(tag), m_rgAad(aad), m_nDescriptor(descriptor) + { + } + + eKeyStoreEncryptAlgorithm CKeyStoreCEKParams::getEncryptionAlgorithm() const { + return m_eAlgorithm; + } + nfBool CKeyStoreCEKParams::isCompressed() const { + return m_bCompression; + } + std::vector const & CKeyStoreCEKParams::getInitVector() const { + return m_rgIv; + } + std::vector const & CKeyStoreCEKParams::getAuthTag() const { + return m_rgTag; + } + std::vector const & CKeyStoreCEKParams::getAddAuthData() const { + return m_rgAad; + } + nfUint64 CKeyStoreCEKParams::getDescriptor() const { + return m_nDescriptor; + } + void CKeyStoreCEKParams::setAuthTag(std::vector const & buf) { + m_rgTag = buf; + } + void CKeyStoreCEKParams::setAddAuthData(std::vector const & buf) { + m_rgAad = buf; + } + + + + CKeyStoreContentEncryptionParams::CKeyStoreContentEncryptionParams( + nfBool const & compression, + eKeyStoreEncryptAlgorithm const & encryptionAlgorithm, + std::vector const & key, + std::vector const & iv, + std::vector const & tag, + std::vector const & aad, + nfUint64 descriptor) : CKeyStoreCEKParams(compression, encryptionAlgorithm, iv, tag, aad, descriptor), m_rgKey(key) {} + + std::vector const & CKeyStoreContentEncryptionParams::getKey() const { + return m_rgKey; + } + +} diff --git a/Source/Model/Classes/NMR_KeyStoreConsumer.cpp b/Source/Model/Classes/NMR_KeyStoreConsumer.cpp new file mode 100644 index 0000000..5d062e2 --- /dev/null +++ b/Source/Model/Classes/NMR_KeyStoreConsumer.cpp @@ -0,0 +1,40 @@ +#include "Model/Classes/NMR_KeyStoreConsumer.h" +namespace NMR { + + CKeyStoreConsumer::CKeyStoreConsumer(std::string const & consumerID, std::string const & keyID, std::string keyValue) + { + m_sConsumerID = consumerID; + m_sKeyID = keyID; + m_sKeyValue = keyValue; + } + + std::string CKeyStoreConsumer::getConsumerID() const { + return m_sConsumerID; + } + + std::string CKeyStoreConsumer::getKeyID() const { + return m_sKeyID; + } + + void CKeyStoreConsumer::setKeyID(std::string const & keyID) { + m_sKeyID = keyID; + } + + nfBool CKeyStoreConsumer::hasKeyID() const { + return !m_sKeyID.empty(); + } + + std::string CKeyStoreConsumer::getKeyValue() const + { + return m_sKeyValue; + } + + void CKeyStoreConsumer::setKeyValue(std::string const & keyValue) + { + m_sKeyValue = keyValue; + } + + nfBool CKeyStoreConsumer::hasKeyValue() const { + return !m_sKeyValue.empty(); + } +} diff --git a/Source/Model/Classes/NMR_KeyStoreFactory.cpp b/Source/Model/Classes/NMR_KeyStoreFactory.cpp new file mode 100644 index 0000000..06298ca --- /dev/null +++ b/Source/Model/Classes/NMR_KeyStoreFactory.cpp @@ -0,0 +1,55 @@ + + +#include "Model/Classes/NMR_KeyStoreFactory.h" +#include "Model/Classes/NMR_Model.h" +#include "Model/Classes/NMR_KeyStore.h" +#include "Model/Classes/NMR_KeyStoreConsumer.h" +#include "Model/Classes/NMR_KeyStoreResourceDataGroup.h" +#include "Model/Classes/NMR_KeyStoreAccessRight.h" +#include "Model/Classes/NMR_KeyStoreResourceData.h" +#include "Model/Classes/NMR_KeyStoreCEKParams.h" +#include "Common/NMR_StringUtils.h" + +namespace NMR { + PKeyStore CKeyStoreFactory::makeKeyStore() { + return std::make_shared(); + } + + PKeyStoreResourceDataGroup CKeyStoreFactory::makeResourceDataGroup(PUUID const & keyUUID, std::vector const & key) { + PUUID uuid = (nullptr != keyUUID) ? keyUUID : std::make_shared(); + return std::make_shared(uuid, key); + } + + PKeyStoreConsumer CKeyStoreFactory::makeConsumer(std::string const & consumerID, std::string const & keyId, std::string const & keyValue) { + return std::make_shared(consumerID, keyId, keyValue); + } + + PKeyStoreAccessRight CKeyStoreFactory::makeAccessRight(PKeyStoreConsumer const & consumer, eKeyStoreWrapAlgorithm const algorithm, eKeyStoreMaskGenerationFunction const mask, eKeyStoreMessageDigest const digest, std::vector const & cipherValue) { + return std::make_shared(consumer, algorithm, mask, digest, cipherValue); + } + + PKeyStoreResourceData CKeyStoreFactory::makeResourceData(PKeyStoreResourceDataGroup const & rdg, PPackageModelPath const & path, PKeyStoreCEKParams params) { + return std::make_shared(rdg, path, + params->isCompressed(), + params->getEncryptionAlgorithm(), + params->getInitVector(), + params->getAuthTag(), + params->getAddAuthData()); + } + + PKeyStoreContentEncryptionParams CKeyStoreFactory::makeContentEncryptionParams(PKeyStoreResourceData rd, PKeyStoreResourceDataGroup rdg) { + return std::make_shared( + rd->isCompressed(), + rd->getEncryptionAlgorithm(), + rdg->getKey(), + rd->getInitVector(), + rd->getAuthTag(), + rd->getAddAuthData(), + rd->getDescriptor() + ); + } + + PKeyStoreCEKParams CKeyStoreFactory::makeCEKParams(nfBool compressed, eKeyStoreEncryptAlgorithm algorithm, std::vector const & aad, std::vector const & iv, std::vector const & tag) { + return std::make_shared(compressed, algorithm, iv, tag, aad, 0); + } +} \ No newline at end of file diff --git a/Source/Model/Classes/NMR_KeyStoreResourceData.cpp b/Source/Model/Classes/NMR_KeyStoreResourceData.cpp new file mode 100644 index 0000000..7d27c9d --- /dev/null +++ b/Source/Model/Classes/NMR_KeyStoreResourceData.cpp @@ -0,0 +1,30 @@ +#include "Model/Classes/NMR_KeyStoreResourceData.h" +#include "Common/NMR_Exception.h" +#include + +namespace NMR { + + + nfUint64 CKeyStoreResourceData::s_nfHandleCount = 0; + + CKeyStoreResourceData::CKeyStoreResourceData( + PKeyStoreResourceDataGroup const & rdg, + PPackageModelPath const& path, + bool compression, + eKeyStoreEncryptAlgorithm alg, + std::vector const & iv, + std::vector const & tag, + std::vector const & aad) + : CKeyStoreCEKParams(compression, alg, iv, tag, aad, ++s_nfHandleCount), + m_pGroup(rdg), m_pPath(path) + { + } + + void CKeyStoreResourceData::setInitVector(std::vector const & newIV) { + m_rgIv = newIV; + } + + void CKeyStoreResourceData::setAuthTag(std::vector const & newTag) { + m_rgTag = newTag; + } +} diff --git a/Source/Model/Classes/NMR_KeyStoreResourceDataGroup.cpp b/Source/Model/Classes/NMR_KeyStoreResourceDataGroup.cpp new file mode 100644 index 0000000..f213b7b --- /dev/null +++ b/Source/Model/Classes/NMR_KeyStoreResourceDataGroup.cpp @@ -0,0 +1,83 @@ +#include "Model/Classes/NMR_KeyStoreResourceDataGroup.h" +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_Exception.h" +#include + +namespace NMR { + + CKeyStoreResourceDataGroup::CKeyStoreResourceDataGroup(PUUID const& keyUUID, std::vector const & key) + { + m_sKeyUUID = keyUUID; + m_rgKey = key; + } + + void CKeyStoreResourceDataGroup::removeAccessRight(std::string const & consumerId) + { + std::lock_guard guard(mtx); + + if (consumerId.empty()) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + size_t n = m_ConsumerAccesstRight.erase(consumerId); + if (n > 0) { + auto it = m_AccessRights.begin(); + while (it != m_AccessRights.end()) { + if ((*it)->getConsumer()->getConsumerID() == consumerId) { + it = m_AccessRights.erase(it); + } + } + } + } + + PUUID CKeyStoreResourceDataGroup::getKeyUUID() const { + return m_sKeyUUID; + } + + nfUint64 CKeyStoreResourceDataGroup::addAccessRight(PKeyStoreAccessRight const & ar) + { + std::lock_guard guard(mtx); + + if (m_AccessRights.size() >= XML_3MF_SECURE_CONTENT_MAXELEMENTCOUNT) + throw CNMRException(NMR_ERROR_KEYSTORETOOMANYELEMENTS); + + std::string consumerId = ar->getConsumer()->getConsumerID(); + if (m_ConsumerAccesstRight.find(consumerId) != m_ConsumerAccesstRight.end()) { + throw CNMRException(NMR_ERROR_KEYSTOREDUPLICATEACCESSRIGHT); + } + + m_AccessRights.push_back(ar); + nfUint64 elIdx = m_AccessRights.size() - 1; + m_ConsumerAccesstRight[consumerId] = ar; + return elIdx; + } + + nfUint64 CKeyStoreResourceDataGroup::getAccessRightCount() + { + return m_AccessRights.size(); + } + + PKeyStoreAccessRight CKeyStoreResourceDataGroup::getAccessRight(nfUint64 index) const + { + if (index >= m_AccessRights.size()) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + return m_AccessRights[(size_t)index]; + } + + PKeyStoreAccessRight CKeyStoreResourceDataGroup::findAccessRightByConsumerID(std::string const & consumerId) const + { + if (consumerId.empty()) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + auto found = m_ConsumerAccesstRight.find(consumerId); + if (found != m_ConsumerAccesstRight.end()) + return (*found).second; + return nullptr; + } + + std::vector const & CKeyStoreResourceDataGroup::getKey() const { + return m_rgKey; + } + + void CKeyStoreResourceDataGroup::setKey(std::vector const & key) { + m_rgKey = key; + } + +} diff --git a/Source/Model/Classes/NMR_Model.cpp b/Source/Model/Classes/NMR_Model.cpp new file mode 100644 index 0000000..3a92be9 --- /dev/null +++ b/Source/Model/Classes/NMR_Model.cpp @@ -0,0 +1,1318 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_Model.cpp implements the Model Class. +A model is an in memory representation of the 3MF file. + +--*/ + +#include "Model/Classes/NMR_Model.h" +#include "Model/Classes/NMR_ModelObject.h" +#include "Model/Classes/NMR_ModelMeshObject.h" +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_ModelTypes.h" +#include "Model/Classes/NMR_ModelAttachment.h" +#include "Model/Classes/NMR_ModelTextureAttachment.h" +#include "Model/Classes/NMR_ModelBuildItem.h" +#include "Model/Classes/NMR_ModelBaseMaterials.h" +#include "Model/Classes/NMR_ModelColorGroup.h" +#include "Model/Classes/NMR_ModelTexture2DGroup.h" +#include "Model/Classes/NMR_ModelCompositeMaterials.h" +#include "Model/Classes/NMR_ModelMultiPropertyGroup.h" +#include "Model/Classes/NMR_ModelTexture2D.h" +#include "Model/Classes/NMR_ModelSliceStack.h" +#include "Model/Classes/NMR_ModelMetaDataGroup.h" +#include "Model/Classes/NMR_KeyStore.h" + +#include "Common/Mesh/NMR_Mesh.h" +#include "Common/MeshInformation/NMR_MeshInformation.h" +#include "Common/MeshInformation/NMR_MeshInformation_Properties.h" +#include "Common/NMR_Exception.h" +#include +#include +#include +#include +#include + +#include "Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceRefModel.h" +#include "Common/Platform/NMR_XmlReader.h" +#include "Common/Platform/NMR_Platform.h" +#include "Common/Platform/NMR_ImportStream_Unique_Memory.h" + +#include "Common/NMR_StringUtils.h" + +#include "Model/Classes/NMR_KeyStoreFactory.h" + +namespace NMR { + + CModel::CModel() + { + m_Unit = MODELUNIT_MILLIMETER; + m_sLanguage = XML_3MF_LANG_US; + m_nHandleCounter = 1; + m_pPath = m_resourceHandler.makePackageModelPath(PACKAGE_3D_MODEL_URI); + m_pCurPath = m_pPath; + m_pKeyStore = CKeyStoreFactory::makeKeyStore(); + + setBuildUUID(std::make_shared()); + + m_MetaDataGroup = std::make_shared(); + } + + CModel::~CModel() + { + clearAll(); + } + + PPackageModelPath CModel::currentModelPath() + { + return m_pCurPath; + } + + const std::string CModel::currentPath() + { + return m_pCurPath->getPath(); + } + + void CModel::setCurrentPath(const std::string sPath) + { + if (PPackageModelPath pModelPath = m_resourceHandler.findPackageModelPath(sPath)) { + m_pCurPath = pModelPath; + } + else { + m_pCurPath = m_resourceHandler.makePackageModelPath(sPath); + } + } + + PPackageModelPath CModel::rootModelPath() + { + return m_pPath; + } + + const std::string CModel::rootPath() + { + return m_pPath->getPath(); + } + + void CModel::setRootPath(const std::string sPath) + { + m_pPath->setPath(sPath); + } + + PPackageModelPath CModel::findOrCreateModelPath(std::string sPath) + { + if (PPackageModelPath pModelPath = m_resourceHandler.findPackageModelPath(sPath)) { + return pModelPath; + } + return m_resourceHandler.makePackageModelPath(sPath); + } + + std::vector CModel::retrieveAllModelPaths() + { + return m_resourceHandler.retrieveAllModelPaths(); + } + + // Merge all build items into one mesh + void CModel::mergeToMesh(_In_ CMesh * pMesh) + { + for (auto iIterator = m_BuildItems.begin(); iIterator != m_BuildItems.end(); iIterator++) { + (*iIterator)->mergeToMesh(pMesh); + } + } + + // Units setter/getter + void CModel::setUnit(_In_ eModelUnit Unit) + { + m_Unit = Unit; + } + + void CModel::setUnitString(_In_ std::string sUnitString) + { + const nfChar * pUnitName = sUnitString.c_str(); + + if (strcmp(pUnitName, XML_3MF_MODELUNIT_MICROMETER) == 0) + setUnit(MODELUNIT_MICROMETER); + else if (strcmp(pUnitName, XML_3MF_MODELUNIT_MILLIMETER) == 0) + setUnit(MODELUNIT_MILLIMETER); + else if (strcmp(pUnitName, XML_3MF_MODELUNIT_CENTIMETER) == 0) + setUnit(MODELUNIT_CENTIMETER); + else if (strcmp(pUnitName, XML_3MF_MODELUNIT_INCH) == 0) + setUnit(MODELUNIT_INCH); + else if (strcmp(pUnitName, XML_3MF_MODELUNIT_FOOT) == 0) + setUnit(MODELUNIT_FOOT); + else if (strcmp(pUnitName, XML_3MF_MODELUNIT_METER) == 0) + setUnit(MODELUNIT_METER); + else + throw CNMRException(NMR_ERROR_INVALIDMODELUNIT); + } + + std::string CModel::getUnitString() + { + switch (m_Unit) { + case MODELUNIT_MICROMETER: + return XML_3MF_MODELUNIT_MICROMETER; + case MODELUNIT_MILLIMETER: + return XML_3MF_MODELUNIT_MILLIMETER; + case MODELUNIT_CENTIMETER: + return XML_3MF_MODELUNIT_CENTIMETER; + case MODELUNIT_INCH: + return XML_3MF_MODELUNIT_INCH; + case MODELUNIT_FOOT: + return XML_3MF_MODELUNIT_FOOT; + case MODELUNIT_METER: + return XML_3MF_MODELUNIT_METER; + default: + return ""; + } + } + + eModelUnit CModel::getUnit() + { + return m_Unit; + } + + // Language setter/getter + void CModel::setLanguage(_In_ std::string sLanguage) + { + m_sLanguage = sLanguage; + } + + std::string CModel::getLanguage() + { + return m_sLanguage; + } + + // General Resource Handling + PModelResource CModel::findResource(_In_ std::string path, ModelResourceID nID) + { + PPackageResourceID pID = m_resourceHandler.findResourceIDByPair(path, nID); + if (pID.get()) + return findResource(pID); + else + return nullptr; + } + + PModelResource CModel::findResource(_In_ UniqueResourceID nID) + { + PPackageResourceID pID = m_resourceHandler.findResourceIDByUniqueID(nID); + if (pID.get()) + return findResource(pID); + else + return nullptr; + } + + PModelResource CModel::findResource(_In_ PPackageResourceID pID) + { + UniqueResourceID uID = pID->getUniqueID(); + + auto iIterator = m_ResourceMap.find(uID); + if (iIterator != m_ResourceMap.end()) { + return iIterator->second; + } + return nullptr; + } + + PPackageResourceID CModel::findPackageResourceID(_In_ std::string path, ModelResourceID nID) + { + return m_resourceHandler.findResourceIDByPair(path, nID); + } + PPackageResourceID CModel::findPackageResourceID(_In_ UniqueResourceID nID) + { + return m_resourceHandler.findResourceIDByUniqueID(nID); + } + + nfUint32 CModel::getResourceCount() + { + return (nfUint32)m_Resources.size(); + } + + PModelResource CModel::getResource(_In_ nfUint32 nIndex) + { + if (nIndex >= (nfUint32)m_Resources.size()) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + + return m_Resources[nIndex]; + } + + void CModel::addResource(_In_ PModelResource pResource) + { + if (!pResource.get()) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + // Check for resource count overflow + if (getMetaDataCount() > XML_3MF_MAXRESOURCECOUNT) + throw CNMRException(NMR_ERROR_INVALIDRESOURCECOUNT); + + // Check if ID already exists + UniqueResourceID nID = pResource->getPackageResourceID()->getUniqueID(); + auto iIterator = m_ResourceMap.find(nID); + if (iIterator != m_ResourceMap.end()) + throw CNMRException(NMR_ERROR_DUPLICATEMODELRESOURCE); + + // Add ID to objects + m_ResourceMap.insert(std::make_pair(nID, pResource)); + m_Resources.push_back(pResource); + + // Create correct lookup table + addResourceToLookupTable(pResource); + } + + // Metadata setter/getter + PModelMetaData CModel::addMetaData(_In_ std::string sNameSpace, _In_ std::string sName, _In_ std::string sValue, _In_ std::string sType, _In_ nfBool bPreserve) + { + return m_MetaDataGroup->addMetaData(sNameSpace, sName, sValue, sType, bPreserve); + } + + nfUint32 CModel::getMetaDataCount() + { + return m_MetaDataGroup->getMetaDataCount(); + } + + PModelMetaData CModel::getMetaData(_In_ nfUint32 nIndex) + { + return m_MetaDataGroup->getMetaData(nIndex); + } + + void CModel::removeMetaData(_In_ nfUint32 nIndex) + { + m_MetaDataGroup->removeMetaData(nIndex); + } + + nfBool CModel::hasMetaData(_In_ std::string sKey) + { + return m_MetaDataGroup->hasMetaData(sKey); + } + + void CModel::mergeMetaData(_In_ CModel * pSourceModel) + { + if (!pSourceModel) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + m_MetaDataGroup->mergeMetaData(pSourceModel->m_MetaDataGroup.get()); + } + + PModelMetaDataGroup CModel::getMetaDataGroup() + { + return m_MetaDataGroup; + } + + // Build Handling + void CModel::addBuildItem(_In_ PModelBuildItem pBuildItem) + { + if (!pBuildItem.get()) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + if (m_BuildItems.size() >= XML_3MF_MAXBUILDITEMCOUNT) + throw CNMRException(NMR_ERROR_INVALIDBUILDITEMCOUNT); + m_BuildItems.push_back(pBuildItem); + } + + nfUint32 CModel::getBuildItemCount() + { + return (nfUint32)m_BuildItems.size(); + } + + PModelBuildItem CModel::getBuildItem(_In_ nfUint32 nIdx) + { + if (nIdx > (nfUint32)m_BuildItems.size()) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + return m_BuildItems[nIdx]; + } + + void CModel::removeBuildItem(_In_ nfUint32 nHandle, _In_ nfBool bThrowExceptionIfNotFound) + { + auto iIterator = m_BuildItems.begin(); + while (iIterator != m_BuildItems.end()) { + if ((*iIterator)->getHandle() == nHandle) { + m_BuildItems.erase(iIterator); + return; + } + iIterator++; + } + + if (bThrowExceptionIfNotFound) + throw CNMRException(NMR_ERROR_BUILDITEMNOTFOUND); + } + + PUUID CModel::buildUUID() + { + return m_buildUUID; + } + + void CModel::setBuildUUID(PUUID pUUID) + { + registerUUID(pUUID); + unRegisterUUID(m_buildUUID); + m_buildUUID = pUUID; + } + + void CModel::unRegisterUUID(PUUID pUUID) + { + if (pUUID.get()) { + usedUUIDs.erase(pUUID->toString()); + } + } + + void CModel::registerUUID(PUUID pUUID) + { + if (pUUID.get()) { + std::string value = pUUID->toString(); + + auto it = usedUUIDs.find(value); + if (it != usedUUIDs.end()) { + throw CNMRException(NMR_ERROR_UUID_NOT_UNIQUE); + } + else { + usedUUIDs[value] = pUUID; + } + } + } + + + // Retrieve a unique Resource ID + ModelResourceID CModel::generateResourceID() + { + // TODO: is this truly safe? + auto iIterator = m_ResourceMap.rbegin(); + if (iIterator != m_ResourceMap.rend()) + return iIterator->first + 1; + else + return 1; + } + + void CModel::updateUniqueResourceID(UniqueResourceID nOldID, UniqueResourceID nNewID) + { + if (m_ResourceMap.find(nNewID) != m_ResourceMap.end()) { + throw CNMRException(NMR_ERROR_DUPLICATEMODELRESOURCE); + } + else + { + auto iIterator = m_ResourceMap.find(nOldID); + if (iIterator == m_ResourceMap.end()) { + throw CNMRException(NMR_ERROR_INVALIDMODELRESOURCE); + } + m_ResourceMap.insert(std::make_pair<>(nNewID, iIterator->second)); + m_ResourceMap.erase(m_ResourceMap.find(nOldID)); + } + } + + PPackageResourceID CModel::generatePackageResourceID(_In_ std::string path, ModelResourceID nID) + { + return m_resourceHandler.makePackageResourceID(path, nID); + } + + void CModel::removePackageResourceID(PPackageResourceID pID) + { + m_resourceHandler.removePackageResourceID(pID); + } + + // Convenience functions for objects + _Ret_maybenull_ CModelObject * CModel::findObject(_In_ UniqueResourceID nResourceID) + { + PModelResource pResource = findResource(nResourceID); + if (pResource != nullptr) { + CModelObject * pModelObject = dynamic_cast (pResource.get()); + if (pModelObject == nullptr) + throw CNMRException (NMR_ERROR_RESOURCETYPEMISMATCH); + + return pModelObject; + } + + return nullptr; + } + + nfUint32 CModel::getObjectCount() + { + return (nfUint32)m_ObjectLookup.size(); + } + + PModelResource CModel::getObjectResource(_In_ nfUint32 nIndex) + { + nfUint32 nCount = getObjectCount(); + if (nIndex >= nCount) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + + return m_ObjectLookup[nIndex]; + } + + // Returns 0: if equal, 1 if A before B, -1 if A after B + nfInt32 CModel::compareObjectsByResourceID(CModelResource* pObjectResourceA, CModelResource* pObjectResourceB) + { + nfUint32 nCount = getObjectCount(); + if ( (pObjectResourceA == nullptr) || (pObjectResourceB == nullptr) ) + throw CNMRException(NMR_ERROR_INVALIDPOINTER); + + nfInt32 indexA = -1; + nfInt32 indexB = -1; + + for (nfUint32 i = 0; i < nCount; i++) { + if (m_ObjectLookup[i].get() == pObjectResourceA) { + indexA = i; + } + if (m_ObjectLookup[i].get() == pObjectResourceB) { + indexB = i; + } + } + + if ( (indexA==-1) || (indexB == -1)) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + if (indexA < indexB) return 1; + if (indexA > indexB) return -1; + return 0; + } + + CModelObject * CModel::getObject(_In_ nfUint32 nIndex) + { + CModelObject * pModelObject = dynamic_cast (getObjectResource(nIndex).get()); + if (pModelObject == nullptr) + throw CNMRException(NMR_ERROR_RESOURCETYPEMISMATCH); + + return pModelObject; + } + + // Add Resource to resource lookup tables + void CModel::addResourceToLookupTable(_In_ PModelResource pResource) + { + if (pResource.get() == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + // Add to lookup tables + CModelObject * pModelObject = dynamic_cast (pResource.get()); + if (pModelObject != nullptr) + m_ObjectLookup.push_back(pResource); + + CModelBaseMaterialResource * pBaseMaterial = dynamic_cast (pResource.get()); + if (pBaseMaterial != nullptr) + m_BaseMaterialLookup.push_back(pResource); + + CModelColorGroupResource * pColorGroup = dynamic_cast (pResource.get()); + if (pColorGroup != nullptr) + m_ColorGroupLookup.push_back(pResource); + + CModelTexture2DResource * pTexture2D = dynamic_cast (pResource.get()); + if (pTexture2D != nullptr) + m_TextureLookup.push_back(pResource); + + CModelTexture2DGroupResource * pTexture2DGroup = dynamic_cast (pResource.get()); + if (pTexture2DGroup != nullptr) + m_Texture2DGroupLookup.push_back(pResource); + + CModelCompositeMaterialsResource * pCompositeMaterials = dynamic_cast (pResource.get()); + if (pCompositeMaterials != nullptr) + m_CompositeMaterialsLookup.push_back(pResource); + + CModelMultiPropertyGroupResource * pMultiPropertyGroup = dynamic_cast (pResource.get()); + if (pMultiPropertyGroup != nullptr) + m_MultiPropertyGroupLookup.push_back(pResource); + + CModelSliceStack *pSliceStack = dynamic_cast(pResource.get()); + if (pSliceStack != nullptr) + m_SliceStackLookup.push_back(pResource); + } + + // Clear all build items and Resources + void CModel::clearAll() + { + m_pPackageThumbnailAttachment = nullptr; + + m_MetaDataGroup->clear(); + m_ObjectLookup.clear(); + m_BaseMaterialLookup.clear(); + m_ColorGroupLookup.clear(); + m_BuildItems.clear(); + m_ResourceMap.clear(); + m_Resources.clear(); + m_TextureLookup.clear(); + m_SliceStackLookup.clear(); + m_CompositeMaterialsLookup.clear(); + m_MultiPropertyGroupLookup.clear(); + + m_MetaDataGroup->clear(); + } + + _Ret_maybenull_ PModelBaseMaterialResource CModel::findBaseMaterial(_In_ PPackageResourceID pID) + { + PModelResource pResource = findResource(pID); + if (pResource != nullptr) { + PModelBaseMaterialResource pBaseMaterialResource = std::dynamic_pointer_cast(pResource); + if (pBaseMaterialResource.get() == nullptr) + throw CNMRException(NMR_ERROR_RESOURCETYPEMISMATCH); + return pBaseMaterialResource; + } + return nullptr; + } + + nfUint32 CModel::getBaseMaterialCount() + { + return (nfUint32)m_BaseMaterialLookup.size(); + } + + PModelResource CModel::getBaseMaterialResource(_In_ nfUint32 nIndex) + { + nfUint32 nCount = getBaseMaterialCount(); + if (nIndex >= nCount) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + + return m_BaseMaterialLookup[nIndex]; + } + + CModelBaseMaterialResource * CModel::getBaseMaterial(_In_ nfUint32 nIndex) + { + CModelBaseMaterialResource * pBaseMaterial = dynamic_cast (getBaseMaterialResource(nIndex).get()); + if (pBaseMaterial == nullptr) + throw CNMRException(NMR_ERROR_RESOURCETYPEMISMATCH); + + return pBaseMaterial; + } + + void CModel::mergeBaseMaterials(_In_ CModel * pSourceModel, _In_ UniqueResourceIDMapping &oldToNewMapping) + { + if (pSourceModel == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + nfUint32 nCount = pSourceModel->getBaseMaterialCount(); + nfUint32 nIndex; + + for (nIndex = 0; nIndex < nCount; nIndex++) { + CModelBaseMaterialResource * pOldMaterial = pSourceModel->getBaseMaterial(nIndex); + __NMRASSERT(pOldMaterial != nullptr); + + PModelBaseMaterialResource pNewMaterial = std::make_shared(generateResourceID(), this); + pNewMaterial->mergeFrom(pOldMaterial); + + addResource(pNewMaterial); + oldToNewMapping[pOldMaterial->getPackageResourceID()->getUniqueID()] = pNewMaterial->getPackageResourceID()->getUniqueID(); + } + + } + + _Ret_maybenull_ PModelColorGroupResource CModel::findColorGroup(_In_ UniqueResourceID nResourceID) + { + PModelResource pResource = findResource(nResourceID); + if (pResource != nullptr) { + PModelColorGroupResource pColorGroupResource = std::dynamic_pointer_cast(pResource); + if (pColorGroupResource.get() == nullptr) + throw CNMRException(NMR_ERROR_RESOURCETYPEMISMATCH); + return pColorGroupResource; + } + return nullptr; + } + + nfUint32 CModel::getColorGroupCount() + { + return (nfUint32)m_ColorGroupLookup.size(); + } + + PModelResource CModel::getColorGroupResource(_In_ nfUint32 nIndex) + { + nfUint32 nCount = getColorGroupCount(); + if (nIndex >= nCount) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + + return m_ColorGroupLookup[nIndex]; + + } + + CModelColorGroupResource * CModel::getColorGroup(_In_ nfUint32 nIndex) + { + CModelColorGroupResource * pColorGroup = dynamic_cast (getColorGroupResource(nIndex).get()); + if (pColorGroup == nullptr) + throw CNMRException(NMR_ERROR_RESOURCETYPEMISMATCH); + + return pColorGroup; + } + + void CModel::mergeColorGroups(_In_ CModel * pSourceModel, _In_ UniqueResourceIDMapping &oldToNewMapping) + { + if (pSourceModel == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + nfUint32 nCount = pSourceModel->getColorGroupCount(); + nfUint32 nIndex; + + for (nIndex = 0; nIndex < nCount; nIndex++) { + CModelColorGroupResource * pOldColor = pSourceModel->getColorGroup(nIndex); + __NMRASSERT(pOldColor != nullptr); + + PModelColorGroupResource pNewColor = std::make_shared(generateResourceID(), this); + pNewColor->mergeFrom(pOldColor); + + addResource(pNewColor); + oldToNewMapping[pOldColor->getPackageResourceID()->getUniqueID()] = pNewColor->getPackageResourceID()->getUniqueID(); + } + } + + + _Ret_maybenull_ PModelTexture2DGroupResource CModel::findTexture2DGroup(_In_ UniqueResourceID nResourceID) + { + PModelResource pResource = findResource(nResourceID); + if (pResource != nullptr) { + PModelTexture2DGroupResource pTexture2DGroupResource = std::dynamic_pointer_cast(pResource); + if (pTexture2DGroupResource.get() == nullptr) + throw CNMRException(NMR_ERROR_RESOURCETYPEMISMATCH); + return pTexture2DGroupResource; + } + return nullptr; + } + + nfUint32 CModel::getTexture2DGroupCount() + { + return (nfUint32)m_Texture2DGroupLookup.size(); + } + + PModelResource CModel::getTexture2DGroupResource(_In_ nfUint32 nIndex) + { + nfUint32 nCount = getTexture2DGroupCount(); + if (nIndex >= nCount) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + + return m_Texture2DGroupLookup[nIndex]; + + } + + CModelTexture2DGroupResource * CModel::getTexture2DGroup(_In_ nfUint32 nIndex) + { + CModelTexture2DGroupResource * pTexture2DGroup = dynamic_cast (getTexture2DGroupResource(nIndex).get()); + if (pTexture2DGroup == nullptr) + throw CNMRException(NMR_ERROR_RESOURCETYPEMISMATCH); + + return pTexture2DGroup; + } + + void CModel::mergeTexture2DGroups(_In_ CModel * pSourceModel, _In_ UniqueResourceIDMapping &oldToNewMapping) + { + if (pSourceModel == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + nfUint32 nCount = pSourceModel->getTexture2DGroupCount(); + for (nfUint32 nIndex = 0; nIndex < nCount; nIndex++) { + CModelTexture2DGroupResource * pOldTexture2DGroup = pSourceModel->getTexture2DGroup(nIndex); + + if (!pOldTexture2DGroup) { + throw CNMRException(NMR_ERROR_RESOURCENOTFOUND); + } + PModelTexture2DResource pOldTexture2D = pOldTexture2DGroup->getTexture2D(); + if (!pOldTexture2D) { + throw CNMRException(NMR_ERROR_RESOURCENOTFOUND); + } + UniqueResourceID packageIDOfOldTexture = oldToNewMapping[pOldTexture2D->getPackageResourceID()->getUniqueID()]; + PModelTexture2DResource pNewTexture2D = findTexture2D(packageIDOfOldTexture); + if (!pNewTexture2D) { + throw CNMRException(NMR_ERROR_RESOURCENOTFOUND); + } + + PModelTexture2DGroupResource pNewTexture2DGroup = std::make_shared(generateResourceID(), this, pNewTexture2D); + pNewTexture2DGroup->mergeFrom(pOldTexture2DGroup); + + addResource(pNewTexture2DGroup); + oldToNewMapping[pOldTexture2DGroup->getPackageResourceID()->getUniqueID()] = pNewTexture2DGroup->getPackageResourceID()->getUniqueID(); + } + } + + + _Ret_maybenull_ PModelCompositeMaterialsResource CModel::findCompositeMaterials(_In_ UniqueResourceID nResourceID) + { + PModelResource pResource = findResource(nResourceID); + if (pResource != nullptr) { + PModelCompositeMaterialsResource pCompositeMaterialsResource = std::dynamic_pointer_cast(pResource); + if (pCompositeMaterialsResource.get() == nullptr) + throw CNMRException(NMR_ERROR_RESOURCETYPEMISMATCH); + return pCompositeMaterialsResource; + } + return nullptr; + } + + nfUint32 CModel::getCompositeMaterialsCount() + { + return (nfUint32)m_CompositeMaterialsLookup.size(); + } + + PModelResource CModel::getCompositeMaterialsResource(_In_ nfUint32 nIndex) + { + nfUint32 nCount = getCompositeMaterialsCount(); + if (nIndex >= nCount) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + + return m_CompositeMaterialsLookup[nIndex]; + + } + + CModelCompositeMaterialsResource * CModel::getCompositeMaterials(_In_ nfUint32 nIndex) + { + CModelCompositeMaterialsResource * pCompositeMaterialsGroup = dynamic_cast (getCompositeMaterialsResource(nIndex).get()); + if (pCompositeMaterialsGroup == nullptr) + throw CNMRException(NMR_ERROR_RESOURCETYPEMISMATCH); + + return pCompositeMaterialsGroup; + } + + void CModel::mergeCompositeMaterials(_In_ CModel * pSourceModel, _In_ UniqueResourceIDMapping &oldToNewMapping) + { + if (pSourceModel == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + nfUint32 nCount = pSourceModel->getCompositeMaterialsCount(); + for (nfUint32 nIndex = 0; nIndex < nCount; nIndex++) { + CModelCompositeMaterialsResource * pOldCompositeMaterials = pSourceModel->getCompositeMaterials(nIndex); + + PModelBaseMaterialResource pOldBaseMaterial = pOldCompositeMaterials->getBaseMaterialResource(); + if (!pOldCompositeMaterials || !pOldBaseMaterial) { + throw CNMRException(NMR_ERROR_RESOURCENOTFOUND); + } + UniqueResourceID packageIDOfOldMaterial = oldToNewMapping[pOldBaseMaterial->getPackageResourceID()->getUniqueID()]; + + PPackageResourceID pNewIDOfOldMaterial = findPackageResourceID(packageIDOfOldMaterial); + PModelBaseMaterialResource pNewBaseMaterialResource = findBaseMaterial(pNewIDOfOldMaterial); + if (!pNewBaseMaterialResource) { + throw CNMRException(NMR_ERROR_RESOURCENOTFOUND); + } + + PModelCompositeMaterialsResource pNewCompositeMaterials = + std::make_shared(generateResourceID(), this, pNewBaseMaterialResource); + pNewCompositeMaterials->mergeFrom(pOldCompositeMaterials); + + addResource(pNewCompositeMaterials); + oldToNewMapping[pOldCompositeMaterials->getPackageResourceID()->getUniqueID()] = pNewCompositeMaterials->getPackageResourceID()->getUniqueID(); + } + } + + _Ret_maybenull_ PModelMultiPropertyGroupResource CModel::findMultiPropertyGroup(_In_ UniqueResourceID nResourceID) + { + PModelResource pResource = findResource(nResourceID); + if (pResource != nullptr) { + PModelMultiPropertyGroupResource pMultiPropertyGroupResource = std::dynamic_pointer_cast(pResource); + if (pMultiPropertyGroupResource.get() == nullptr) + throw CNMRException(NMR_ERROR_RESOURCETYPEMISMATCH); + return pMultiPropertyGroupResource; + } + return nullptr; + } + + nfUint32 CModel::getMultiPropertyGroupCount() + { + return (nfUint32)m_MultiPropertyGroupLookup.size(); + } + + PModelResource CModel::getMultiPropertyGroupResource(_In_ nfUint32 nIndex) + { + nfUint32 nCount = getMultiPropertyGroupCount(); + if (nIndex >= nCount) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + + return m_MultiPropertyGroupLookup[nIndex]; + + } + + CModelMultiPropertyGroupResource * CModel::getMultiPropertyGroup(_In_ nfUint32 nIndex) + { + CModelMultiPropertyGroupResource * pMultiPropertyGroupGroup = dynamic_cast(getMultiPropertyGroupResource(nIndex).get()); + if (pMultiPropertyGroupGroup == nullptr) + throw CNMRException(NMR_ERROR_RESOURCETYPEMISMATCH); + + return pMultiPropertyGroupGroup; + } + + void CModel::mergeMultiPropertyGroups(_In_ CModel * pSourceModel, _In_ UniqueResourceIDMapping &oldToNewMapping) + { + if (pSourceModel == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + nfUint32 nCount = pSourceModel->getMultiPropertyGroupCount(); + for (nfUint32 nIndex = 0; nIndex < nCount; nIndex++) { + CModelMultiPropertyGroupResource * pOldMultiPropertyGroup = pSourceModel->getMultiPropertyGroup(nIndex); + __NMRASSERT(pNewTexture2DGroup != nullptr); + + PModelMultiPropertyGroupResource pNewMultiPropertyGroup = std::make_shared(generateResourceID(), this); + pNewMultiPropertyGroup->mergeFrom(pOldMultiPropertyGroup); + + addResource(pNewMultiPropertyGroup); + oldToNewMapping[pOldMultiPropertyGroup->getPackageResourceID()->getUniqueID()] = pNewMultiPropertyGroup->getPackageResourceID()->getUniqueID(); + } + } + + _Ret_maybenull_ PModelTexture2DResource CModel::findTexture2D(_In_ UniqueResourceID nResourceID) + { + PModelResource pResource = findResource(nResourceID); + if (pResource != nullptr) { + PModelTexture2DResource pTexture2DResource = std::dynamic_pointer_cast(pResource); + if (pTexture2DResource.get() == nullptr) + throw CNMRException(NMR_ERROR_RESOURCETYPEMISMATCH); + return pTexture2DResource; + } + return nullptr; + } + + nfUint32 CModel::getTexture2DCount() + { + return (nfUint32)m_TextureLookup.size(); + } + + PModelResource CModel::getTexture2DResource(_In_ nfUint32 nIndex) + { + nfUint32 nCount = getTexture2DCount(); + if (nIndex >= nCount) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + + return m_TextureLookup[nIndex]; + + } + + CModelTexture2DResource * CModel::getTexture2D(_In_ nfUint32 nIndex) + { + CModelTexture2DResource * pTexture2D = dynamic_cast (getTexture2DResource(nIndex).get()); + if (pTexture2D == nullptr) + throw CNMRException(NMR_ERROR_RESOURCETYPEMISMATCH); + + return pTexture2D; + } + + void CModel::mergeTextures2D(_In_ CModel * pSourceModel, _In_ UniqueResourceIDMapping &oldToNewMapping) + { + if (pSourceModel == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + nfUint32 nCount = pSourceModel->getTexture2DCount(); + nfUint32 nIndex; + + for (nIndex = 0; nIndex < nCount; nIndex++) + { + CModelTexture2DResource * pTextureResource = pSourceModel->getTexture2D(nIndex); + if (pTextureResource == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + PModelAttachment pSourceAttachment = pTextureResource->getAttachment(); + PModelAttachment pNewAttachment; + if (pSourceAttachment.get()) { + pNewAttachment = findModelAttachment(pSourceAttachment->getPathURI()); + if (pNewAttachment.get() == nullptr) + throw CNMRException(NMR_ERROR_ATTACHMENTNOTFOUND); + } + PModelTexture2DResource pNewTextureResource = CModelTexture2DResource::make(generateResourceID(), this, pNewAttachment); + pNewTextureResource->copyFrom(pTextureResource, false); + + addResource(pNewTextureResource); + oldToNewMapping[pTextureResource->getPackageResourceID()->getUniqueID()] = pNewTextureResource->getPackageResourceID()->getUniqueID(); + } + } + + nfUint32 CModel::createHandle() + { + if (m_nHandleCounter >= NMR_MAXHANDLE) + throw CNMRException(NMR_ERROR_HANDLEOVERFLOW); + + nfUint32 nHandle = m_nHandleCounter; + m_nHandleCounter++; + + return nHandle; + } + + PModelAttachment CModel::addPackageThumbnail(_In_ std::string sPath, _In_ PImportStream pStream) + { + if (m_pPackageThumbnailAttachment.get() == nullptr) + { + m_pPackageThumbnailAttachment = std::make_shared(this, + sPath, + PACKAGE_THUMBNAIL_RELATIONSHIP_TYPE, pStream); + } + return m_pPackageThumbnailAttachment; + } + + PModelAttachment CModel::addPackageThumbnail() + { + return addPackageThumbnail(PACKAGE_THUMBNAIL_URI_BASE + std::string("/") + "thumbnail.png", std::make_shared()); + } + + void CModel::removePackageThumbnail() + { + m_pPackageThumbnailAttachment.reset(); + } + + PModelAttachment CModel::getPackageThumbnail() + { + return m_pPackageThumbnailAttachment; + } + + PModelAttachment CModel::addAttachment(_In_ const std::string sPath, _In_ const std::string sRelationShipType, PImportStream pCopiedStream) + { + if (pCopiedStream.get() == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + std::string sLowerPath = sPath; + //std::transform(sLowerPath.begin(), sLowerPath.end(), sLowerPath.begin(), towupper); + + auto iIterator = m_AttachmentURIMap.find(sLowerPath); + if (iIterator != m_AttachmentURIMap.end()) + throw CNMRException(NMR_ERROR_DUPLICATEATTACHMENTPATH); + + PModelAttachment pAttachment = std::make_shared(this, sPath, sRelationShipType, pCopiedStream); + m_Attachments.push_back(pAttachment); + m_AttachmentURIMap.insert(std::make_pair(sLowerPath, pAttachment)); + + return pAttachment; + } + + PModelAttachment CModel::getModelAttachment(_In_ nfUint32 nIndex) + { + nfUint32 nCount = getAttachmentCount(); + if (nIndex >= nCount) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + + return m_Attachments[nIndex]; + } + + nfUint32 CModel::getAttachmentCount() + { + return (nfUint32)m_Attachments.size(); + } + + std::string CModel::getModelAttachmentPath(_In_ nfUint32 nIndex) + { + nfUint32 nCount = getAttachmentCount(); + if (nIndex >= nCount) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + + PModelAttachment pAttachment = m_Attachments[nIndex]; + + return pAttachment->getPathURI(); + } + + PModelAttachment CModel::findModelAttachment(_In_ std::string sPath) + { + auto iIterator = m_AttachmentURIMap.find(sPath); + if (iIterator != m_AttachmentURIMap.end()) { + return iIterator->second; + } + + return nullptr; + } + + void CModel::removeAttachment(_In_ const std::string sPath) + { + auto iIterator = m_AttachmentURIMap.find(sPath); + if (iIterator != m_AttachmentURIMap.end()) { + auto iVectorIterator = m_Attachments.begin(); + while (iVectorIterator != m_Attachments.end()) { + if (iVectorIterator->get() == iIterator->second.get()) { + m_Attachments.erase(iVectorIterator); + break; + } + iVectorIterator++; + } + + m_AttachmentURIMap.erase(iIterator); + } + } + + + void CModel::mergeModelAttachments(_In_ CModel * pSourceModel) + { + if (pSourceModel == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + nfUint32 nCount = pSourceModel->getAttachmentCount(); + nfUint32 nIndex; + + for (nIndex = 0; nIndex < nCount; nIndex++) + { + PModelAttachment pModelAttachment = pSourceModel->getModelAttachment(nIndex); + if (pModelAttachment == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + PImportStream pInStream = pModelAttachment->getStream(); + if (!pInStream) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + nfUint64 nPos = pInStream->getPosition(); + pInStream->seekPosition(0, true); + PImportStream pCopiedStream = std::make_shared(pInStream.get(), pInStream->retrieveSize(), true); + pInStream->seekPosition(nPos, true); + + addAttachment(pModelAttachment->getPathURI(), pModelAttachment->getRelationShipType(), pCopiedStream); + } + } + + template + void moveItemToBack(std::vector& v, size_t itemIndex) + { + auto it = v.begin() + itemIndex; + std::rotate(it, it + 1, v.end()); + } + + PModelAttachment CModel::addProductionAttachment(_In_ const std::string sPath, _In_ const std::string sRelationShipType, PImportStream pCopiedStream, nfBool bForceUnique) + { + if (pCopiedStream.get() == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + std::string sLowerPath = sPath; + //std::transform(sLowerPath.begin(), sLowerPath.end(), sLowerPath.begin(), towupper); + PModelAttachment pAttachment; + auto iIterator = m_ProductionAttachmentURIMap.find(sLowerPath); + if (iIterator != m_ProductionAttachmentURIMap.end()) { + if (bForceUnique) + throw CNMRException(NMR_ERROR_DUPLICATEATTACHMENTPATH); + else { + pAttachment = iIterator->second; + auto it = std::find(m_ProductionAttachments.begin(), m_ProductionAttachments.end(), iIterator->second); + moveItemToBack(m_ProductionAttachments, it - m_ProductionAttachments.begin()); + } + } + else + { + pAttachment = std::make_shared(this, sPath, sRelationShipType, pCopiedStream); + m_ProductionAttachments.push_back(pAttachment); + m_ProductionAttachmentURIMap.insert(std::make_pair(sLowerPath, pAttachment)); + } + + return pAttachment; + } + + PModelAttachment CModel::getProductionModelAttachment(_In_ nfUint32 nIndex) + { + nfUint32 nCount = getProductionAttachmentCount(); + if (nIndex >= nCount) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + + return m_ProductionAttachments[nIndex]; + + } + + nfUint32 CModel::getProductionAttachmentCount() + { + return (nfUint32)m_ProductionAttachments.size(); + } + + std::string CModel::getProductionModelAttachmentPath(_In_ nfUint32 nIndex) + { + nfUint32 nCount = getProductionAttachmentCount(); + if (nIndex >= nCount) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + + PModelAttachment pProductionAttachment = m_ProductionAttachments[nIndex]; + + return pProductionAttachment->getPathURI(); + + } + + PModelAttachment CModel::findProductionModelAttachment(_In_ std::string sPath) + { + auto iIterator = m_ProductionAttachmentURIMap.find(sPath); + if (iIterator != m_ProductionAttachmentURIMap.end()) { + return iIterator->second; + } + + return nullptr; + } + + void CModel::removeProductionAttachment(_In_ const std::string sPath) + { + auto iIterator = m_ProductionAttachmentURIMap.find(sPath); + if (iIterator != m_ProductionAttachmentURIMap.end()) { + auto iVectorIterator = m_ProductionAttachments.begin(); + while (iVectorIterator != m_ProductionAttachments.end()) { + if (iVectorIterator->get() == iIterator->second.get()) { + m_ProductionAttachments.erase(iVectorIterator); + break; + } + iVectorIterator++; + } + + m_ProductionAttachmentURIMap.erase(iIterator); + } + } + + + std::map CModel::getCustomContentTypes() + { + return m_CustomContentTypes; + } + + void CModel::addCustomContentType(_In_ const std::string sExtension, _In_ const std::string sContentType) + { + m_CustomContentTypes.insert(std::make_pair(sExtension, sContentType)); + } + + void CModel::removeCustomContentType(_In_ const std::string sExtension) + { + m_CustomContentTypes.erase(sExtension); + } + + nfBool CModel::contentTypeIsDefault(_In_ const std::string sExtension) + { + if (strcmp(sExtension.c_str(), PACKAGE_3D_RELS_EXTENSION) == 0) + return true; + if (strcmp(sExtension.c_str(), PACKAGE_3D_MODEL_EXTENSION) == 0) + return true; + if (strcmp(sExtension.c_str(), PACKAGE_3D_TEXTURE_EXTENSION) == 0) + return true; + if (strcmp(sExtension.c_str(), PACKAGE_3D_PNG_EXTENSION) == 0) + return true; + if (strcmp(sExtension.c_str(), PACKAGE_3D_JPEG_EXTENSION) == 0) + return true; + if (strcmp(sExtension.c_str(), PACKAGE_3D_JPG_EXTENSION) == 0) + return true; + + return false; + } + + // returns whether a specific extension has to be marked as required + nfBool CModel::RequireExtension(_In_ const std::string sExtension) { + // loop over all resources to check for slices, beamlattices, production-references, + // that make it necessary to mark these extensions as required + if (sExtension == XML_3MF_NAMESPACE_BEAMLATTICESPEC) { + nfBool bRequireBeamLattice = false; + for (size_t i = 0; i < m_ObjectLookup.size(); i++) { + CModelMeshObject* pMeshObject = dynamic_cast(m_ObjectLookup[i].get()); + if (pMeshObject == nullptr || pMeshObject->getMesh() == nullptr) + continue; + if (pMeshObject->getMesh()->getBeamCount() > 0) { + bRequireBeamLattice = true; + break; + } + } + return bRequireBeamLattice; + } + + if (sExtension == XML_3MF_NAMESPACE_SLICESPEC) { + nfBool bRequireSliceExtension = false; + for (size_t i = 0; i < m_ObjectLookup.size(); i++) { + CModelMeshObject* pMeshObject = dynamic_cast(m_ObjectLookup[i].get()); + if (pMeshObject == nullptr || pMeshObject->getMesh() == nullptr) + continue; + if (!pMeshObject->getSliceStack().get()) + continue; + if (pMeshObject->slicesMeshResolution() == MODELSLICESMESHRESOLUTION_LOW) { + bRequireSliceExtension = true; + break; + } + } + return bRequireSliceExtension; + } + + if (sExtension == XML_3MF_NAMESPACE_SECURECONTENTSPEC) { + if (m_pKeyStore.get() != nullptr) { + return !m_pKeyStore->empty(); + } + } + + if (sExtension == XML_3MF_NAMESPACE_PRODUCTIONSPEC) { + // We do not write out models that require the production specification + // i.e. we do not make use of the "getPath"-redirection. + // Thus, never mark the production extension is required. + return false; + } + + return false; + } + + nfUint32 CModel::getSliceStackCount() { + return (nfUint32)m_SliceStackLookup.size(); + } + + PModelResource CModel::getSliceStackResource(_In_ nfUint32 nIndex) { + nfUint32 nCount = getSliceStackCount(); + if (nIndex >= nCount) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + + return m_SliceStackLookup[nIndex]; + } + + std::list CModel::getSortedObjectList() + { + std::list resultList; + + for (size_t i = 0; i < m_ObjectLookup.size(); i++) { + CModelObject* pObject = dynamic_cast(m_ObjectLookup[i].get()); + if (pObject != nullptr) { + pObject->clearComponentDepthLevel(); + resultList.push_back(pObject); + } + } + + for (auto iIterator = resultList.begin(); iIterator != resultList.end(); iIterator++) { + (*iIterator)->calculateComponentDepthLevel(1); + } + + // sort by (level descending, ResourceID ascending) + resultList.sort( [](CModelObject * pObject1, CModelObject * pObject2) + { + nfUint32 nLevel1 = pObject1->getComponentDepthLevel(); + nfUint32 nLevel2 = pObject2->getComponentDepthLevel(); + + if (nLevel1 == nLevel2) + return (pObject1->getPackageResourceID()->getUniqueID()) < (pObject2->getPackageResourceID()->getUniqueID()); + + return nLevel1 > nLevel2; + }); + + return resultList; + } + + PKeyStore CModel::getKeyStore() { + return m_pKeyStore; + } + + void CModel::setKeyStore(PKeyStore keyStore) { + m_pKeyStore = keyStore; + } + + void CModel::setCryptoRandCallback(CryptoRandGenDescriptor const & randDescriptor) { + m_sRandDescriptor = randDescriptor; + } + + nfBool CModel::hasCryptoRandCallbak() const { + return (bool)m_sRandDescriptor.m_fnRNG; + } + + nfUint64 CModel::generateRandomBytes(nfByte * bytes, nfUint64 size) { + if (m_sRandDescriptor.m_fnRNG) + return m_sRandDescriptor.m_fnRNG(bytes, size, m_sRandDescriptor.m_pUserData); + + static bool rngInitialized = false; + static std::random_device randDev; + static std::mt19937 mTwister; + static std::mutex mtLock; + + { + //scope the guard to the generator initialization + std::lock_guard guard(mtLock); + if (!rngInitialized) { + std::array seedData; + uint32_t curTime = static_cast(time(nullptr)); + for (auto it = seedData.begin(); it != seedData.end(); ++it) + *it = randDev() ^ curTime; + std::seed_seq seedSeq(seedData.begin(), seedData.end()); + mTwister.seed(seedSeq); + rngInitialized = true; + } + } + + std::uniform_int_distribution distByte(std::numeric_limits::min(), std::numeric_limits::max()); + for (nfUint64 n = 0; n < size; ++n) { + *(bytes + n) = distByte(mTwister); + } + return size; + } + +} diff --git a/Source/Model/Classes/NMR_ModelAttachment.cpp b/Source/Model/Classes/NMR_ModelAttachment.cpp new file mode 100644 index 0000000..68e851d --- /dev/null +++ b/Source/Model/Classes/NMR_ModelAttachment.cpp @@ -0,0 +1,88 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelAttachment.cpp implements the Model Attachment Class. + +--*/ + +#include "Model/Classes/NMR_ModelAttachment.h" +#include "Common/NMR_Exception.h" + +namespace NMR { + + CModelAttachment::CModelAttachment(_In_ CModel * pModel, _In_ const std::string sPathURI, _In_ const std::string sRelationShipType, _In_ PImportStream pStream) + { + __NMRASSERT(pModel); + if (pStream.get() == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + m_pModel = pModel; + m_sPathURI = sPathURI; + m_pStream = pStream; + m_sRelationShipType = sRelationShipType; + } + + CModelAttachment::~CModelAttachment() + { + m_pModel = NULL; + } + + _Ret_notnull_ CModel * CModelAttachment::getModel() + { + return m_pModel; + } + + std::string CModelAttachment::getPathURI() + { + return m_sPathURI; + } + + std::string CModelAttachment::getRelationShipType() + { + return m_sRelationShipType; + } + + PImportStream CModelAttachment::getStream() + { + return m_pStream; + } + + void CModelAttachment::setStream(_In_ PImportStream pStream) + { + m_pStream = pStream; + } + + void CModelAttachment::setRelationShipType(_In_ const std::string sRelationShipType) + { + m_sRelationShipType = sRelationShipType; + } + + + +} + diff --git a/Source/Model/Classes/NMR_ModelBaseMaterial.cpp b/Source/Model/Classes/NMR_ModelBaseMaterial.cpp new file mode 100644 index 0000000..a9c8444 --- /dev/null +++ b/Source/Model/Classes/NMR_ModelBaseMaterial.cpp @@ -0,0 +1,78 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelBaseMaterial.cpp implements the Model Base Material Class. +A base material is an in memory representation of the 3MF basematerial node. + +--*/ + +#include "Model/Classes/NMR_ModelBaseMaterial.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_StringUtils.h" +#include + +namespace NMR { + + CModelBaseMaterial::CModelBaseMaterial(_In_ const std::string sName, _In_ nfColor cDisplayColor, _In_ ModelPropertyID nPropertyID) + { + m_sName = sName; + m_cDisplayColor = cDisplayColor; + m_nPropertyID = nPropertyID; + } + + nfColor CModelBaseMaterial::getDisplayColor() + { + return m_cDisplayColor; + } + + void CModelBaseMaterial::setColor(_In_ nfColor cColor) + { + m_cDisplayColor = cColor; + } + + std::string CModelBaseMaterial::getName() + { + return m_sName; + } + + void CModelBaseMaterial::setName(_In_ const std::string sName) + { + m_sName = sName; + } + + std::string CModelBaseMaterial::getDisplayColorString() + { + return fnColorToString(m_cDisplayColor); + } + + nfUint32 CModelBaseMaterial::getPropertyID() + { + return m_nPropertyID; + } +} + diff --git a/Source/Model/Classes/NMR_ModelBaseMaterials.cpp b/Source/Model/Classes/NMR_ModelBaseMaterials.cpp new file mode 100644 index 0000000..3806da1 --- /dev/null +++ b/Source/Model/Classes/NMR_ModelBaseMaterials.cpp @@ -0,0 +1,119 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelBaseMaterials.cpp implements the Model Base Material Resource Class. +A base material is an in memory representation of the 3MF basematerials node. + +--*/ + +#include "Model/Classes/NMR_ModelBaseMaterials.h" +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_Exception.h" +#include + +namespace NMR { + + CModelBaseMaterialResource::CModelBaseMaterialResource(_In_ const ModelResourceID sID, _In_ CModel * pModel) + : CModelResource(sID, pModel) + { + m_nNextPropertyID = 1; + } + + nfUint32 CModelBaseMaterialResource::addBaseMaterial(_In_ const std::string sName, _In_ nfColor cDisplayColor) + { + nfUint32 nID = m_nNextPropertyID; + if (getCount() >= XML_3MF_MAXRESOURCEINDEX) { + throw CNMRException(NMR_ERROR_TOOMANYMATERIALS); + } + + m_pMaterials.insert( + std::make_pair(nID, std::make_shared(sName, cDisplayColor, nID)) + ); + + m_nNextPropertyID++; + + clearResourceIndexMap(); + + return nID; + } + + nfUint32 CModelBaseMaterialResource::getCount() + { + return (nfUint32)m_pMaterials.size(); + } + + PModelBaseMaterial CModelBaseMaterialResource::getBaseMaterial(_In_ nfUint32 nPropertyID) + { + auto iIterator = m_pMaterials.find(nPropertyID); + if (iIterator != m_pMaterials.end()) { + return iIterator->second; + } + else { + throw CNMRException(NMR_ERROR_INVALIDINDEX); + } + } + + void CModelBaseMaterialResource::removeMaterial(_In_ nfUint32 nPropertyID) + { + m_pMaterials.erase(nPropertyID); + clearResourceIndexMap(); + } + + void CModelBaseMaterialResource::mergeFrom(_In_ CModelBaseMaterialResource * pSourceMaterial) + { + if (pSourceMaterial == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + nfUint32 nCount = pSourceMaterial->getCount(); + + pSourceMaterial->buildResourceIndexMap(); + for (nfUint32 nIndex = 0; nIndex < nCount; nIndex++) { + ModelPropertyID nPropertyID; + pSourceMaterial->mapResourceIndexToPropertyID(nIndex, nPropertyID); + PModelBaseMaterial pMaterial = pSourceMaterial->getBaseMaterial(nPropertyID); + addBaseMaterial(pMaterial->getName(), pMaterial->getDisplayColor()); + } + clearResourceIndexMap(); + } + + void CModelBaseMaterialResource::buildResourceIndexMap() + { + m_ResourceIndexMap.clear(); + m_ResourceIndexMap.reserve(m_pMaterials.size()); + + auto iIterator = m_pMaterials.begin(); + while (iIterator != m_pMaterials.end()) { + m_ResourceIndexMap.push_back(iIterator->first); + iIterator++; + } + + m_bHasResourceIndexMap = true; + } + +} + diff --git a/Source/Model/Classes/NMR_ModelBuildItem.cpp b/Source/Model/Classes/NMR_ModelBuildItem.cpp new file mode 100644 index 0000000..81ec1ef --- /dev/null +++ b/Source/Model/Classes/NMR_ModelBuildItem.cpp @@ -0,0 +1,151 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelBuildItem.cpp implements the Model Build Item Class. +A model build item is an in memory representation of the 3MF +build item. + +--*/ + +#include "Model/Classes/NMR_ModelBuildItem.h" +#include "Common/NMR_Exception.h" +#include + +namespace NMR { + + CModelBuildItem::CModelBuildItem(_In_ CModelObject * pObject, _In_ nfUint32 nHandle) + { + if (!pObject) + throw CNMRException (NMR_ERROR_INVALIDPARAM); + m_pObject = pObject; + m_mTransform = fnMATRIX3_identity (); + m_nHandle = nHandle; + m_MetaDataGroup = std::make_shared(); + + setUUID(std::make_shared()); + } + + CModelBuildItem::CModelBuildItem(_In_ CModelObject * pObject, _In_ const NMATRIX3 mTransform, _In_ nfUint32 nHandle) + { + if (!pObject) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + m_pObject = pObject; + m_mTransform = mTransform; + m_nHandle = nHandle; + m_MetaDataGroup = std::make_shared(); + + setUUID(std::make_shared()); + } + + CModelBuildItem::~CModelBuildItem() + { + m_pObject = nullptr; + } + + CModelObject * CModelBuildItem::getObject() + { + return m_pObject; + } + + NMATRIX3 CModelBuildItem::getTransform() + { + return m_mTransform; + } + + void CModelBuildItem::setTransform(_In_ const NMATRIX3 mTransform) + { + m_mTransform = mTransform; + } + + nfBool CModelBuildItem::hasTransform() + { + return (!fnMATRIX3_isIdentity(m_mTransform)); + } + + std::string CModelBuildItem::getTransformString() + { + return fnMATRIX3_toString(m_mTransform); + } + + std::string CModelBuildItem::getPartNumber() + { + return m_sPartNumber; + } + + void CModelBuildItem::setPartNumber(_In_ std::string sPartNumber) + { + m_sPartNumber = sPartNumber; + } + + CModel* CModelBuildItem::getModel() { + return m_pObject->getModel(); + } + + PUUID CModelBuildItem::uuid() + { + return m_UUID; + } + + void CModelBuildItem::setUUID(PUUID uuid) + { + getModel()->registerUUID(uuid); + getModel()->unRegisterUUID(m_UUID); + m_UUID = uuid; + } + + PModelMetaDataGroup CModelBuildItem::metaDataGroup() + { + return m_MetaDataGroup; + } + + std::string CModelBuildItem::path() + { + return m_sPath; + } + + void CModelBuildItem::setPath(std::string sPath) + { + m_sPath = sPath; + } + + void CModelBuildItem::mergeToMesh(_In_ CMesh * pMesh) + { + __NMRASSERT(pMesh); + m_pObject->mergeToMesh(pMesh, m_mTransform); + } + + nfUint32 CModelBuildItem::getHandle() + { + return m_nHandle; + } + + bool CModelBuildItem::isValidForSlices() { + NMATRIX3 mat = getTransform(); + return m_pObject->isValidForSlices(mat); + } +} diff --git a/Source/Model/Classes/NMR_ModelColorGroup.cpp b/Source/Model/Classes/NMR_ModelColorGroup.cpp new file mode 100644 index 0000000..29fc649 --- /dev/null +++ b/Source/Model/Classes/NMR_ModelColorGroup.cpp @@ -0,0 +1,128 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelColorGroup.cpp implements the Model Color Group Resource Class. +A color group is an in memory representation of the 3MF color groups node. + +--*/ + +#include "Model/Classes/NMR_ModelColorGroup.h" +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_Exception.h" +#include + +namespace NMR { + + CModelColorGroupResource::CModelColorGroupResource(_In_ const ModelResourceID sID, _In_ CModel * pModel) + : CModelResource(sID, pModel) + { + m_nNextPropertyID = 1; + } + + nfUint32 CModelColorGroupResource::addColor( _In_ nfColor cColor) + { + nfUint32 nID = m_nNextPropertyID; + if (getCount() >= XML_3MF_MAXRESOURCEINDEX) { + throw CNMRException(NMR_ERROR_TOOMANYCOLORS); + } + + m_pColors.insert(std::make_pair(nID, cColor)); + + m_nNextPropertyID++; + + clearResourceIndexMap(); + + return nID; + } + + nfUint32 CModelColorGroupResource::getCount() + { + return (nfUint32)m_pColors.size(); + } + + nfColor CModelColorGroupResource::getColor(_In_ ModelPropertyID nPropertyID) + { + auto iIterator = m_pColors.find(nPropertyID); + if (iIterator != m_pColors.end()) { + return iIterator->second; + } + else { + throw CNMRException(NMR_ERROR_INVALIDINDEX); + } + } + + void CModelColorGroupResource::setColor(_In_ ModelPropertyID nPropertyID, _In_ nfColor cColor) + { + auto iIterator = m_pColors.find(nPropertyID); + if (iIterator != m_pColors.end()) { + iIterator->second = cColor; + } + else { + throw CNMRException(NMR_ERROR_INVALIDINDEX); + } + } + + void CModelColorGroupResource::removeColor(_In_ ModelPropertyID nPropertyID) + { + m_pColors.erase(nPropertyID); + clearResourceIndexMap(); + } + + void CModelColorGroupResource::mergeFrom(_In_ CModelColorGroupResource * pSourceColorGroup) + { + if (pSourceColorGroup == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + nfUint32 nCount = pSourceColorGroup->getCount(); + + pSourceColorGroup->buildResourceIndexMap(); + for (nfUint32 nIndex = 0; nIndex < nCount; nIndex++) { + ModelPropertyID nPropertyID; + pSourceColorGroup->mapResourceIndexToPropertyID(nIndex, nPropertyID); + nfColor color = pSourceColorGroup->getColor(nPropertyID); + addColor(color); + } + clearResourceIndexMap(); + } + + void CModelColorGroupResource::buildResourceIndexMap() + { + m_ResourceIndexMap.clear(); + m_ResourceIndexMap.reserve(m_pColors.size()); + + auto iIterator = m_pColors.begin(); + while (iIterator != m_pColors.end()) { + m_ResourceIndexMap.push_back(iIterator->first); + iIterator++; + } + + m_bHasResourceIndexMap = true; + } + +} + diff --git a/Source/Model/Classes/NMR_ModelComponent.cpp b/Source/Model/Classes/NMR_ModelComponent.cpp new file mode 100644 index 0000000..4ae41f9 --- /dev/null +++ b/Source/Model/Classes/NMR_ModelComponent.cpp @@ -0,0 +1,113 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelComponent.cpp implements the Model Component Class. +A model component is an in memory representation of the 3MF component. + +--*/ + +#include "Model/Classes/NMR_ModelComponent.h" +#include "Common/NMR_Exception.h" + +namespace NMR { + + CModelComponent::CModelComponent(_In_ CModelObject * pObject) + { + if (!pObject) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + m_pObject = pObject; + m_mTransform = fnMATRIX3_identity(); + + m_UUID = std::make_shared(); + } + + CModelComponent::CModelComponent(_In_ CModelObject * pObject, _In_ const NMATRIX3 mTransform) + { + if (!pObject) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + m_pObject = pObject; + m_mTransform = mTransform; + + m_UUID = std::make_shared(); + } + + CModelComponent::~CModelComponent() + { + m_pObject = NULL; + } + + CModelObject * CModelComponent::getObject() + { + return m_pObject; + } + + CModel* CModelComponent::getModel() + { + return m_pObject->getModel(); + } + + NMATRIX3 CModelComponent::getTransform() + { + return m_mTransform; + } + + void CModelComponent::setTransform(_In_ const NMATRIX3 mTransform) + { + m_mTransform = mTransform; + } + + nfBool CModelComponent::hasTransform() + { + return (!fnMATRIX3_isIdentity(m_mTransform)); + } + + std::string CModelComponent::getTransformString() + { + return fnMATRIX3_toString(m_mTransform); + } + + PUUID CModelComponent::uuid() + { + return m_UUID; + } + + void CModelComponent::setUUID(PUUID uuid) + { + getObject()->getModel()->registerUUID(uuid); + getObject()->getModel()->unRegisterUUID(m_UUID); + m_UUID = uuid; + } + + void CModelComponent::mergeToMesh(_In_ CMesh * pMesh, _In_ const NMATRIX3 mMatrix) + { + __NMRASSERT(pMesh); + NMATRIX3 mLocalMatrix = fnMATRIX3_multiply(mMatrix, m_mTransform); + m_pObject->mergeToMesh(pMesh, mLocalMatrix); + } + +} diff --git a/Source/Model/Classes/NMR_ModelComponentsObject.cpp b/Source/Model/Classes/NMR_ModelComponentsObject.cpp new file mode 100644 index 0000000..d77b8a3 --- /dev/null +++ b/Source/Model/Classes/NMR_ModelComponentsObject.cpp @@ -0,0 +1,156 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelComponentsObject.cpp implements the Model Component Class. +A model component object is an in memory representation of the 3MF +component object. + +--*/ + +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Common/NMR_Exception.h" + +namespace NMR { + + CModelComponentsObject::CModelComponentsObject(_In_ const ModelResourceID sID, _In_ CModel * pModel) + : CModelObject(sID, pModel) + { + // empty on purpose + } + + CModelComponentsObject::~CModelComponentsObject() + { + m_Components.clear(); + } + + void CModelComponentsObject::addComponent(_In_ PModelComponent pComponent) + { + if (!pComponent) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + CModel * pModel = getModel(); + CModelObject * pModelObject = pComponent->getObject(); + + if (pModel != pModelObject->getModel()) + throw CNMRException(NMR_ERROR_MODELMISMATCH); + + if (pComponent->getObject()->getPackageResourceID() == this->getPackageResourceID() ) + throw CNMRException(NMR_ERROR_MODELMISMATCH); + + m_Components.push_back(pComponent); + } + + nfUint32 CModelComponentsObject::getComponentCount() + { + return (nfUint32)m_Components.size(); + } + + PModelComponent CModelComponentsObject::getComponent(_In_ nfUint32 nIdx) + { + if (nIdx >= (nfUint32)m_Components.size()) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + + return m_Components[nIdx]; + } + + void CModelComponentsObject::mergeToMesh(_In_ CMesh * pMesh, _In_ const NMATRIX3 mMatrix) + { + __NMRASSERT(pMesh); + for (auto iIterator = m_Components.begin(); iIterator != m_Components.end(); iIterator++) + (*iIterator)->mergeToMesh(pMesh, mMatrix); + } + + nfBool CModelComponentsObject::isValid() + { + if (m_Components.size() == 0) + return false; + + for (auto iIterator = m_Components.begin(); iIterator != m_Components.end(); iIterator++) { + CModelObject * pObject = (*iIterator)->getObject(); + __NMRASSERT(pObject); + + if (!pObject->isValid()) + return false; + } + + return true; + } + + nfBool CModelComponentsObject::hasSlices(nfBool bRecursive) + { + if (bRecursive) { + if (this->getSliceStack().get()) + return true; + for (auto iIterator = m_Components.begin(); iIterator != m_Components.end(); iIterator++) { + CModelObject * pObject = (*iIterator)->getObject(); + __NMRASSERT(pObject); + if (pObject->hasSlices(bRecursive)) + return true; + } + return false; + } + else { + return (this->getSliceStack().get() != nullptr); + } + } + + nfBool CModelComponentsObject::isValidForSlices(const NMATRIX3& totalParentMatrix) + { + if (this->getSliceStack().get()) { + if (!fnMATRIX3_isplanar(totalParentMatrix)) { + return false; + } + } + + for (auto iIterator = m_Components.begin(); iIterator != m_Components.end(); iIterator++) { + CModelObject * pObject = (*iIterator)->getObject(); + __NMRASSERT(pObject); + NMATRIX3 curMat = fnMATRIX3_multiply(totalParentMatrix, (*iIterator)->getTransform()); + if (!pObject->isValidForSlices(curMat)) + return false; + } + + return true; + } + + void CModelComponentsObject::calculateComponentDepthLevel(nfUint32 nLevel) + { + CModelObject::calculateComponentDepthLevel(nLevel); + for (auto iIterator = m_Components.begin(); iIterator != m_Components.end(); iIterator++) { + CModelObject * pObject = (*iIterator)->getObject(); + pObject->calculateComponentDepthLevel(nLevel + 1); + } + } + + void CModelComponentsObject::extendOutbox(_Out_ NOUTBOX3& vOutBox, _In_ const NMATRIX3 mAccumulatedMatrix) + { + for (auto iIterator = m_Components.begin(); iIterator != m_Components.end(); iIterator++) { + (*iIterator)->getObject()->extendOutbox(vOutBox, fnMATRIX3_multiply(mAccumulatedMatrix, (*iIterator)->getTransform())); + } + } +} diff --git a/Source/Model/Classes/NMR_ModelCompositeMaterials.cpp b/Source/Model/Classes/NMR_ModelCompositeMaterials.cpp new file mode 100644 index 0000000..4548ac3 --- /dev/null +++ b/Source/Model/Classes/NMR_ModelCompositeMaterials.cpp @@ -0,0 +1,146 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelCompositeMaterials.cpp implements the Model Composite Materials Resource Class. +A model composite materials resource is an in memory representation of the 3MF +composite materials resource object. + +--*/ + +#include "Model/Classes/NMR_ModelCompositeMaterials.h" +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_Exception.h" +#include + +namespace NMR { + + ; + CModelCompositeMaterialsResource::CModelCompositeMaterialsResource(_In_ const ModelResourceID sID, _In_ CModel * pModel, + _In_ PModelBaseMaterialResource pBaseMaterialResource) + : CModelResource(sID, pModel), m_pBaseMaterialResource(pBaseMaterialResource) + { + m_nNextPropertyID = 1; + if (!pBaseMaterialResource.get()) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + } + + nfUint32 CModelCompositeMaterialsResource::addComposite(_In_ PModelComposite pComposite) + { + nfUint32 nID = m_nNextPropertyID; + if (getCount() >= XML_3MF_MAXRESOURCEINDEX) { + throw CNMRException(NMR_ERROR_TOOMANYCOMPOSITES); + } + + // check for valid PropertyID + for (auto constituent : *pComposite) { + m_pBaseMaterialResource->getBaseMaterial(constituent.m_nPropertyID); + if ((constituent.m_dMixingRatio < 0) || constituent.m_dMixingRatio > 1.0) { + throw CNMRException(NMR_ERROR_MIXINGRATIO_OUTOFRANGE); + } + } + + + m_pComposites.insert(std::make_pair(nID, pComposite)); + + m_nNextPropertyID++; + + clearResourceIndexMap(); + + return nID; + } + + nfUint32 CModelCompositeMaterialsResource::getCount() + { + return (nfUint32)m_pComposites.size(); + } + + PModelComposite CModelCompositeMaterialsResource::getComposite(_In_ ModelPropertyID nPropertyID) + { + auto iIterator = m_pComposites.find(nPropertyID); + if (iIterator != m_pComposites.end()) { + return iIterator->second; + } + else { + throw CNMRException(NMR_ERROR_INVALIDINDEX); + } + } + + void CModelCompositeMaterialsResource::setComposite(_In_ ModelPropertyID nPropertyID, _In_ PModelComposite pComposite) + { + auto iIterator = m_pComposites.find(nPropertyID); + if (iIterator != m_pComposites.end()) { + iIterator->second = pComposite; + } + else { + throw CNMRException(NMR_ERROR_INVALIDINDEX); + } + } + + void CModelCompositeMaterialsResource::removeComposite(_In_ ModelPropertyID nPropertyID) + { + m_pComposites.erase(nPropertyID); + clearResourceIndexMap(); + } + + void CModelCompositeMaterialsResource::mergeFrom(_In_ CModelCompositeMaterialsResource * pSourceCompositesMaterials) + { + if (pSourceCompositesMaterials == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + nfUint32 nCount = pSourceCompositesMaterials->getCount(); + + pSourceCompositesMaterials->buildResourceIndexMap(); + for (nfUint32 nIndex = 0; nIndex < nCount; nIndex++) { + ModelPropertyID nPropertyID; + pSourceCompositesMaterials->mapResourceIndexToPropertyID(nIndex, nPropertyID); + PModelComposite pCmposite = pSourceCompositesMaterials->getComposite(nPropertyID); + addComposite(pCmposite); + } + clearResourceIndexMap(); + } + + void CModelCompositeMaterialsResource::buildResourceIndexMap() + { + m_ResourceIndexMap.clear(); + m_ResourceIndexMap.reserve(m_pComposites.size()); + + auto iIterator = m_pComposites.begin(); + while (iIterator != m_pComposites.end()) { + m_ResourceIndexMap.push_back(iIterator->first); + iIterator++; + } + + m_bHasResourceIndexMap = true; + } + + PModelBaseMaterialResource CModelCompositeMaterialsResource::getBaseMaterialResource() + { + return m_pBaseMaterialResource; + } +} + diff --git a/Source/Model/Classes/NMR_ModelContext.cpp b/Source/Model/Classes/NMR_ModelContext.cpp new file mode 100644 index 0000000..15baa14 --- /dev/null +++ b/Source/Model/Classes/NMR_ModelContext.cpp @@ -0,0 +1,66 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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 "Model/Classes/NMR_ModelContext.h" + +#include "Model/Classes/NMR_Model.h" +#include "Model/Classes/NMR_KeyStore.h" +#include "Common/NMR_SecureContext.h" +#include "Common/3MF_ProgressMonitor.h" +#include "Common/NMR_ModelWarnings.h" + +namespace NMR { + + + + CModelContext::CModelContext(_In_ PModel pModel) { + if (!pModel) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + m_pModel = pModel; + + m_pKeystore = pModel->getKeyStore(); + + m_pProgressMonitor = std::make_shared(); + + m_pSecureContext = std::make_shared(); + + m_pWarnings = std::make_shared(); + } + + nfBool CModelContext::isComplete() const { + return (nullptr != m_pModel && nullptr != m_pProgressMonitor && nullptr != m_pSecureContext); + } + + void CModelContext::SetProgressCallback(Lib3MFProgressCallback callback, void* userData) { + m_pProgressMonitor->SetProgressCallback(callback, userData); + } + + +} \ No newline at end of file diff --git a/Source/Model/Classes/NMR_ModelMeshBeamLatticeAttributes.cpp b/Source/Model/Classes/NMR_ModelMeshBeamLatticeAttributes.cpp new file mode 100644 index 0000000..de37fe3 --- /dev/null +++ b/Source/Model/Classes/NMR_ModelMeshBeamLatticeAttributes.cpp @@ -0,0 +1,54 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelMeshBeamLatticeAttribues.cpp implements the Model Mesh BeamLattice Attributes +class and is part of the BeamLattice extension to 3MF + +--*/ + +#include "Model/Classes/NMR_ModelMeshBeamLatticeAttributes.h" + +namespace NMR { + + CModelMeshBeamLatticeAttributes::CModelMeshBeamLatticeAttributes() + { + m_eClipMode = eModelBeamLatticeClipMode::MODELBEAMLATTICECLIPMODE_NONE; + m_bHasClippingMeshID = false; + m_pClippingMeshUniqueID = nullptr; + m_bHasRepresentationMeshID = false; + m_pRepresentationUniqueID = nullptr; + m_eBallMode = eModelBeamLatticeBallMode::MODELBEAMLATTICEBALLMODE_NONE; + } + + CModelMeshBeamLatticeAttributes::~CModelMeshBeamLatticeAttributes() + { + + } +} + + diff --git a/Source/Model/Classes/NMR_ModelMeshObject.cpp b/Source/Model/Classes/NMR_ModelMeshObject.cpp new file mode 100644 index 0000000..4829ea7 --- /dev/null +++ b/Source/Model/Classes/NMR_ModelMeshObject.cpp @@ -0,0 +1,230 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelMeshObject.cpp implements the Model Mesh Object Class. +A model mesh object is an in memory representation of the 3MF +mesh object. + +--*/ + +#include "Model/Classes/NMR_ModelObject.h" +#include "Model/Classes/NMR_ModelMeshObject.h" +#include "Common/Math/NMR_PairMatchingTree.h" + +namespace NMR { + + CModelMeshObject::CModelMeshObject(_In_ const ModelResourceID sID, _In_ CModel * pModel) + : CModelObject(sID, pModel) + { + m_pMesh = std::make_shared(); + m_pBeamLatticeAttributes = std::make_shared(); + } + + CModelMeshObject::CModelMeshObject(_In_ const ModelResourceID sID, _In_ CModel * pModel, _In_ PMesh pMesh) + : CModelObject(sID, pModel) + { + m_pMesh = pMesh; + if (m_pMesh.get() == nullptr) + m_pMesh = std::make_shared(); + m_pBeamLatticeAttributes = std::make_shared(); + } + + CModelMeshObject::~CModelMeshObject() + { + m_pMesh = NULL; + } + + _Ret_notnull_ CMesh * CModelMeshObject::getMesh() + { + return m_pMesh.get(); + } + + void CModelMeshObject::setMesh(_In_ PMesh pMesh) + { + if (!pMesh) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + m_pMesh = pMesh; + } + + void CModelMeshObject::mergeToMesh(_In_ CMesh * pMesh, _In_ const NMATRIX3 mMatrix) + { + __NMRASSERT(pMesh); + pMesh->mergeMesh(m_pMesh.get(), mMatrix); + } + + void CModelMeshObject::setObjectType(_In_ eModelObjectType ObjectType) + { + if ((ObjectType != MODELOBJECTTYPE_MODEL) && (ObjectType != MODELOBJECTTYPE_SOLIDSUPPORT)) { + if (m_pMesh->getBeamCount() > 0) + throw CNMRException(NMR_ERROR_BEAMLATTICE_INVALID_OBJECTTYPE); + } + CModelObject::setObjectType(ObjectType); + } + + nfBool CModelMeshObject::isValid() + { + eModelObjectType eType = getObjectType(); + switch (eType) { + case MODELOBJECTTYPE_MODEL: return isManifoldAndOriented(); + case MODELOBJECTTYPE_SUPPORT: return true; + case MODELOBJECTTYPE_SOLIDSUPPORT: return isManifoldAndOriented(); + case MODELOBJECTTYPE_SURFACE: return true; + default: + return false; + + } + } + + nfBool CModelMeshObject::hasSlices(nfBool bRecursive) + { + return (this->getSliceStack().get() != nullptr); + } + + nfBool CModelMeshObject::isValidForSlices(const NMATRIX3& totalParentMatrix) + { + if (!this->getSliceStack().get()) { + return true; + } + else { + return fnMATRIX3_isplanar(totalParentMatrix); + } + } + + nfBool CModelMeshObject::isValidForBeamLattices() + { + return ( (getObjectType() == eModelObjectType::MODELOBJECTTYPE_MODEL) || (getObjectType() == eModelObjectType::MODELOBJECTTYPE_SOLIDSUPPORT) ); + } + + nfBool CModelMeshObject::isManifoldAndOriented() + { + if (!m_pMesh->checkSanity()) + return false; + + nfUint32 nNodeCount = m_pMesh->getNodeCount(); + nfUint32 nFaceCount = m_pMesh->getFaceCount(); + + if (nNodeCount < 3) + return false; + if (nFaceCount < 3) + return false; + + CPairMatchingTree PairMatchingTree; + nfUint32 nFaceIndex; + nfInt32 nEdgeIndex; + nfInt32 nEdgeCounter = 0; + nfUint32 j; + + // Build Edge Tree + for (nFaceIndex = 0; nFaceIndex < nFaceCount; nFaceIndex++) { + MESHFACE * pFace = m_pMesh->getFace(nFaceIndex); + + for (j = 0; j < 3; j++) { + nfInt32 nNodeIndex1 = pFace->m_nodeindices[j]; + nfInt32 nNodeIndex2 = pFace->m_nodeindices[(j + 1) % 3]; + + if (!PairMatchingTree.checkMatch(nNodeIndex1, nNodeIndex2, nEdgeIndex)) { + PairMatchingTree.addMatch(nNodeIndex1, nNodeIndex2, nEdgeCounter); + nEdgeCounter++; + + if (nEdgeCounter > NMR_MESH_MAXEDGECOUNT) + throw CNMRException(NMR_ERROR_INVALIDEDGEINDEX); + } + } + + } + + // Count positively and negatively oriented edges... + std::vector PositiveOrientations; + std::vector NegativeOrientations; + + // Create Edge arrays + PositiveOrientations.resize(nEdgeCounter); + NegativeOrientations.resize(nEdgeCounter); + for (nEdgeIndex = 0; nEdgeIndex < nEdgeCounter; nEdgeIndex++) { + PositiveOrientations[nEdgeIndex] = 0; + NegativeOrientations[nEdgeIndex] = 0; + } + + for (nFaceIndex = 0; nFaceIndex < nFaceCount; nFaceIndex++) { + MESHFACE * pFace = m_pMesh->getFace(nFaceIndex); + + for (j = 0; j < 3; j++) { + nfInt32 nNodeIndex1 = pFace->m_nodeindices[j]; + nfInt32 nNodeIndex2 = pFace->m_nodeindices[(j + 1) % 3]; + + if (PairMatchingTree.checkMatch(nNodeIndex1, nNodeIndex2, nEdgeIndex)) { + if ((nEdgeIndex < 0) || (nEdgeIndex >= nEdgeCounter)) + throw CNMRException(NMR_ERROR_INVALIDEDGEINDEX); + + if (nNodeIndex1 <= nNodeIndex2) { + PositiveOrientations[nEdgeIndex]++; + } + else { + NegativeOrientations[nEdgeIndex]++; + } + } + else { + throw CNMRException(NMR_ERROR_INVALIDMESHTOPOLOGY); + } + } + } + + // Check Edge Orientations and determine manifoldness + for (nEdgeIndex = 0; nEdgeIndex < nEdgeCounter; nEdgeIndex++) { + if (PositiveOrientations[nEdgeIndex] != 1) + return false; + if (NegativeOrientations[nEdgeIndex] != 1) + return false; + } + + // Mesh is non-empty, oriented and manifold + return true; + } + + + _Ret_notnull_ PModelMeshBeamLatticeAttributes CModelMeshObject::getBeamLatticeAttributes() + { + return m_pBeamLatticeAttributes; + } + + void CModelMeshObject::setBeamLatticeAttributes(_In_ PModelMeshBeamLatticeAttributes pBeamLatticeAttributes) + { + if (!pBeamLatticeAttributes) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + m_pBeamLatticeAttributes = pBeamLatticeAttributes; + } + + void CModelMeshObject::extendOutbox(_Out_ NOUTBOX3& vOutBox, _In_ const NMATRIX3 mAccumulatedMatrix) + { + m_pMesh->extendOutbox(vOutBox, mAccumulatedMatrix); + } +} + + diff --git a/Source/Model/Classes/NMR_ModelMetaData.cpp b/Source/Model/Classes/NMR_ModelMetaData.cpp new file mode 100644 index 0000000..53c744b --- /dev/null +++ b/Source/Model/Classes/NMR_ModelMetaData.cpp @@ -0,0 +1,141 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelMetaData.cpp implements the Model MetaData Class. +A metadata item is an in memory representation of the 3MF +metadata, and can be attached to any 3MF model node. + +--*/ + +#include "Model/Classes/NMR_ModelMetaData.h" +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_StringUtils.h" + +namespace NMR { + + CModelMetaData::CModelMetaData(_In_ std::string sNameSpace, _In_ std::string sName, _In_ std::string sValue, + _In_ std::string sType, _In_ nfBool bPreserve) + { + if (!isValidNamespaceAndName(sNameSpace, sName)) + throw CNMRException(NMR_ERROR_INVALIDMETADATA); + + // TODO: this check SHOULD be more clever + // https://www.ibm.com/support/knowledgecenter/en/SS7J8H/com.ibm.odm.dserver.rules.designer.author/designing_bom_topics/tpc_bom_builtin_simple_types.html + if (sType.empty()) + throw CNMRException(NMR_ERROR_INVALIDMETADATA); + + m_sNameSpace = sNameSpace; + m_sName = sName; + m_sValue = sValue; + m_sType = sType; + m_bPreserve = bPreserve; + } + + std::string CModelMetaData::getName() + { + return m_sName; + } + + std::string CModelMetaData::getNameSpace() + { + return m_sNameSpace; + } + + std::string CModelMetaData::getKey() + { + return composeNamespaceAndNameIntoKey(m_sNameSpace, m_sName); + } + + std::string CModelMetaData::getValue() + { + return m_sValue; + } + + std::string CModelMetaData::getType() + { + return m_sType; + } + + nfBool CModelMetaData::getPreserve() { + return m_bPreserve; + } + + + void CModelMetaData::setName(std::string sName) + { + if (!isValidNamespaceAndName(m_sNameSpace, sName)) { + throw CNMRException(NMR_ERROR_INVALIDMETADATA); + } + m_sName = sName; + } + + void CModelMetaData::setNameSpace(std::string sNameSpace) + { + if (!isValidNamespaceAndName(sNameSpace, m_sName)) { + throw CNMRException(NMR_ERROR_INVALIDMETADATA); + } + m_sNameSpace = sNameSpace; + } + + void CModelMetaData::setValue(std::string sValue) + { + m_sValue = sValue; + } + + void CModelMetaData::setType(std::string sType) + { + if (sType.empty()) + throw CNMRException(NMR_ERROR_INVALIDMETADATA); + m_sType = sType; + } + + void CModelMetaData::setPreserve(nfBool bPreserve) + { + m_bPreserve = bPreserve; + } + + bool CModelMetaData::isValidNamespaceAndName(std::string sNameSpace, std::string sName) + { + if (sNameSpace.empty()) { + return ((sName == XML_3MF_METADATA_VALUE_1) || + (sName == XML_3MF_METADATA_VALUE_2) || + (sName == XML_3MF_METADATA_VALUE_3) || + (sName == XML_3MF_METADATA_VALUE_4) || + (sName == XML_3MF_METADATA_VALUE_5) || + (sName == XML_3MF_METADATA_VALUE_6) || + (sName == XML_3MF_METADATA_VALUE_7) || + (sName == XML_3MF_METADATA_VALUE_8) || + (sName == XML_3MF_METADATA_VALUE_9)); + } + else { + return !sName.empty(); + } + } + +} diff --git a/Source/Model/Classes/NMR_ModelMetaDataGroup.cpp b/Source/Model/Classes/NMR_ModelMetaDataGroup.cpp new file mode 100644 index 0000000..a2608ca --- /dev/null +++ b/Source/Model/Classes/NMR_ModelMetaDataGroup.cpp @@ -0,0 +1,120 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelMetaDataGroup.cpp implements the Model MetaData Group Class. + +--*/ + +#include "Model/Classes/NMR_ModelMetaDataGroup.h" +#include "Common/NMR_Exception.h" +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_StringUtils.h" + +namespace NMR { + + CModelMetaDataGroup::CModelMetaDataGroup() + { + } + + void CModelMetaDataGroup::clear() + { + m_MetaData.clear(); + m_MetaDataMap.clear(); + } + + + PModelMetaData CModelMetaDataGroup::addMetaData(_In_ std::string sNameSpace, _In_ std::string sName, _In_ std::string sValue, _In_ std::string sType, _In_ nfBool bPreserve) + { + if (hasMetaData(composeNamespaceAndNameIntoKey(sNameSpace, sName))) { + throw CNMRException(NMR_ERROR_DUPLICATEMETADATA); + } + + if (!CModelMetaData::isValidNamespaceAndName(sNameSpace, sName)) { + throw CNMRException(NMR_ERROR_INVALIDMETADATA); + } + + if (m_MetaData.size() >= XML_3MF_MAXMETADATACOUNT) + throw CNMRException(NMR_ERROR_INVALIDMETADATACOUNT); + + PModelMetaData pMetaData = std::make_shared(sNameSpace, sName, sValue, sType, bPreserve); + m_MetaData.push_back(pMetaData); + m_MetaDataMap.insert(std::make_pair(pMetaData->getKey(), pMetaData)); + return pMetaData; + } + + nfUint32 CModelMetaDataGroup::getMetaDataCount() + { + return (nfUint32)m_MetaData.size(); + } + + PModelMetaData CModelMetaDataGroup::getMetaData(_In_ nfUint32 nIndex) + { + nfUint32 nCount = getMetaDataCount(); + if (nIndex >= nCount) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + + PModelMetaData pMetaData = m_MetaData[nIndex]; + __NMRASSERT(pMetaData.get() != nullptr); + + return pMetaData; + } + + void CModelMetaDataGroup::removeMetaData(_In_ nfUint32 nIndex) + { + nfUint32 nCount = getMetaDataCount(); + if (nIndex >= nCount) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + + auto iIterator = m_MetaData.begin(); + if (nIndex > 0) + iIterator += nIndex; + m_MetaData.erase(iIterator); + } + + nfBool CModelMetaDataGroup::hasMetaData(_In_ std::string sKey) + { + std::map::iterator iIterator = m_MetaDataMap.find(sKey); + return iIterator != m_MetaDataMap.end(); + } + + void CModelMetaDataGroup::mergeMetaData(_In_ CModelMetaDataGroup * pSourceMetaDataGroup) + { + if (pSourceMetaDataGroup == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + nfUint32 nCount = pSourceMetaDataGroup->getMetaDataCount(); + nfUint32 nIndex; + + for (nIndex = 0; nIndex < nCount; nIndex++) { + std::string sName; + std::string sValue; + PModelMetaData metaData = pSourceMetaDataGroup->getMetaData(nIndex); + addMetaData(metaData->getNameSpace(), metaData->getName(), metaData->getValue(), metaData->getType(), metaData->getPreserve()); + } + } +} diff --git a/Source/Model/Classes/NMR_ModelMultiPropertyGroup.cpp b/Source/Model/Classes/NMR_ModelMultiPropertyGroup.cpp new file mode 100644 index 0000000..6c6a312 --- /dev/null +++ b/Source/Model/Classes/NMR_ModelMultiPropertyGroup.cpp @@ -0,0 +1,241 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelMultiPropertyGroup.cpp implements the Model Color Group Resource Class. +A color group is an in memory representation of the 3MF color groups node. + +--*/ + +#include "Model/Classes/NMR_ModelMultiPropertyGroup.h" + +#include "Model/Classes/NMR_ModelBaseMaterials.h" +#include "Model/Classes/NMR_ModelColorGroup.h" +#include "Model/Classes/NMR_ModelCompositeMaterials.h" +#include "Model/Classes/NMR_ModelTexture2DGroup.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_Exception.h" +#include + +namespace NMR { + + ; + CModelMultiPropertyGroupResource::CModelMultiPropertyGroupResource(_In_ const ModelResourceID sID, _In_ CModel * pModel) + : CModelResource(sID, pModel) + { + m_nNextPropertyID = 1; + } + + nfUint32 CModelMultiPropertyGroupResource::addMultiProperty(_In_ PModelMultiProperty pMultiProperty) + { + nfUint32 nID = m_nNextPropertyID; + if (getCount() >= XML_3MF_MAXRESOURCEINDEX) { + throw CNMRException(NMR_ERROR_TOOMANYCOMPOSITES); + } + + //// TODO check for valid PropertyID + //for (ModelPropertyID constituent : *pMultiProperty) { + // + //} + + m_vctMultiProperties.insert(std::make_pair(nID, pMultiProperty)); + + m_nNextPropertyID++; + + clearResourceIndexMap(); + + return nID; + } + + nfUint32 CModelMultiPropertyGroupResource::getCount() + { + return (nfUint32)m_vctMultiProperties.size(); + } + + PModelMultiProperty CModelMultiPropertyGroupResource::getMultiProperty(_In_ ModelPropertyID nPropertyID) + { + auto iIterator = m_vctMultiProperties.find(nPropertyID); + if (iIterator != m_vctMultiProperties.end()) { + return iIterator->second; + } + else { + throw CNMRException(NMR_ERROR_INVALIDINDEX); + } + } + + void CModelMultiPropertyGroupResource::setMultiProperty(_In_ ModelPropertyID nPropertyID, _In_ PModelMultiProperty pMultiProperty) + { + auto iIterator = m_vctMultiProperties.find(nPropertyID); + if (iIterator != m_vctMultiProperties.end()) { + // TODO: check whether the respective resource contains the PropertyID + // throw CNMRException(NMR_ERROR_PROPERTYIDNOTFOUND); + iIterator->second = pMultiProperty; + } + else { + throw CNMRException(NMR_ERROR_INVALIDINDEX); + } + } + + void CModelMultiPropertyGroupResource::removeMultiProperty(_In_ ModelPropertyID nPropertyID) + { + m_vctMultiProperties.erase(nPropertyID); + clearResourceIndexMap(); + } + + nfUint32 CModelMultiPropertyGroupResource::getLayerCount() + { + return nfUint32(m_vctLayers.size()); + } + + nfUint32 CModelMultiPropertyGroupResource::addLayer(_In_ MODELMULTIPROPERTYLAYER sLayer) + { + bool hasMaterial = false; + bool hasColorGroup = false; + for (MODELMULTIPROPERTYLAYER layer : m_vctLayers) + { + PModelResource pResource = Model()->findResource(layer.m_nUniqueResourceID); + hasMaterial |= (dynamic_cast(pResource.get())!=nullptr) + || (dynamic_cast(pResource.get()) != nullptr); + hasColorGroup |= (dynamic_cast(pResource.get()) != nullptr); + } + + PModelResource pResource = Model()->findResource(sLayer.m_nUniqueResourceID); + if ((dynamic_cast(pResource.get()) != nullptr)) + { + throw CNMRException(NMR_ERROR_MULTIPROPERTIES_MUST_NOT_CONTAIN_MULTIPROPERTIES); + } + + if (!( (dynamic_cast(pResource.get()) != nullptr) + || (dynamic_cast(pResource.get()) != nullptr) + || (dynamic_cast(pResource.get()) != nullptr) + || (dynamic_cast(pResource.get()) != nullptr) ) ) + { + throw CNMRException(NMR_ERROR_MULTIPROPERTIES_INVALID_RESOURCE); + } + + if (hasMaterial && ( (dynamic_cast(pResource.get()) != nullptr) + || (dynamic_cast(pResource.get()) != nullptr) ) + ) + { + throw CNMRException(NMR_ERROR_MULTIPROPERTIES_MUST_NOT_CONTAIN_MULTIPLE_MATERIALS); + } + + if (hasColorGroup && (dynamic_cast(pResource.get()) != nullptr)) + { + throw CNMRException(NMR_ERROR_MULTIPROPERTIES_MUST_NOT_CONTAIN_MULTIPLE_COLORGOURPS); + } + + + m_vctLayers.push_back(sLayer); + return nfUint32(m_vctLayers.size() - 1); + } + + MODELMULTIPROPERTYLAYER CModelMultiPropertyGroupResource::getLayer(_In_ nfUint32 nIndex) + { + if (nIndex > m_vctLayers.size() - 1) { + throw CNMRException(NMR_ERROR_INVALIDINDEX); + } + return m_vctLayers[nIndex]; + } + + void CModelMultiPropertyGroupResource::setLayer(_In_ nfUint32 nIndex, _In_ MODELMULTIPROPERTYLAYER sLayer) + { + if (nIndex > m_vctLayers.size() - 1) { + throw CNMRException(NMR_ERROR_INVALIDINDEX); + } + m_vctLayers[nIndex] = sLayer; + } + + void CModelMultiPropertyGroupResource::removeLayer(_In_ nfUint32 nIndex) + { + if (nIndex > m_vctLayers.size() - 1) { + throw CNMRException(NMR_ERROR_INVALIDINDEX); + } + m_vctLayers.erase(m_vctLayers.begin() + nIndex); + } + + void CModelMultiPropertyGroupResource::mergeFrom(_In_ CModelMultiPropertyGroupResource * pSourceMultiMaterialGroup) + { + if (pSourceMultiMaterialGroup == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + nfUint32 nCount = pSourceMultiMaterialGroup->getCount(); + pSourceMultiMaterialGroup->buildResourceIndexMap(); + for (nfUint32 nIndex = 0; nIndex < nCount; nIndex++) { + ModelPropertyID nPropertyID; + pSourceMultiMaterialGroup->mapResourceIndexToPropertyID(nIndex, nPropertyID); + PModelMultiProperty pCmposite = pSourceMultiMaterialGroup->getMultiProperty(nPropertyID); + addMultiProperty(pCmposite); + } + + nfUint32 nLayers = pSourceMultiMaterialGroup->getLayerCount(); + for (nfUint32 nIndex = 0; nIndex < nLayers; nIndex++) { + MODELMULTIPROPERTYLAYER layer = pSourceMultiMaterialGroup->getLayer(nIndex); + addLayer(layer); + } + + clearResourceIndexMap(); + } + + void CModelMultiPropertyGroupResource::buildResourceIndexMap() + { + m_ResourceIndexMap.clear(); + m_ResourceIndexMap.reserve(m_vctMultiProperties.size()); + + auto iIterator = m_vctMultiProperties.begin(); + while (iIterator != m_vctMultiProperties.end()) { + m_ResourceIndexMap.push_back(iIterator->first); + iIterator++; + } + + m_bHasResourceIndexMap = true; + } + + std::string CModelMultiPropertyGroupResource::blendMethodToString(_In_ eModelBlendMethod eBlendMethod) + { + switch (eBlendMethod) { + case MODELBLENDMETHOD_MIX: return XML_3MF_ATTRIBUTE_MULTIPROPERTIES_BLENDMETHOD_MIX; + case MODELBLENDMETHOD_MULTIPLY: return XML_3MF_ATTRIBUTE_MULTIPROPERTIES_BLENDMETHOD_MULTIPLY; + default: + return XML_3MF_ATTRIBUTE_MULTIPROPERTIES_BLENDMETHOD_MIX; + } + } + eModelBlendMethod CModelMultiPropertyGroupResource::stringToBlendMethod(_In_ std::string sBlendMethod) + { + if (sBlendMethod == XML_3MF_ATTRIBUTE_MULTIPROPERTIES_BLENDMETHOD_MIX) { + return MODELBLENDMETHOD_MIX; + } else if (sBlendMethod == XML_3MF_ATTRIBUTE_MULTIPROPERTIES_BLENDMETHOD_MULTIPLY) { + return MODELBLENDMETHOD_MULTIPLY; + } + else { + throw CNMRException(NMR_ERROR_INVALID_BLENDMETHOD_ATTRIBUTE); + } + } + +} + diff --git a/Source/Model/Classes/NMR_ModelObject.cpp b/Source/Model/Classes/NMR_ModelObject.cpp new file mode 100644 index 0000000..ccfd31e --- /dev/null +++ b/Source/Model/Classes/NMR_ModelObject.cpp @@ -0,0 +1,213 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelObject.cpp implements the Model Object Class. +A model object is an in memory representation of the 3MF model object. + +--*/ + +#include "Model/Classes/NMR_ModelObject.h" +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_Exception.h" + +namespace NMR { + + CModelObject::CModelObject(_In_ const ModelResourceID sID, _In_ CModel * pModel) + : CModelResource(sID, pModel) + { + m_ObjectType = MODELOBJECTTYPE_MODEL; + setUUID(std::make_shared()); + m_pSliceStack.reset(); + m_eSlicesMeshResolution = MODELSLICESMESHRESOLUTION_FULL; + m_MetaDataGroup = std::make_shared(); + + m_nComponentDepthLevel = 0; + } + + void CModelObject::mergeToMesh(_In_ CMesh * pMesh, _In_ const NMATRIX3 mMatrix) + { + // empty on purpose, to be implemented by child classes + } + + void CModelObject::mergeToMesh(_In_ CMesh * pMesh) + { + mergeToMesh(pMesh, fnMATRIX3_identity()); + } + + eModelObjectType CModelObject::getObjectType() + { + return m_ObjectType; + } + + void CModelObject::setObjectType(_In_ eModelObjectType ObjectType) + { + m_ObjectType = ObjectType; + } + + std::string CModelObject::getName() + { + return m_sName; + } + + void CModelObject::setName(_In_ std::string sName) + { + m_sName = sName; + } + + std::string CModelObject::getPartNumber() + { + return m_sPartNumber; + } + + void CModelObject::setPartNumber(_In_ std::string sPartNumber) + { + m_sPartNumber = sPartNumber; + } + + PUUID CModelObject::uuid() + { + return m_UUID; + } + + void CModelObject::setUUID(PUUID uuid) + { + getModel()->registerUUID(uuid); + getModel()->unRegisterUUID(m_UUID); + m_UUID = uuid; + } + + PModelMetaDataGroup CModelObject::metaDataGroup() + { + return m_MetaDataGroup; + } + + nfBool CModelObject::setObjectTypeString(_In_ std::string sTypeString, _In_ nfBool bRaiseException) + { + if (sTypeString == XML_3MF_OBJECTTYPE_OTHER) { + setObjectType(MODELOBJECTTYPE_OTHER); + return true; + } + if (sTypeString == XML_3MF_OBJECTTYPE_MODEL) { + setObjectType(MODELOBJECTTYPE_MODEL); + return true; + } + if (sTypeString == XML_3MF_OBJECTTYPE_SUPPORT) { + setObjectType(MODELOBJECTTYPE_SUPPORT); + return true; + } + if (sTypeString == XML_3MF_OBJECTTYPE_SOLIDSUPPORT) { + setObjectType(MODELOBJECTTYPE_SOLIDSUPPORT); + return true; + } + if (sTypeString == XML_3MF_OBJECTTYPE_SURFACE) { + setObjectType(MODELOBJECTTYPE_SURFACE); + return true; + } + + if (bRaiseException) + throw CNMRException(NMR_ERROR_INVALIDMODELOBJECTTYPE); + + return false; + } + + std::string CModelObject::getObjectTypeString() + { + switch (m_ObjectType) { + case MODELOBJECTTYPE_OTHER: + return std::string(XML_3MF_OBJECTTYPE_OTHER); + case MODELOBJECTTYPE_MODEL: + return std::string(XML_3MF_OBJECTTYPE_MODEL); + case MODELOBJECTTYPE_SUPPORT: + return std::string(XML_3MF_OBJECTTYPE_SUPPORT); + case MODELOBJECTTYPE_SOLIDSUPPORT: + return std::string(XML_3MF_OBJECTTYPE_SOLIDSUPPORT); + case MODELOBJECTTYPE_SURFACE: + return std::string(XML_3MF_OBJECTTYPE_SURFACE); + default: + return ""; + } + } + + void CModelObject::assignSliceStack(PModelSliceStack pSliceStack) { + if (pSliceStack == nullptr) + m_pSliceStack.reset(); + else { + m_pSliceStack = pSliceStack; + } + } + + PModelSliceStack CModelObject::getSliceStack() { + return m_pSliceStack; + } + + void CModelObject::setSlicesMeshResolution(eModelSlicesMeshResolution eMeshResolution) { + m_eSlicesMeshResolution = eMeshResolution; + } + + eModelSlicesMeshResolution CModelObject::slicesMeshResolution() const { + return m_eSlicesMeshResolution; + } + + void CModelObject::clearThumbnailAttachment() { + m_pThumbnailAttachment.reset(); + } + + void CModelObject::setThumbnailAttachment(_In_ PModelAttachment pThumbnailAttachment, bool bThrowIfIncorrect) + { + if (!pThumbnailAttachment) { + throw CNMRException(NMR_ERROR_INVALIDPARAM); + } + if ((pThumbnailAttachment->getRelationShipType() != PACKAGE_THUMBNAIL_RELATIONSHIP_TYPE) && (bThrowIfIncorrect)) { + throw CNMRException(NMR_ERROR_NOTEXTURESTREAM); + } + m_pThumbnailAttachment = pThumbnailAttachment; + } + + PModelAttachment CModelObject::getThumbnailAttachment() + { + return m_pThumbnailAttachment; + } + + nfUint32 CModelObject::getComponentDepthLevel() + { + return m_nComponentDepthLevel; + } + + void CModelObject::clearComponentDepthLevel() + { + m_nComponentDepthLevel = 0; + } + + void CModelObject::calculateComponentDepthLevel(nfUint32 nLevel) + { + if (nLevel >= m_nComponentDepthLevel) + m_nComponentDepthLevel = nLevel; + } + + +} diff --git a/Source/Model/Classes/NMR_ModelResource.cpp b/Source/Model/Classes/NMR_ModelResource.cpp new file mode 100644 index 0000000..c9a31d9 --- /dev/null +++ b/Source/Model/Classes/NMR_ModelResource.cpp @@ -0,0 +1,105 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelResource.cpp implements the Model Resource Class. +A model resource is an in memory representation of the 3MF +resource object. + +--*/ + +#include "Model/Classes/NMR_Model.h" +#include "Model/Classes/NMR_ModelResource.h" +#include "Common/NMR_Exception.h" + +namespace NMR { + + CModelResource::CModelResource(_In_ const ModelResourceID sResourceID, _In_ CModel * pModel) + { + if (!pModel) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + m_pModel = pModel; + m_pPackageResourceID = m_pModel->generatePackageResourceID(pModel->currentPath(), sResourceID); + m_bHasResourceIndexMap = false; + } + + CModelResource::~CModelResource() + { + m_pModel = NULL; + } + + CModel * CModelResource::Model() + { + return m_pModel; + } + + PPackageResourceID CModelResource::getPackageResourceID() + { + return m_pPackageResourceID; + } + + void CModelResource::setPackageResourceID(PPackageResourceID pID) + { + m_pModel->updateUniqueResourceID(m_pPackageResourceID->getUniqueID(), pID->getUniqueID()); + m_pPackageResourceID = pID; + } + + _Ret_notnull_ CModel * CModelResource::getModel() + { + return m_pModel; + } + + + void CModelResource::clearResourceIndexMap() + { + m_ResourceIndexMap.clear(); + m_bHasResourceIndexMap = false; + } + + void CModelResource::buildResourceIndexMap() + { + clearResourceIndexMap(); + m_bHasResourceIndexMap = true; + } + + nfBool CModelResource::hasResourceIndexMap() + { + return m_bHasResourceIndexMap; + } + + bool CModelResource::mapResourceIndexToPropertyID(_In_ ModelResourceIndex nPropertyIndex, _Out_ ModelPropertyID & nPropertyID) + { + if (nPropertyIndex < m_ResourceIndexMap.size()) { + nPropertyID = m_ResourceIndexMap[nPropertyIndex]; + return true; + } + + nPropertyID = 0; + return false; + } + +} diff --git a/Source/Model/Classes/NMR_ModelSlice.cpp b/Source/Model/Classes/NMR_ModelSlice.cpp new file mode 100644 index 0000000..7e059a6 --- /dev/null +++ b/Source/Model/Classes/NMR_ModelSlice.cpp @@ -0,0 +1,179 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelSliceStack.cpp: implementes the Model Slice Class. +A Model Slice represents a single slice as vertices and polygons + +--*/ + +#include "Model/Classes/NMR_ModelSlice.h" +#include "Common/NMR_Exception.h" + +namespace NMR { + CSlice::CSlice(nfDouble dZTop) + { + m_dZTop = dZTop; + } + + CSlice::CSlice(CSlice& other) + { + m_dZTop = other.m_dZTop; + m_Vertices = other.m_Vertices; + m_Polygons = other.m_Polygons; + } + + CSlice::~CSlice() + { + } + + nfUint32 CSlice::beginPolygon() + { + m_Polygons.push_back(std::vector()); + return (nfUint32)m_Polygons.size() - 1; + } + + void CSlice::Clear() + { + m_Polygons.clear(); + m_Vertices.clear(); + } + + nfUint32 CSlice::addVertex(nfFloat x, nfFloat y) + { + SLICENODE cNode; + + cNode.m_position.m_fields[0] = x; + cNode.m_position.m_fields[1] = y; + + cNode.m_index = (nfUint32)m_Vertices.size(); + + m_Vertices.push_back(cNode); + + return cNode.m_index; + } + + void CSlice::getVertex(nfUint32 nIndex, nfFloat *x, nfFloat *y) + { + if (nIndex >= m_Vertices.size()) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + + *x = m_Vertices[nIndex].m_position.m_values.x; + *y = m_Vertices[nIndex].m_position.m_values.y; + } + + void CSlice::clearPolygon(nfUint32 nPolygonIndex) + { + if (nPolygonIndex >= m_Polygons.size()) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + m_Polygons[nPolygonIndex].clear(); + } + + void CSlice::addPolygonIndex(nfUint32 nPolygonIndex, nfUint32 nIndex) + { + if (nPolygonIndex >= m_Polygons.size()) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + + if (nIndex >= m_Vertices.size()) + throw CNMRException(NMR_ERROR_INVALID_SLICESEGMENT_VERTEXINDEX); + + if (m_Polygons[nPolygonIndex].size() > 0) { + if (m_Polygons[nPolygonIndex][m_Polygons[nPolygonIndex].size()-1] == nIndex) + throw CNMRException(NMR_ERROR_INVALID_SLICESEGMENT_VERTEXINDEX); + } + m_Polygons[nPolygonIndex].push_back(nIndex); + } + + nfUint32 CSlice::getPolygonCount() + { + return (nfUint32)m_Polygons.size(); + } + + nfDouble CSlice::getTopZ() + { + return m_dZTop; + } + + void CSlice::setTopZ(nfDouble dZTop) + { + m_dZTop = dZTop; + } + + _Ret_notnull_ SLICENODE *CSlice::getNode(nfUint32 nIndex) + { + return &m_Vertices[nIndex]; + } + + nfUint32 CSlice::getVertexCount() + { + return (nfUint32)m_Vertices.size(); + } + + bool CSlice::allPolygonsAreClosed() + { + for (auto polygon : m_Polygons) { + if (polygon.size() > 1) { + if (*polygon.begin() != *polygon.rbegin()) { + return false; + } + } + } + return true; + } + + bool CSlice::isPolygonValid(nfUint32 nPolygonIndex) + { + if (nPolygonIndex >= m_Polygons.size()) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + if (m_Polygons[nPolygonIndex].size() > 2) + return true; + if (m_Polygons[nPolygonIndex].size() <= 1) + return false; + // closed polygon must have 3 points or more. + return m_Polygons[nPolygonIndex][0] != m_Polygons[nPolygonIndex][1]; + } + + nfUint32 CSlice::getPolygonIndex(nfUint32 nPolygonIndex, nfUint32 nIndexOfIndex) + { + if (nPolygonIndex >= m_Polygons.size()) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + + if (nIndexOfIndex >= m_Polygons[nPolygonIndex].size()) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + + return m_Polygons[nPolygonIndex][nIndexOfIndex]; + } + + nfUint32 CSlice::getPolygonIndexCount(nfUint32 nPolygonIndex) + { + if (nPolygonIndex >= m_Polygons.size()) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + + return (nfUint32)m_Polygons[nPolygonIndex].size(); + } +} + diff --git a/Source/Model/Classes/NMR_ModelSliceStack.cpp b/Source/Model/Classes/NMR_ModelSliceStack.cpp new file mode 100644 index 0000000..7a25395 --- /dev/null +++ b/Source/Model/Classes/NMR_ModelSliceStack.cpp @@ -0,0 +1,204 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelSliceStackResource.h: implements the resource object for a slice stack + +--*/ + +#include "Model/Classes/NMR_ModelSliceStack.h" +#include "Model/Classes/NMR_ModelResource.h" +#include "Common/NMR_Exception.h" + +#include + +namespace NMR { + + CModelSliceStack::CModelSliceStack(_In_ const ModelResourceID sID, _In_ CModel * pModel, nfDouble dZBottom) + : CModelResource(sID, pModel) + { + m_dZBottom = dZBottom; + } + + CModelSliceStack::~CModelSliceStack() + { + + } + + PSlice CModelSliceStack::AddSlice(const nfDouble dZTop) + { + if (!AllowsGeometry()) { + throw CNMRException(NMR_ERROR_SLICES_MIXING_SLICES_WITH_SLICEREFS); + } + + if (m_pSlices.size() > 0) + { + if (m_pSlices.back()->getTopZ() >= dZTop) + throw CNMRException(NMR_ERROR_SLICES_Z_NOTINCREASING); + } + else { + if (m_dZBottom >= dZTop) + throw CNMRException(NMR_ERROR_SLICES_Z_NOTINCREASING); + } + PSlice pSlice = std::make_shared(dZTop); + m_pSlices.push_back(pSlice); + return pSlice; + } + + void CModelSliceStack::AddSliceRef(PModelSliceStack pOtherStack, bool bPedantic) + { + if (!AllowsReferences()) { + throw CNMRException(NMR_ERROR_SLICES_MIXING_SLICES_WITH_SLICEREFS); + } + if (this == pOtherStack.get()) { + throw CNMRException(NMR_ERROR_SLICES_SLICEREF_CIRCULAR); + } + if (pOtherStack->getSliceRefCount() > 0) { + throw CNMRException(NMR_ERROR_SLICES_REFS_LEVELTOODEEP); + } + if (bPedantic) { + if (pOtherStack->getZBottom() < getHighestZ()) { + throw CNMRException(NMR_ERROR_SLICES_REFS_Z_NOTINCREASING); + } + } + + // TODO: check in model, whether "this" is used as sliceref anywhere in the model + m_pSliceRefs.push_back(pOtherStack); + } + + nfUint32 CModelSliceStack::getSliceCount() + { + return nfUint32(m_pSlices.size()); + } + + PSlice CModelSliceStack::getSlice(nfUint32 nIndex) + { + if (nIndex >= m_pSlices.size()) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + return m_pSlices[nIndex]; + } + + bool CModelSliceStack::AllowsGeometry() const + { + return m_pSliceRefs.empty(); + } + + nfUint32 CModelSliceStack::getSliceRefCount() + { + return nfUint32(m_pSliceRefs.size()); + } + + PModelSliceStack CModelSliceStack::getSliceRef(nfUint32 nIndex) + { + if (nIndex >= m_pSliceRefs.size()) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + return m_pSliceRefs[nIndex]; + } + + bool CModelSliceStack::AllowsReferences() const + { + return m_pSlices.empty(); + } + + + void CModelSliceStack::CollapseSliceReferences() + { + m_pSlices.clear(); + nfUint64 nSlices = 0; + for (auto pStack : m_pSliceRefs) { + nSlices += pStack->getSliceCount(); + } + m_pSlices.reserve(nSlices); + for (auto pStack : m_pSliceRefs) { + for (auto pOldSlice : pStack->m_pSlices) { + m_pSlices.push_back(std::make_shared(*pOldSlice.get())); + } + } + } + + std::string CModelSliceStack::OwnPath() + { + std::string sPath = getPackageResourceID()->getPath(); + if (sPath.empty()) { + throw CNMRException(NMR_ERROR_INVALID_SLICEPATH); + } + return sPath; + } + + void CModelSliceStack::SetOwnPath(std::string sOwnPath) + { + PPackageModelPath pModelPath = getModel()->findOrCreateModelPath(sOwnPath); + CPackageResourceID::setModelPath(getPackageResourceID(), pModelPath); + } + + nfDouble CModelSliceStack::getZBottom() + { + return m_dZBottom; + } + + void CModelSliceStack::setZBottom(nfDouble dZBottom) + { + if (!m_pSlices.empty()) { + if (m_pSlices.front()->getTopZ() <= dZBottom) + throw CNMRException(NMR_ERROR_SLICES_Z_NOTINCREASING); + } + if (!m_pSliceRefs.empty()) { + if (m_pSliceRefs.front()->getZBottom() < dZBottom) + throw CNMRException(NMR_ERROR_SLICES_Z_NOTINCREASING); + } + m_dZBottom = dZBottom; + } + + nfDouble CModelSliceStack::getHighestZ() const + { + nfDouble dHighestZ = m_dZBottom; + if (!m_pSlices.empty()) { + dHighestZ = std::max(dHighestZ, m_pSlices.back()->getTopZ()); + } + if (!m_pSliceRefs.empty()) { + dHighestZ = std::max(dHighestZ, m_pSliceRefs.back()->getHighestZ()); + } + return dHighestZ; + } + + bool CModelSliceStack::areAllPolygonsClosed() + { + for (auto pSlice : m_pSlices) { + if (!pSlice->allPolygonsAreClosed()) + return false; + } + + for (auto pSliceRef : m_pSliceRefs) { + if (!pSliceRef->areAllPolygonsClosed()) + return false; + } + + return true; + } + +} + diff --git a/Source/Model/Classes/NMR_ModelTexture2D.cpp b/Source/Model/Classes/NMR_ModelTexture2D.cpp new file mode 100644 index 0000000..319ea27 --- /dev/null +++ b/Source/Model/Classes/NMR_ModelTexture2D.cpp @@ -0,0 +1,295 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelTexture2D.cpp implements the Model Texture Class. + +--*/ + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_ModelTexture2D.h" +#include "Model/Classes/NMR_ModelTextureAttachment.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_StringUtils.h" +#include +#include + +namespace NMR { + + + + CModelTexture2DResource::CModelTexture2DResource(_In_ const ModelResourceID sID, _In_ CModel * pModel, _In_ PModelAttachment pAttachment) + :CModelResource(sID, pModel), m_pAttachment(pAttachment) + { + m_ContentType = MODELTEXTURETYPE_PNG; + m_bHasBox2D = false; + m_fBox2D_U = 0.0f; + m_fBox2D_V = 0.0f; + m_fBox2D_Width = 1.0f; + m_fBox2D_Height = 1.0f; + m_eTileStyleU = MODELTEXTURETILESTYLE_WRAP; + m_eTileStyleV = MODELTEXTURETILESTYLE_WRAP; + m_eFilter = MODELTEXTUREFILTER_AUTO; + } + + PModelTexture2DResource CModelTexture2DResource::make(_In_ const ModelResourceID sID, _In_ CModel * pModel, _In_ PModelAttachment pAttachment) + { + if (!pAttachment.get()) + throw CNMRException(NMR_ERROR_INVALIDTEXTURE); + if (pAttachment->getRelationShipType() != PACKAGE_TEXTURE_RELATIONSHIP_TYPE) + throw CNMRException(NMR_ERROR_INVALIDRELATIONSHIPTYPEFORTEXTURE); + if (pAttachment->getModel() != pModel) + throw CNMRException(NMR_ERROR_ATTACHMENTMODELMISMATCH); + + return std::make_shared(CModelTexture2DResource(sID, pModel, pAttachment)); + } + + PModelAttachment CModelTexture2DResource::getAttachment() + { + if (m_pAttachment->getRelationShipType() != PACKAGE_TEXTURE_RELATIONSHIP_TYPE) + throw CNMRException(NMR_ERROR_INVALIDRELATIONSHIPTYPEFORTEXTURE); + return m_pAttachment; + } + + void CModelTexture2DResource::setAttachment(PModelAttachment pAttachment) + { + if (pAttachment.get() == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + if (pAttachment->getModel() != getModel()) + throw CNMRException(NMR_ERROR_ATTACHMENTMODELMISMATCH); + + if (pAttachment->getRelationShipType() != PACKAGE_TEXTURE_RELATIONSHIP_TYPE) + throw CNMRException(NMR_ERROR_INVALIDRELATIONSHIPTYPEFORTEXTURE); + + m_pAttachment = pAttachment; + } + + // getters/setters ContentType + eModelTexture2DType CModelTexture2DResource::getContentType() + { + return m_ContentType; + } + + void CModelTexture2DResource::setContentType(_In_ eModelTexture2DType ContentType) + { + m_ContentType = ContentType; + } + + std::string CModelTexture2DResource::getContentTypeString() + { + switch (m_ContentType) { + case MODELTEXTURETYPE_PNG: return PACKAGE_PNG_CONTENT_TYPE; + case MODELTEXTURETYPE_JPEG: return PACKAGE_JPG_CONTENT_TYPE; + default: return ""; + } + + } + + void CModelTexture2DResource::setContentTypeString(_In_ std::string sValue, _In_ nfBool bFailIfUnknown) + { + std::transform(sValue.begin(), sValue.end(), sValue.begin(), ::tolower); + + if (strcmp(sValue.c_str(), PACKAGE_PNG_CONTENT_TYPE) == 0) { + m_ContentType = MODELTEXTURETYPE_PNG; + return; + } + + if (strcmp(sValue.c_str(), PACKAGE_JPG_CONTENT_TYPE) == 0) { + m_ContentType = MODELTEXTURETYPE_JPEG; + return; + } + + if (bFailIfUnknown) + throw CNMRException(NMR_ERROR_INVALIDCONTENTTYPE); + + m_ContentType = MODELTEXTURETYPE_UNKNOWN; + + } + + + void CModelTexture2DResource::setTileStyleUString(_In_ std::string sValue) + { + m_eTileStyleU = CModelTexture2DResource::tileStyleFromString(sValue); + } + + void CModelTexture2DResource::setTileStyleVString(_In_ std::string sValue) + { + m_eTileStyleV = CModelTexture2DResource::tileStyleFromString(sValue); + } + + void CModelTexture2DResource::setFilterFromString(_In_ std::string sValue) + { + setFilter(CModelTexture2DResource::filterFromString(sValue)); + } + + + // getters/setters Box2D + nfBool CModelTexture2DResource::getBox2D(_Out_ nfFloat & fU, _Out_ nfFloat & fV, _Out_ nfFloat & fWidth, _Out_ nfFloat & fHeight) + { + if (m_bHasBox2D) { + fU = m_fBox2D_U; + fV = m_fBox2D_V; + fWidth = m_fBox2D_Width; + fHeight = m_fBox2D_Height; + return true; + } + else { + fU = 0.0f; + fV = 0.0f; + fWidth = 1.0f; + fHeight = 1.0f; + return false; + } + } + + void CModelTexture2DResource::setBox2D(_In_ nfFloat fU, _In_ nfFloat fV, _In_ nfFloat fWidth, _In_ nfFloat fHeight) + { + m_bHasBox2D = true; + m_fBox2D_U = fU; + m_fBox2D_V = fV; + m_fBox2D_Width = fWidth; + m_fBox2D_Height = fHeight; + } + + void CModelTexture2DResource::clearBox2D() + { + m_bHasBox2D = false; + m_fBox2D_U = 0.0f; + m_fBox2D_V = 0.0f; + m_fBox2D_Width = 1.0f; + m_fBox2D_Height = 1.0f; + } + + nfBool CModelTexture2DResource::hasBox2D() + { + return m_bHasBox2D; + } + + // getters/setters TileStyle + eModelTextureTileStyle CModelTexture2DResource::getTileStyleU() + { + return m_eTileStyleU; + } + + eModelTextureTileStyle CModelTexture2DResource::getTileStyleV() + { + return m_eTileStyleV; + } + + void CModelTexture2DResource::setTileStyleU(_In_ eModelTextureTileStyle sStyle) + { + m_eTileStyleU = sStyle; + } + + void CModelTexture2DResource::setTileStyleV(_In_ eModelTextureTileStyle sStyle) + { + m_eTileStyleV = sStyle; + } + + eModelTextureFilter CModelTexture2DResource::getFilter() + { + return m_eFilter; + } + void CModelTexture2DResource::setFilter(_In_ eModelTextureFilter eFilter) + { + m_eFilter = eFilter; + } + + void CModelTexture2DResource::copyFrom(_In_ CModelTexture2DResource * pSourceTexture, _In_ nfBool bCopyAttachment) + { + if (pSourceTexture == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + if (bCopyAttachment) + setAttachment(pSourceTexture->getAttachment()); + + setContentType(pSourceTexture->getContentType ()); + setTileStyleU(pSourceTexture->getTileStyleU()); + setTileStyleV(pSourceTexture->getTileStyleV()); + if (pSourceTexture->hasBox2D()) { + nfFloat fU, fV, fWidth, fHeight; + pSourceTexture->getBox2D(fU, fV, fWidth, fHeight); + setBox2D(fU, fV, fWidth, fHeight); + } + else { + clearBox2D(); + } + } + + eModelTextureTileStyle CModelTexture2DResource::tileStyleFromString(_In_ std::string sValue) + { + std::transform(sValue.begin(), sValue.end(), sValue.begin(), ::tolower); + if (strcmp(sValue.c_str(), XML_3MF_ATTRIBUTE_TEXTURE2D_TILESTYLE_NONE) == 0) + return MODELTEXTURETILESTYLE_NONE; + if (strcmp(sValue.c_str(), XML_3MF_ATTRIBUTE_TEXTURE2D_TILESTYLE_CLAMP) == 0) + return MODELTEXTURETILESTYLE_CLAMP; + if (strcmp(sValue.c_str(), XML_3MF_ATTRIBUTE_TEXTURE2D_TILESTYLE_WRAP) == 0) + return MODELTEXTURETILESTYLE_WRAP; + if (strcmp(sValue.c_str(), XML_3MF_ATTRIBUTE_TEXTURE2D_TILESTYLE_MIRROR) == 0) + return MODELTEXTURETILESTYLE_MIRROR; + throw CNMRException(NMR_ERROR_INVALIDTILESTYLE); + return MODELTEXTURETILESTYLE_WRAP; + } + + std::string CModelTexture2DResource::tileStyleToString(_In_ eModelTextureTileStyle eTileStyle) + { + switch (eTileStyle) { + case MODELTEXTURETILESTYLE_WRAP: return XML_3MF_ATTRIBUTE_TEXTURE2D_TILESTYLE_WRAP; + case MODELTEXTURETILESTYLE_MIRROR: return XML_3MF_ATTRIBUTE_TEXTURE2D_TILESTYLE_MIRROR; + case MODELTEXTURETILESTYLE_CLAMP: return XML_3MF_ATTRIBUTE_TEXTURE2D_TILESTYLE_CLAMP; + case MODELTEXTURETILESTYLE_NONE: return XML_3MF_ATTRIBUTE_TEXTURE2D_TILESTYLE_NONE; + default: + return XML_3MF_ATTRIBUTE_TEXTURE2D_TILESTYLE_WRAP; + } + } + + eModelTextureFilter CModelTexture2DResource::filterFromString(_In_ std::string sValue) + { + std::transform(sValue.begin(), sValue.end(), sValue.begin(), ::tolower); + if (strcmp(sValue.c_str(), XML_3MF_ATTRIBUTE_TEXTURE2D_FILTER_AUTO) == 0) + return MODELTEXTUREFILTER_AUTO; + if (strcmp(sValue.c_str(), XML_3MF_ATTRIBUTE_TEXTURE2D_FILTER_LINEAR) == 0) + return MODELTEXTUREFILTER_LINEAR; + if (strcmp(sValue.c_str(), XML_3MF_ATTRIBUTE_TEXTURE2D_FILTER_NEAREST) == 0) + return MODELTEXTUREFILTER_NEAREST; + throw CNMRException(NMR_ERROR_INVALIDFILTER); + return MODELTEXTUREFILTER_AUTO; + } + + std::string CModelTexture2DResource::filterToString(_In_ eModelTextureFilter eFilter) + { + switch (eFilter) { + case MODELTEXTUREFILTER_AUTO: return XML_3MF_ATTRIBUTE_TEXTURE2D_FILTER_AUTO; + case MODELTEXTUREFILTER_LINEAR: return XML_3MF_ATTRIBUTE_TEXTURE2D_FILTER_LINEAR; + case MODELTEXTUREFILTER_NEAREST: return XML_3MF_ATTRIBUTE_TEXTURE2D_FILTER_NEAREST; + default: + return XML_3MF_ATTRIBUTE_TEXTURE2D_FILTER_AUTO; + } + } + +} diff --git a/Source/Model/Classes/NMR_ModelTexture2DGroup.cpp b/Source/Model/Classes/NMR_ModelTexture2DGroup.cpp new file mode 100644 index 0000000..3826e13 --- /dev/null +++ b/Source/Model/Classes/NMR_ModelTexture2DGroup.cpp @@ -0,0 +1,137 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelTexture2DGroup.cpp implements the Model Color Group Resource Class. +A color group is an in memory representation of the 3MF color groups node. + +--*/ + +#include "Model/Classes/NMR_ModelTexture2DGroup.h" +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_Exception.h" +#include + +namespace NMR { + + CModelTexture2DGroupResource::CModelTexture2DGroupResource(_In_ const ModelResourceID sID, + _In_ CModel * pModel, _In_ PModelTexture2DResource pTexture2D) + : CModelResource(sID, pModel) + { + m_nNextPropertyID = 1; + if (!pTexture2D.get()) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + m_pTexture2D = pTexture2D; + } + + nfUint32 CModelTexture2DGroupResource::addUVCoordinate(_In_ MODELTEXTURE2DCOORDINATE UV) + { + nfUint32 nID = m_nNextPropertyID; + if (getCount() >= XML_3MF_MAXRESOURCEINDEX) { + throw CNMRException(NMR_ERROR_TOOMANYCOLORS); + } + + m_pUVCoordinates.insert(std::make_pair(nID, UV)); + + m_nNextPropertyID++; + + clearResourceIndexMap(); + + return nID; + } + + nfUint32 CModelTexture2DGroupResource::getCount() + { + return (nfUint32)m_pUVCoordinates.size(); + } + + void CModelTexture2DGroupResource::setUVCoordinate(_In_ ModelPropertyID nPropertyID, _In_ MODELTEXTURE2DCOORDINATE sCoordinate) + { + auto iIterator = m_pUVCoordinates.find(nPropertyID); + if (iIterator != m_pUVCoordinates.end()) { + iIterator->second = sCoordinate; + } + else { + throw CNMRException(NMR_ERROR_INVALIDINDEX); + } + } + + void CModelTexture2DGroupResource::removePropertyID(_In_ ModelPropertyID nPropertyID) + { + m_pUVCoordinates.erase(nPropertyID); + clearResourceIndexMap(); + } + + MODELTEXTURE2DCOORDINATE CModelTexture2DGroupResource::getUVCoordinate(_In_ ModelPropertyID nPropertyID) + { + auto iIterator = m_pUVCoordinates.find(nPropertyID); + if (iIterator != m_pUVCoordinates.end()) { + return iIterator->second; + } + else { + throw CNMRException(NMR_ERROR_INVALIDINDEX); + } + } + + void CModelTexture2DGroupResource::mergeFrom(_In_ CModelTexture2DGroupResource * pSourceTexture2DGroup) + { + if (pSourceTexture2DGroup == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + nfUint32 nCount = pSourceTexture2DGroup->getCount(); + pSourceTexture2DGroup->buildResourceIndexMap(); + + for (nfUint32 nIndex = 0; nIndex < nCount; nIndex++) { + ModelPropertyID nPropertyID; + pSourceTexture2DGroup->mapResourceIndexToPropertyID(nIndex, nPropertyID); + MODELTEXTURE2DCOORDINATE UVCoordinate = pSourceTexture2DGroup->getUVCoordinate(nPropertyID); + addUVCoordinate(UVCoordinate); + } + clearResourceIndexMap(); + } + + void CModelTexture2DGroupResource::buildResourceIndexMap() + { + m_ResourceIndexMap.clear(); + m_ResourceIndexMap.reserve(m_pUVCoordinates.size()); + + auto iIterator = m_pUVCoordinates.begin(); + while (iIterator != m_pUVCoordinates.end()) { + m_ResourceIndexMap.push_back(iIterator->first); + iIterator++; + } + + m_bHasResourceIndexMap = true; + } + + + PModelTexture2DResource CModelTexture2DGroupResource::getTexture2D() + { + return m_pTexture2D; + } +} + diff --git a/Source/Model/Classes/NMR_PackageResourceID.cpp b/Source/Model/Classes/NMR_PackageResourceID.cpp new file mode 100644 index 0000000..1d5dc9a --- /dev/null +++ b/Source/Model/Classes/NMR_PackageResourceID.cpp @@ -0,0 +1,233 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_PackageResourceID.cpp implements the UniqueResourceID Class. + +--*/ + +#include "Model/Classes/NMR_PackageResourceID.h" +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" + +#include + +namespace NMR { + + CPackageModelPath::CPackageModelPath(CResourceHandler* pResourceHandler, std::string sPath) + : m_pResourceHandler(pResourceHandler), m_sPath(sPath) + { + if (pResourceHandler == nullptr) { + throw CNMRException(NMR_ERROR_INVALIDPOINTER); + } + } + + std::string CPackageModelPath::getPath() + { + return m_sPath; + } + + void CPackageModelPath::setPath(std::string sPath) + { + if (m_sPath != sPath) { + PPackageModelPath pPath = m_pResourceHandler->findPackageModelPath(sPath); + if (pPath) { + throw CNMRException(NMR_ERROR_DUPLICATEPACKAGEPATH); + } + m_sPath = sPath; + } + } + + CPackageResourceID::CPackageResourceID(CResourceHandler* pResourceHandler, PPackageModelPath pModelPath, ModelResourceID nID) + : m_pResourceHandler(pResourceHandler), m_pModelPath(pModelPath), m_id(nID) + { + if (pResourceHandler == nullptr || pModelPath == nullptr) { + throw CNMRException(NMR_ERROR_INVALIDPOINTER); + } + } + + PPackageModelPath CPackageResourceID::getPackageModelPath() { + return m_pModelPath; + } + std::string CPackageResourceID::getPath() { + return m_pModelPath->getPath(); + } + + ModelResourceID CPackageResourceID::getModelResourceID() { + return m_id; + } + + void CPackageResourceID::setModelPath(std::shared_ptr pPackageResourceID, PPackageModelPath pPath) + { + pPackageResourceID->m_pResourceHandler->updateModelPath(pPackageResourceID, pPath); + } + + CResourceHandler * CPackageResourceID::getResourceHandler() { + return m_pResourceHandler; + } + + void CPackageResourceID::setUniqueID(UniqueResourceID id) { + m_uniqueID = id; + } + UniqueResourceID CPackageResourceID::getUniqueID() { + return m_uniqueID; + } + + PPackageModelPath CResourceHandler::makePackageModelPath(std::string sPath) + { + if (findPackageModelPath(sPath)) { + throw CNMRException(NMR_ERROR_DUPLICATEPACKAGEPATH); + } + PPackageModelPath pModelPath = std::make_shared(this, sPath); + m_PathToModelPath.insert(std::make_pair(sPath, pModelPath)); + return pModelPath; + } + + std::vector CResourceHandler::retrieveAllModelPaths() + { + std::vector vctPModelPaths; + vctPModelPaths.reserve(m_PathToModelPath.size()); + for (auto pModelPathPair : m_PathToModelPath) { + vctPModelPaths.push_back(pModelPathPair.second); + } + return vctPModelPaths; + } + + PPackageModelPath CResourceHandler::findPackageModelPath(std::string sPath) + { + auto it = m_PathToModelPath.find(sPath); + if (it != m_PathToModelPath.end()) + { + return it->second; + } + return nullptr; + } + + // this is supposed to be the only way to generate a CPackageResourceID + PPackageResourceID CResourceHandler::makePackageResourceID(std::string path, ModelResourceID id) + { + PPackageModelPath pModelPath = findPackageModelPath(path); + if (!pModelPath) { + pModelPath = makePackageModelPath(path); + } + // This can be optimized + if (findResourceIDByPair(pModelPath->getPath(), id)) + throw CNMRException(NMR_ERROR_DUPLICATERESOURCEID); + + PPackageResourceID pPackageResourceID = std::make_shared(this, pModelPath, id); + UniqueIDPackageIdMap::const_iterator biggestId = std::max_element(m_resourceIDs.begin(), m_resourceIDs.end(), [](const UniqueIdPackageIdPair & v1, const UniqueIdPackageIdPair v2) { + return v1.first < v2.first; + }); + if (biggestId != m_resourceIDs.end()) { + pPackageResourceID->setUniqueID(int(biggestId->first) + 1); + } else { + pPackageResourceID->setUniqueID(1); + } + + + m_resourceIDs.insert(std::make_pair(pPackageResourceID->getUniqueID(), pPackageResourceID)); + m_IdAndPathToPackageResourceIDs.insert(std::make_pair(std::make_pair(id, pModelPath), pPackageResourceID)); + return pPackageResourceID; + } + + PPackageResourceID CResourceHandler::findResourceIDByUniqueID(UniqueResourceID id) + { + auto it = m_resourceIDs.find(id); + if (it != m_resourceIDs.end()) + { + return it->second; + } + return nullptr; + } + + PPackageResourceID CResourceHandler::findResourceIDByPair(std::string path, ModelResourceID id) + { + PPackageModelPath pModelPath = findPackageModelPath(path); + if (pModelPath) { + auto it = m_IdAndPathToPackageResourceIDs.find(std::make_pair(id, pModelPath)); + if (it != m_IdAndPathToPackageResourceIDs.end()) + { + return it->second; + } + } + return nullptr; + } + + void CResourceHandler::updateModelPath(PPackageResourceID pPackageResourceID, PPackageModelPath pNewPath) + { + if (pPackageResourceID == nullptr || pNewPath == nullptr) { + throw CNMRException(NMR_ERROR_INVALIDPOINTER); + } + + PPackageModelPath pOldPath = pPackageResourceID->m_pModelPath; + + if (pNewPath == pOldPath) { + return; + } + + auto itOld = m_IdAndPathToPackageResourceIDs.find(std::make_pair(pPackageResourceID->m_id, pOldPath)); + if (itOld == m_IdAndPathToPackageResourceIDs.end()) + { + throw CNMRException(NMR_ERROR_INVALIDPARAM); + } + + auto itNew = m_IdAndPathToPackageResourceIDs.find(std::make_pair(pPackageResourceID->m_id, pNewPath)); + if (itNew != m_IdAndPathToPackageResourceIDs.end()) + { + throw CNMRException(NMR_ERROR_INVALIDPARAM); + } + + m_IdAndPathToPackageResourceIDs.erase(itOld); + //what if idOld was the last one standing pointint to PackageModelPath? + + pPackageResourceID->m_pModelPath = pNewPath; + m_IdAndPathToPackageResourceIDs.insert(std::make_pair(std::make_pair(pPackageResourceID->m_id, pNewPath), pPackageResourceID)); + } + + void CResourceHandler::removePackageResourceID(PPackageResourceID pPackageResourceID) + { + auto it = m_IdAndPathToPackageResourceIDs.find(std::make_pair(pPackageResourceID->m_id, pPackageResourceID->getPackageModelPath())); + if (it == m_IdAndPathToPackageResourceIDs.end()) + { + throw CNMRException(NMR_ERROR_INVALIDPARAM); + } + + auto itID = m_resourceIDs.find(pPackageResourceID->m_uniqueID); + if (itID == m_resourceIDs.end()) + { + throw CNMRException(NMR_ERROR_INVALIDPARAM); + } + m_IdAndPathToPackageResourceIDs.erase(it); + m_resourceIDs.erase(itID); + } + + void CResourceHandler::clear() { + m_resourceIDs.clear(); + m_IdAndPathToPackageResourceIDs.clear(); + } + +} diff --git a/Source/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Ball.cpp b/Source/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Ball.cpp new file mode 100644 index 0000000..0d8d4b5 --- /dev/null +++ b/Source/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Ball.cpp @@ -0,0 +1,126 @@ +/*++ + +Copyright (C) 2020 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_BeamLattice1702_Ball.cpp covers the official 3MF beamlattice extension. + +--*/ + +#include "Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Ball.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_ModelMeshObject.h" + +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + eModelBeamLatticeBallMode stringToBallMode(const nfChar* ballModeStr) + { + if (strcmp(ballModeStr, XML_3MF_BEAMLATTICE_BALLMODE_MIXED) == 0) + return eModelBeamLatticeBallMode::MODELBEAMLATTICEBALLMODE_MIXED; + if (strcmp(ballModeStr, XML_3MF_BEAMLATTICE_BALLMODE_ALL) == 0) + return eModelBeamLatticeBallMode::MODELBEAMLATTICEBALLMODE_ALL; + return eModelBeamLatticeBallMode::MODELBEAMLATTICEBALLMODE_NONE; + } + + CModelReaderNode_BeamLattice1702_Ball::CModelReaderNode_BeamLattice1702_Ball(_In_ CModel* pModel, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + m_nIndex = -1; + + m_bHasRadius = false; + m_dRadius = 0; + + m_bHasRadius = false; + + m_bHasTag = false; + m_nTag = -1; + } + + void CModelReaderNode_BeamLattice1702_Ball::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + } + + void CModelReaderNode_BeamLattice1702_Ball::retrieveIndex(_Out_ nfInt32 & nIndex, nfInt32 nNodeCount) + { + if ((m_nIndex < 0) || m_nIndex >= nNodeCount) + throw CNMRException(NMR_ERROR_INVALIDMODELNODEINDEX); + + nIndex = m_nIndex; + } + + void CModelReaderNode_BeamLattice1702_Ball::retrieveRadius(_Out_ nfBool & bHasRadius, _Out_ nfDouble & dRadius) + { + bHasRadius = m_bHasRadius; + if (bHasRadius) + dRadius = m_dRadius; + } + + void CModelReaderNode_BeamLattice1702_Ball::retrieveTag(_Out_ nfBool & bHasTag, _Out_ nfInt32 & nTag) + { + bHasTag = m_bHasTag; + if (bHasTag) + nTag = m_nTag; + } + + void CModelReaderNode_BeamLattice1702_Ball::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_BEAMLATTICE_BALL_VINDEX) == 0) { + nfInt32 nValue = fnStringToInt32(pAttributeValue); + if ((nValue >= 0) && (nValue < XML_3MF_MAXRESOURCEINDEX)) + m_nIndex = nValue; + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_BEAMLATTICE_BALL_R) == 0) { + nfFloat fValue = fnStringToFloat(pAttributeValue); + if ((fValue >= 0) && (fValue < XML_3MF_MAXIMUMBALLRADIUSVALUE)) { + m_dRadius = fValue; + m_bHasRadius = true; + } + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_BEAMLATTICEINVALIDATTRIBUTE), mrwInvalidOptionalValue); + } + + void CModelReaderNode_BeamLattice1702_Ball::OnNSAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue, _In_z_ const nfChar * pNameSpace) + { + + } +} \ No newline at end of file diff --git a/Source/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BallRef.cpp b/Source/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BallRef.cpp new file mode 100644 index 0000000..88d8318 --- /dev/null +++ b/Source/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BallRef.cpp @@ -0,0 +1,82 @@ +/*++ + +Copyright (C) 2020 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_BeamLattice1702_BallRef.cpp covers the official 3MF beamlattice extension. + +--*/ + +#include "Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BallRef.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_ModelMeshObject.h" + +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CModelReaderNode_BeamLattice1702_BallRef::CModelReaderNode_BeamLattice1702_BallRef(_In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings), m_nIndex(0) + { + } + + void CModelReaderNode_BeamLattice1702_BallRef::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + + } + + void CModelReaderNode_BeamLattice1702_BallRef::retrieveIndex(_Out_ nfInt32 & nIndex) + { + nIndex = m_nIndex; + } + + void CModelReaderNode_BeamLattice1702_BallRef::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_BEAMLATTICE_INDEX) == 0) { + nfInt32 nValue = fnStringToInt32(pAttributeValue); + if ((nValue >= 0) && (nValue < XML_3MF_MAXBALLCOUNT)) + m_nIndex = nValue; + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_BEAMLATTICEINVALIDATTRIBUTE), mrwInvalidOptionalValue); + + } + +} diff --git a/Source/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Balls.cpp b/Source/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Balls.cpp new file mode 100644 index 0000000..9aeb5b4 --- /dev/null +++ b/Source/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Balls.cpp @@ -0,0 +1,108 @@ +/*++ + +Copyright (C) 2020 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_BeamLattice1702_Balls.cpp covers the official 3MF beamlattice extension. + +--*/ + +#include "Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Balls.h" +#include "Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Ball.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_StringUtils.h" + +namespace NMR { + + CModelReaderNode_BeamLattice1702_Balls::CModelReaderNode_BeamLattice1702_Balls(_In_ CModel * pModel, _In_ CMesh * pMesh, + _In_ nfDouble defaultBallRadius, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + __NMRASSERT(pMesh); + __NMRASSERT(pModel); + + m_pModel = pModel; + m_pMesh = pMesh; + m_dDefaultBallRadius = defaultBallRadius; + } + + void CModelReaderNode_BeamLattice1702_Balls::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse Name + parseName(pXMLReader); + + // Parse Attributes + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + } + + void CModelReaderNode_BeamLattice1702_Balls::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + } + + void CModelReaderNode_BeamLattice1702_Balls::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pChildName); + __NMRASSERT(pXMLReader); + __NMRASSERT(pNameSpace); + + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_BEAMLATTICESPEC) == 0) { + if (strcmp(pChildName, XML_3MF_ELEMENT_BALL) == 0) { + // Parse XML + PModelReaderNode_BeamLattice1702_Ball pXMLNode = std::make_shared(m_pModel, m_pWarnings); + pXMLNode->parseXML(pXMLReader); + + // Retrieve node index + nfInt32 nIndex; + pXMLNode->retrieveIndex(nIndex, m_pMesh->getNodeCount()); + + nfInt32 nTag; + nfBool bHasTag, bHasRadius; + nfDouble dRadius; + pXMLNode->retrieveTag(bHasTag, nTag); + pXMLNode->retrieveRadius(bHasRadius, dRadius); + + if (!bHasRadius) { + dRadius = m_dDefaultBallRadius; + } + + // Create ball + MESHNODE * pNode = m_pMesh->getNode(nIndex); + m_pMesh->addBall(pNode, dRadius); + } + else { + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT), mrwInvalidOptionalValue); + } + } + } +} \ No newline at end of file diff --git a/Source/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Beam.cpp b/Source/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Beam.cpp new file mode 100644 index 0000000..d449d7f --- /dev/null +++ b/Source/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Beam.cpp @@ -0,0 +1,174 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_BeamLattice1702_Beam.cpp covers the official 3MF beamlattice extension. +(Initial version based on private beam extension) + + +--*/ + +#include "Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Beam.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_ModelMeshObject.h" + +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + eModelBeamLatticeCapMode stringToCapMode(const nfChar * capModeStr) { + if (strcmp(capModeStr, XML_3MF_BEAMLATTICE_CAPMODE_BUTT) == 0) + return eModelBeamLatticeCapMode::MODELBEAMLATTICECAPMODE_BUTT; + if ((strcmp(capModeStr, XML_3MF_BEAMLATTICE_CAPMODE_HEMISPHERE) == 0) || (strcmp(capModeStr, XML_3MF_BEAMLATTICE_CAPMODE_ROUND) == 0)) + return eModelBeamLatticeCapMode::MODELBEAMLATTICECAPMODE_HEMISPHERE; + // if (strcmp(capModeStr, XML_3MF_BEAMLATTICE_CAPMODE_SPHERE) == 0) + // return eModelBeamLatticeCapMode::MODELBEAMLATTICECAPMODE_SPHERE; + return eModelBeamLatticeCapMode::MODELBEAMLATTICECAPMODE_SPHERE; + } + + CModelReaderNode_BeamLattice1702_Beam::CModelReaderNode_BeamLattice1702_Beam(_In_ CModel * pModel, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + m_nIndex1 = -1; + m_nIndex2 = -1; + + m_bHasRadius1 = false; + m_bHasRadius2 = false; + m_dRadius1 = 0; + m_dRadius2 = 0; + + m_bHasCap1 = false; + m_bHasCap2 = false; + + m_bHasTag = false; + m_nTag = -1; + } + + void CModelReaderNode_BeamLattice1702_Beam::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + + } + + void CModelReaderNode_BeamLattice1702_Beam::retrieveIndices(_Out_ nfInt32 & nIndex1, _Out_ nfInt32 & nIndex2, nfInt32 nNodeCount) + { + if ((m_nIndex1 < 0) || (m_nIndex2 < 0)) + throw CNMRException(NMR_ERROR_INVALIDMODELNODEINDEX); + + if ((m_nIndex1 >= nNodeCount) || (m_nIndex2 >= nNodeCount)) + throw CNMRException(NMR_ERROR_INVALIDMODELNODEINDEX); + + if ( m_nIndex1 == m_nIndex2 ) + throw CNMRException(NMR_ERROR_INVALIDMODELNODEINDEX); + + nIndex1 = m_nIndex1; + nIndex2 = m_nIndex2; + } + + void CModelReaderNode_BeamLattice1702_Beam::retrieveRadii(_Out_ nfBool & bHasRadius1, _Out_ nfDouble & dRadius1, _Out_ nfBool & bHasRadius2, _Out_ nfDouble & dRadius2) { + bHasRadius1 = m_bHasRadius1; + if (bHasRadius1) + dRadius1 = m_dRadius1; + bHasRadius2 = m_bHasRadius2; + if (bHasRadius2) + dRadius2 = m_dRadius2; + } + + void CModelReaderNode_BeamLattice1702_Beam::retrieveCapModes(_Out_ nfBool & bHasCapMode1, _Out_ eModelBeamLatticeCapMode & eCapMode1, _Out_ nfBool & bHasCapMode2, _Out_ eModelBeamLatticeCapMode & eCapMode2) + { + bHasCapMode1 = m_bHasCap1; + if (bHasCapMode1) + eCapMode1 = m_eCapMode1; + bHasCapMode2 = m_bHasCap2; + if (bHasCapMode2) + eCapMode2 = m_eCapMode2; + } + + + void CModelReaderNode_BeamLattice1702_Beam::retrieveTag(_Out_ nfBool & bHasTag, _Out_ nfInt32 & nTag) { + bHasTag = m_bHasTag; + if (bHasTag) + nTag = m_nTag; + } + + void CModelReaderNode_BeamLattice1702_Beam::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_BEAMLATTICE_V1) == 0) { + nfInt32 nValue = fnStringToInt32(pAttributeValue); + if ((nValue >= 0) && (nValue < XML_3MF_MAXRESOURCEINDEX)) + m_nIndex1 = nValue; + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_BEAMLATTICE_V2) == 0) { + nfInt32 nValue = fnStringToInt32(pAttributeValue); + if ((nValue >= 0) && (nValue < XML_3MF_MAXRESOURCEINDEX)) + m_nIndex2 = nValue; + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_BEAMLATTICE_R1) == 0) { + nfFloat fValue = fnStringToFloat(pAttributeValue); + if ((fValue >= 0) && (fValue < XML_3MF_MAXIMUMBEAMRADIUSVALUE)) { + m_dRadius1 = fValue; + m_bHasRadius1 = true; + } + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_BEAMLATTICE_R2) == 0) { + nfFloat fValue = fnStringToFloat(pAttributeValue); + if ((fValue >= 0) && (fValue < XML_3MF_MAXIMUMBEAMRADIUSVALUE)) { + m_dRadius2 = fValue; + m_bHasRadius2 = true; + } + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_BEAMLATTICE_CAP1) == 0) { + m_bHasCap1 = true; + m_eCapMode1 = stringToCapMode(pAttributeValue); + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_BEAMLATTICE_CAP2) == 0) { + m_bHasCap2 = true; + m_eCapMode2 = stringToCapMode(pAttributeValue); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_BEAMLATTICEINVALIDATTRIBUTE), mrwInvalidOptionalValue); + } + + void CModelReaderNode_BeamLattice1702_Beam::OnNSAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue, _In_z_ const nfChar * pNameSpace) + { + + } + +} diff --git a/Source/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BeamLattice.cpp b/Source/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BeamLattice.cpp new file mode 100644 index 0000000..37c2ce3 --- /dev/null +++ b/Source/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BeamLattice.cpp @@ -0,0 +1,194 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_BeamLattice1702_BeamLattice.cpp covers the official 3MF beamlattice extension. +(Initial version based on private beam extension) + +--*/ + +#include "Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BeamLattice.h" +#include "Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Beams.h" +#include "Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Beam.h" +#include "Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BeamSets.h" +#include "Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Balls.h" +#include "Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Ball.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_ModelMeshObject.h" + +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include + +namespace NMR { + + CModelReaderNode_BeamLattice1702_BeamLattice::CModelReaderNode_BeamLattice1702_BeamLattice(_In_ CModel * pModel, _In_ CMesh * pMesh, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + m_pModel = pModel; + m_pMesh = pMesh; + m_pWarnings = pWarnings; + m_bHasClippingMeshID = false; + m_nClippingMeshID = 0; + m_bHasRepresentationMeshID = false; + m_nRepresentationMeshID = 0; + m_eClipMode = eModelBeamLatticeClipMode::MODELBEAMLATTICECLIPMODE_NONE; + m_dDefaultRadius = 0.0001; + m_eDefaultCapMode = eModelBeamLatticeCapMode::MODELBEAMLATTICECAPMODE_SPHERE; + m_dDefaultBallRadius = 0.0; + } + + void CModelReaderNode_BeamLattice1702_BeamLattice::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + + } + + void CModelReaderNode_BeamLattice1702_BeamLattice::retrieveClippingInfo(_Out_ eModelBeamLatticeClipMode &eClipMode, _Out_ nfBool & bHasClippingMode, _Out_ ModelResourceID & nClippingMeshID) + { + bHasClippingMode = m_bHasClippingMeshID; + nClippingMeshID = m_nClippingMeshID; + eClipMode = m_eClipMode; + } + + void CModelReaderNode_BeamLattice1702_BeamLattice::retrieveRepresentationInfo(_Out_ nfBool & bHasRepresentation, _Out_ ModelResourceID & nRepresentationMeshID) + { + bHasRepresentation = m_bHasRepresentationMeshID; + nRepresentationMeshID = m_nRepresentationMeshID; + } + + void CModelReaderNode_BeamLattice1702_BeamLattice::validateBallOptions(_In_ PModelWarnings pWarnings) + { + if (m_pMesh->getBeamLatticeBallMode() != eModelBeamLatticeBallMode::MODELBEAMLATTICEBALLMODE_NONE) { + if (m_pMesh->getDefaultBallRadius() <= 0 && m_pMesh->getDefaultBallRadius() >= XML_3MF_MAXIMUMCOORDINATEVALUE) { + pWarnings->addException(CNMRException(NMR_ERROR_BEAMLATTICEINVALIDATTRIBUTE), mrwInvalidOptionalValue); + } + } + } + + void CModelReaderNode_BeamLattice1702_BeamLattice::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_BEAMLATTICE_RADIUS) == 0) { + nfDouble dValue = fnStringToDouble(pAttributeValue); + if ( std::isnan(dValue) || (dValue <= 0) || (dValue > XML_3MF_MAXIMUMCOORDINATEVALUE) ) + throw CNMRException(NMR_ERROR_BEAMLATTICEINVALIDATTRIBUTE); + m_dDefaultRadius = dValue; + } + else if ( (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_BEAMLATTICE_MINLENGTH) == 0) || + (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_BEAMLATTICE_PRECISION) == 0) ) // legacy + { + nfDouble dValue = fnStringToDouble(pAttributeValue); + if (std::isnan(dValue) || (dValue <= 0) || (dValue > XML_3MF_MAXIMUMCOORDINATEVALUE)) + throw CNMRException(NMR_ERROR_BEAMLATTICEINVALIDATTRIBUTE); + m_pMesh->setBeamLatticeMinLength(dValue); + } + else if ((strcmp(pAttributeName, XML_3MF_ATTRIBUTE_BEAMLATTICE_CLIPPINGMODE) == 0) || + (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_BEAMLATTICE_CLIPPING) == 0)) // legacy + { + if (strcmp(pAttributeValue, XML_3MF_BEAMLATTICE_CLIPMODE_INSIDE) == 0) { + m_eClipMode = MODELBEAMLATTICECLIPMODE_INSIDE; + } + else if (strcmp(pAttributeValue, XML_3MF_BEAMLATTICE_CLIPMODE_OUTSIDE) == 0) { + m_eClipMode = MODELBEAMLATTICECLIPMODE_OUTSIDE; + } + else { + m_eClipMode = MODELBEAMLATTICECLIPMODE_NONE; + } + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_BEAMLATTICE_CLIPPINGMESH) == 0) { + m_nClippingMeshID = fnStringToUint32(pAttributeValue); + m_bHasClippingMeshID = true; + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_BEAMLATTICE_REPRESENTATIONMESH) == 0) { + m_nRepresentationMeshID = fnStringToUint32(pAttributeValue); + m_bHasRepresentationMeshID = true; + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_BEAMLATTICE_ACCURACY) == 0) { + // legacy, ignore it + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_BEAMLATTICE_CAPMODE) == 0) { + m_eDefaultCapMode = stringToCapMode(pAttributeValue); + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_BEAMLATTICE_BALLMODE) == 0) { + m_pMesh->setBeamLatticeBallMode(stringToBallMode(pAttributeValue)); + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_BEAMLATTICE_BALLRADIUS) == 0) { + nfDouble dValue = fnStringToDouble(pAttributeValue); + if (std::isnan(dValue) || (dValue <= 0) || (dValue > XML_3MF_MAXIMUMCOORDINATEVALUE)) + throw CNMRException(NMR_ERROR_BEAMLATTICEINVALIDATTRIBUTE); + m_dDefaultBallRadius = dValue; + m_pMesh->setDefaultBallRadius(dValue); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_BEAMLATTICEINVALIDATTRIBUTE), mrwInvalidOptionalValue); + } + + void CModelReaderNode_BeamLattice1702_BeamLattice::OnNSAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue, _In_z_ const nfChar * pNameSpace) + { + + + } + + void CModelReaderNode_BeamLattice1702_BeamLattice::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pChildName); + __NMRASSERT(pXMLReader); + __NMRASSERT(pNameSpace); + + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_BEAMLATTICESPEC) == 0) { + if (strcmp(pChildName, XML_3MF_ELEMENT_BEAMS) == 0) + { + PModelReaderNode pXMLNode = std::make_shared(m_pModel, m_pMesh, m_dDefaultRadius, m_eDefaultCapMode, m_pWarnings); + pXMLNode->parseXML(pXMLReader); + } + else if (strcmp(pChildName, XML_3MF_ELEMENT_BEAMSETS) == 0) + { + PModelReaderNode pXMLNode = std::make_shared(m_pMesh, m_pWarnings); + pXMLNode->parseXML(pXMLReader); + } + else if (strcmp(pChildName, XML_3MF_ELEMENT_BALLS) == 0) + { + PModelReaderNode pXMLNode = std::make_shared(m_pModel, m_pMesh, m_dDefaultBallRadius, m_pWarnings); + pXMLNode->parseXML(pXMLReader); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT), mrwInvalidOptionalValue); + } + } +} diff --git a/Source/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BeamSet.cpp b/Source/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BeamSet.cpp new file mode 100644 index 0000000..7b018a7 --- /dev/null +++ b/Source/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BeamSet.cpp @@ -0,0 +1,124 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_BeamLattice1702_BeamSet.cpp covers the official 3MF beamlattice extension. + + +--*/ + +#include "Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BeamSet.h" +#include "Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Ref.h" +#include "Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BallRef.h" + + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_ModelMeshObject.h" + +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CModelReaderNode_BeamLattice1702_BeamSet::CModelReaderNode_BeamLattice1702_BeamSet(_In_ BEAMSET * pBeamSet, _In_ std::unordered_set * pUniqueIdentifiers, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + m_pBeamSet = pBeamSet; + m_pUniqueIdentifiers = pUniqueIdentifiers; + } + + void CModelReaderNode_BeamLattice1702_BeamSet::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + + } + + void CModelReaderNode_BeamLattice1702_BeamSet::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_BEAMLATTICE_NAME) == 0) { + m_pBeamSet->m_sName = pAttributeValue; + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_BEAMLATTICE_IDENTIFIER) == 0) { + std::string attributeString(pAttributeValue); + if (m_pUniqueIdentifiers->find(attributeString) == m_pUniqueIdentifiers->end()) { + m_pUniqueIdentifiers->insert(attributeString); + m_pBeamSet->m_sIdentifier = pAttributeValue; + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_BEAMSET_IDENTIFIER_NOT_UNIQUE), mrwInvalidOptionalValue); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_BEAMLATTICEINVALIDATTRIBUTE), mrwInvalidOptionalValue); + } + + void CModelReaderNode_BeamLattice1702_BeamSet::OnNSAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue, _In_z_ const nfChar * pNameSpace) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + __NMRASSERT(pNameSpace); + + } + + void CModelReaderNode_BeamLattice1702_BeamSet::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pChildName); + __NMRASSERT(pXMLReader); + __NMRASSERT(pNameSpace); + + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_BEAMLATTICESPEC) == 0) { + if (strcmp(pChildName, XML_3MF_ELEMENT_REF) == 0) { + PModelReaderNode_BeamLattice1702_Ref pXMLNode = std::make_shared(m_pWarnings); + pXMLNode->parseXML(pXMLReader); + nfInt32 nIndex; + pXMLNode->retrieveIndex(nIndex); + m_pBeamSet->m_Refs.push_back(nIndex); + } + else if (strcmp(pChildName, XML_3MF_ELEMENT_BALLREF) == 0) { + PModelReaderNode_BeamLattice1702_BallRef pXMLNode = std::make_shared(m_pWarnings); + pXMLNode->parseXML(pXMLReader); + nfInt32 nIndex; + pXMLNode->retrieveIndex(nIndex); + m_pBeamSet->m_BallRefs.push_back(nIndex); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT), mrwInvalidOptionalValue); + + } + } + +} diff --git a/Source/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BeamSets.cpp b/Source/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BeamSets.cpp new file mode 100644 index 0000000..97a691c --- /dev/null +++ b/Source/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BeamSets.cpp @@ -0,0 +1,89 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_BeamLattice1702_BeamSets.cpp covers the official 3MF beamlattice extension. + + +--*/ + +#include "Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BeamSets.h" +#include "Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BeamSet.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_ModelMeshObject.h" + +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CModelReaderNode_BeamLattice1702_BeamSets::CModelReaderNode_BeamLattice1702_BeamSets(_In_ CMesh * pMesh, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + m_pMesh = pMesh; + } + + void CModelReaderNode_BeamLattice1702_BeamSets::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + + } + + void CModelReaderNode_BeamLattice1702_BeamSets::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + } + + void CModelReaderNode_BeamLattice1702_BeamSets::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pChildName); + __NMRASSERT(pXMLReader); + __NMRASSERT(pNameSpace); + + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_BEAMLATTICESPEC) == 0) { + if (strcmp(pChildName, XML_3MF_ELEMENT_BEAMSET) == 0) + { + PBEAMSET pBeamSet = m_pMesh->addBeamSet(); + PModelReaderNode pXMLNode = std::make_shared(pBeamSet.get(), &m_uniqueIdentifiers, m_pWarnings); + pXMLNode->parseXML(pXMLReader); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT), mrwInvalidOptionalValue); + } + } + +} diff --git a/Source/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Beams.cpp b/Source/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Beams.cpp new file mode 100644 index 0000000..6dcef04 --- /dev/null +++ b/Source/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Beams.cpp @@ -0,0 +1,134 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_BeamLattice1702_Beams.cpp covers the official 3MF beamlattice extension. +(Initial version based on private beam extension) + + +--*/ + +#include "Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Beams.h" +#include "Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Beam.h" +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_StringUtils.h" + +namespace NMR { + + CModelReaderNode_BeamLattice1702_Beams::CModelReaderNode_BeamLattice1702_Beams(_In_ CModel * pModel, _In_ CMesh * pMesh, + _In_ nfDouble defaultRadius, _In_ eModelBeamLatticeCapMode defaultCapMode, + _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + __NMRASSERT(pMesh); + __NMRASSERT(pModel); + + m_pModel = pModel; + m_pMesh = pMesh; + m_dDefaultRadius = defaultRadius; + m_eDefaultCapMode = defaultCapMode; + } + + void CModelReaderNode_BeamLattice1702_Beams::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse Name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + } + + void CModelReaderNode_BeamLattice1702_Beams::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + } + + void CModelReaderNode_BeamLattice1702_Beams::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pChildName); + __NMRASSERT(pXMLReader); + __NMRASSERT(pNameSpace); + + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_BEAMLATTICESPEC) == 0) { + if (strcmp(pChildName, XML_3MF_ELEMENT_BEAM) == 0) { + // Parse XML + PModelReaderNode_BeamLattice1702_Beam pXMLNode = std::make_shared(m_pModel, m_pWarnings); + pXMLNode->parseXML(pXMLReader); + + // Retrieve node indices + nfInt32 nIndex1, nIndex2; + pXMLNode->retrieveIndices(nIndex1, nIndex2, m_pMesh->getNodeCount()); + + MESHNODE* pNode1 = m_pMesh->getNode(nIndex1); + MESHNODE* pNode2 = m_pMesh->getNode(nIndex2); + + if (fnVEC3_length(fnVEC3_sub(pNode1->m_position, pNode2->m_position)) < m_pMesh->getBeamLatticeMinLength()) + m_pWarnings->addException(CNMRException(NMR_ERROR_BEAMLATTICENODESTOOCLOSE), mrwInvalidMandatoryValue); + + nfInt32 nTag; + nfBool bHasTag, bHasRadius1, bHasRadius2; + nfDouble dRadius1, dRadius2; + pXMLNode->retrieveTag(bHasTag, nTag); + pXMLNode->retrieveRadii(bHasRadius1, dRadius1, bHasRadius2, dRadius2); + nfDouble dDefaultValueForR2 = m_dDefaultRadius; + if (bHasRadius1) { + dDefaultValueForR2 = dRadius1; + } + else { + dRadius1 = m_dDefaultRadius; + } + + if (!bHasRadius2) { + dRadius2 = dDefaultValueForR2; + } + + nfBool bHasCapMode1, bHasCapMode2; + eModelBeamLatticeCapMode eCap1, eCap2; + nfInt32 nCap1, nCap2; + pXMLNode->retrieveCapModes(bHasCapMode1, eCap1, bHasCapMode2, eCap2); + nCap1 = bHasCapMode1 ? eCap1 : m_eDefaultCapMode; + nCap2 = bHasCapMode2 ? eCap2 : m_eDefaultCapMode; + + // Create beam if valid + if (nIndex1 != nIndex2) { + MESHNODE * pNode1 = m_pMesh->getNode(nIndex1); + MESHNODE * pNode2 = m_pMesh->getNode(nIndex2); + m_pMesh->addBeam(pNode1, pNode2, dRadius1, dRadius2, nCap1, nCap2); + } + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT), mrwInvalidOptionalValue); + } + } + +} diff --git a/Source/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Ref.cpp b/Source/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Ref.cpp new file mode 100644 index 0000000..d5255cc --- /dev/null +++ b/Source/Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Ref.cpp @@ -0,0 +1,82 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_BeamLattice1702_Ref.cpp covers the official 3MF beamlattice extension. + +--*/ + +#include "Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_Ref.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_ModelMeshObject.h" + +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CModelReaderNode_BeamLattice1702_Ref::CModelReaderNode_BeamLattice1702_Ref(_In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings), m_nIndex(0) + { + } + + void CModelReaderNode_BeamLattice1702_Ref::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + + } + + void CModelReaderNode_BeamLattice1702_Ref::retrieveIndex(_Out_ nfInt32 & nIndex) + { + nIndex = m_nIndex; + } + + void CModelReaderNode_BeamLattice1702_Ref::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_BEAMLATTICE_INDEX) == 0) { + nfInt32 nValue = fnStringToInt32(pAttributeValue); + if ((nValue >= 0) && (nValue < XML_3MF_MAXBEAMCOUNT)) + m_nIndex = nValue; + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_BEAMLATTICEINVALIDATTRIBUTE), mrwInvalidOptionalValue); + + } + +} diff --git a/Source/Model/Reader/NMR_KeyStoreOpcPackageReader.cpp b/Source/Model/Reader/NMR_KeyStoreOpcPackageReader.cpp new file mode 100644 index 0000000..50a3296 --- /dev/null +++ b/Source/Model/Reader/NMR_KeyStoreOpcPackageReader.cpp @@ -0,0 +1,203 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_KeyStoreOpcPackageReader.cpp defines an OPC Package reader in a portable way. + +--*/ + +#include "Model/Reader/NMR_KeyStoreOpcPackageReader.h" + +#include "Common/NMR_Types.h" +#include "Common/NMR_Local.h" +#include "Common/NMR_SecureContentTypes.h" +#include "Common/NMR_SecureContext.h" +#include "Common/Platform/NMR_Platform.h" +#include "Common/Platform/NMR_ImportStream.h" +#include "Common/Platform/NMR_ImportStream_Compressed.h" +#include "Common/Platform/NMR_ImportStream_Encrypted.h" +#include "Common/OPC/NMR_OpcPackageReader.h" +#include "Common/OPC/NMR_OpcPackagePart.h" +#include "Model/Classes/NMR_ModelContext.h" +#include "Model/Classes/NMR_KeyStoreFactory.h" +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_KeyStore.h" +#include "Model/Classes/NMR_KeyStoreResourceData.h" +#include "Model/Classes/NMR_KeyStoreResourceDataGroup.h" +#include "Model/Reader/NMR_ModelReader_InstructionElement.h" +#include "Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStore.h" +#include + +namespace NMR { + CKeyStoreOpcPackageReader::CKeyStoreOpcPackageReader(PImportStream pImportStream, CModelContext const & context) + :m_pContext(context) + { + if (!context.isComplete()) + throw CNMRException(NMR_ERROR_INVALIDPOINTER); + m_pPackageReader = std::make_shared(pImportStream, context.warnings(), context.monitor()); + + PImportStream keyStoreStream = findKeyStoreStream(); + if (nullptr != keyStoreStream) { + parseKeyStore(keyStoreStream); + + if (!context.keyStore()->empty()) { + openAllResourceDataGroups(); + } + } + } + + COpcPackageRelationship * CKeyStoreOpcPackageReader::findRootRelation(std::string sRelationType, nfBool bMustBeUnique) { + return m_pPackageReader->findRootRelation(sRelationType, bMustBeUnique); + } + + POpcPackagePart CKeyStoreOpcPackageReader::createPart(std::string sPath) { + auto pPart = m_pPackageReader->createPart(sPath); + auto keyStore = m_pContext.keyStore(); + auto secureContext = m_pContext.secureContext(); + if (secureContext->hasDekCtx()) { + NMR::PKeyStoreResourceDataGroup rdg = keyStore->findResourceDataGroupByResourceDataPath(sPath); + if (nullptr != rdg) { + auto pIt = m_encryptedParts.find(pPart->getURI()); + if (pIt != m_encryptedParts.end()) { + return pIt->second; + } + NMR::PKeyStoreResourceData rd = keyStore->findResourceData(sPath); + PKeyStoreContentEncryptionParams params = CKeyStoreFactory::makeContentEncryptionParams(rd, rdg); + + ContentEncryptionDescriptor p = secureContext->getDekCtx(); + p.m_sDekDecryptData.m_sParams = params; + + PImportStream stream; + PImportStream decryptStream = std::make_shared(pPart->getImportStream(), p); + if (params->isCompressed()) { + PImportStream decompressStream = std::make_shared(decryptStream); + stream = decompressStream; + } + else { + stream = decryptStream; + } + auto encryptedPart = std::make_shared(*pPart, stream); + m_encryptedParts[pPart->getURI()] = encryptedPart; + return encryptedPart; + } + } + return pPart; + } + + nfUint64 CKeyStoreOpcPackageReader::getPartSize(std::string sPath) { + return m_pPackageReader->getPartSize(sPath); + } + + void CKeyStoreOpcPackageReader::close() { + checkAuthenticatedTags(); + } + + NMR::PImportStream CKeyStoreOpcPackageReader::findKeyStoreStream() { + COpcPackageRelationship * pKeyStoreRelation = m_pPackageReader->findRootRelation(PACKAGE_KEYSTORE_RELATIONSHIP_TYPE, true); + if (pKeyStoreRelation != nullptr) { + std::string sTargetPartURI = pKeyStoreRelation->getTargetPartURI(); + POpcPackagePart pKeystorePart = m_pPackageReader->createPart(sTargetPartURI); + if (pKeystorePart == nullptr) + throw CNMRException(NMR_ERROR_KEYSTOREOPCCOULDNOTGETSTREAM); + return pKeystorePart->getImportStream(); + } + return nullptr; + } + + void CKeyStoreOpcPackageReader::parseKeyStore(NMR::PImportStream keyStoreStream) { + + PXmlReader pXMLReader = fnCreateXMLReaderInstance(keyStoreStream, m_pContext.monitor()); + nfBool bHasModel = false; + eXmlReaderNodeType NodeType; + // Read all XML Root Nodes + while (!pXMLReader->IsEOF()) { + if (!pXMLReader->Read(NodeType)) + break; + + // Get Node Name + LPCSTR pszLocalName = nullptr; + pXMLReader->GetLocalName(&pszLocalName, nullptr); + if (!pszLocalName) + throw CNMRException(NMR_ERROR_COULDNOTGETLOCALXMLNAME); + + if (strcmp(pszLocalName, XML_3MF_ATTRIBUTE_PREFIX_XML) == 0) { + PModelReader_InstructionElement pXMLNode = std::make_shared(m_pContext.warnings()); + pXMLNode->parseXML(pXMLReader.get()); + } + + // Compare with Keystore Node Name + if (strcmp(pszLocalName, XML_3MF_ELEMENT_KEYSTORE) == 0) { + if (bHasModel) + throw CNMRException(NMR_ERROR_DUPLICATEMODELNODE); + bHasModel = true; + + PModelReaderNode_KeyStore pXMLNode = std::make_shared(m_pContext.model().get(), m_pContext.keyStore().get(), m_pContext.warnings()); + pXMLNode->parseXML(pXMLReader.get()); + } + } + } + + void CKeyStoreOpcPackageReader::openAllResourceDataGroups() { + auto keyStore = m_pContext.keyStore(); + auto secureContext = m_pContext.secureContext(); + + for (nfUint64 i = 0; i < keyStore->getResourceDataGroupCount() && !secureContext->emptyKekCtx(); ++i) { + PKeyStoreResourceDataGroup rdg = keyStore->getResourceDataGroup(i); + for (auto it = secureContext->kekCtxBegin(); it != secureContext->kekCtxEnd(); ++it) { + PKeyStoreConsumer consumer = keyStore->findConsumerById((*it).first); + if (consumer) { + PKeyStoreAccessRight accessRight = rdg->findAccessRightByConsumerID(consumer->getConsumerID()); + if (accessRight) { + KeyWrappingDescriptor ctx = (*it).second; + ctx.m_sKekDecryptData.m_pAccessRight = accessRight; + std::vector const & closedKey = accessRight->getCipherValue(); + std::vector openedKey; + size_t decrypted = ctx.m_fnWrap(closedKey, openedKey, ctx.m_sKekDecryptData); + if (decrypted) { + rdg->setKey(openedKey); + break; + } + } + } + } + } + } + void CKeyStoreOpcPackageReader::checkAuthenticatedTags() { + auto secureContext = m_pContext.secureContext(); + auto keyStore = m_pContext.keyStore(); + if (secureContext->hasDekCtx()) { + for (nfUint64 i = 0; i < m_pContext.keyStore()->getResourceDataCount(); ++i) { + NMR::PKeyStoreResourceData rd = keyStore->getResourceData(i); + NMR::PKeyStoreResourceDataGroup rdg = keyStore->findResourceDataGroupByResourceDataPath(rd->packagePath()); + PKeyStoreContentEncryptionParams params = CKeyStoreFactory::makeContentEncryptionParams(rd, rdg); + ContentEncryptionDescriptor descriptor = secureContext->getDekCtx(); + descriptor.m_sDekDecryptData.m_sParams= params; + descriptor.m_fnCrypt(0, nullptr, nullptr, descriptor.m_sDekDecryptData); + } + } + } +} diff --git a/Source/Model/Reader/NMR_ModelReader.cpp b/Source/Model/Reader/NMR_ModelReader.cpp new file mode 100644 index 0000000..381d593 --- /dev/null +++ b/Source/Model/Reader/NMR_ModelReader.cpp @@ -0,0 +1,85 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: +NMR_ModelReader.cpp implements the Model Reader Class. +A model reader reads in a model file and generates an in-memory representation of it. + +--*/ + +#include "Model/Reader/NMR_ModelReader.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/Platform/NMR_ImportStream.h" +#include "Common/NMR_SecureContext.h" +#include "Common/3MF_ProgressMonitor.h" +#include "Model/Classes/NMR_ModelObject.h" +#include "Model/Classes/NMR_ModelMeshObject.h" +#include "Model/Classes/NMR_ModelBuildItem.h" + +namespace NMR { + + CModelReader::CModelReader(_In_ PModel pModel) + :CModelContext(pModel) + { + } + + void CModelReader::readFromMeshImporter(_In_ CMeshImporter * pImporter) + { + __NMRASSERT(pImporter); + + // Create Empty Mesh + PMesh pMesh = std::make_shared(); + + // Import Mesh + pImporter->loadMesh(pMesh.get(), nullptr); + + // Add Single Mesh to Model + PModelMeshObject pMeshObject = std::make_shared(model()->generateResourceID(), model().get(), pMesh); + model()->addResource(pMeshObject); + + // Add Build Item to Model + PModelBuildItem pBuildItem = std::make_shared(pMeshObject.get(), model()->createHandle()); + model()->addBuildItem(pBuildItem); + } + + PImportStream CModelReader::retrievePrintTicket(_Out_ std::string & sContentType) + { + sContentType = m_sPrintTicketContentType; + return m_pPrintTicketStream; + } + + void CModelReader::addRelationToRead(_In_ std::string sRelationShipType) + { + m_RelationsToRead.insert(sRelationShipType); + } + + void CModelReader::removeRelationToRead(_In_ std::string sRelationShipType) + { + m_RelationsToRead.erase(sRelationShipType); + } + +} diff --git a/Source/Model/Reader/NMR_ModelReaderNode.cpp b/Source/Model/Reader/NMR_ModelReaderNode.cpp new file mode 100644 index 0000000..ae3afaf --- /dev/null +++ b/Source/Model/Reader/NMR_ModelReaderNode.cpp @@ -0,0 +1,243 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode.cpp implements the Model Reader Node Class. +A model reader node is an abstract base class for all XML nodes of a +3MF Model Stream. + +--*/ + +#include "Model/Reader/NMR_ModelReaderNode.h" +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_StringUtils.h" + +namespace NMR { + + CModelReaderNode::CModelReaderNode(_In_ PModelWarnings pWarnings, _In_ PProgressMonitor pProgressMonitor) + { + m_bParsedAttributes = false; + m_bParsedContent = false; + m_bIsEmptyElement = false; + + if (pProgressMonitor) { + m_pProgressMonitor = pProgressMonitor; + } + else { + m_pProgressMonitor = std::make_shared(); + } + + if (pWarnings) { + m_pWarnings = pWarnings; + } + else { + m_pWarnings = std::make_shared(); + } + } + + void CModelReaderNode::parseName(_In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pXMLReader); + + LPCSTR pszName = nullptr; + pXMLReader->GetLocalName(&pszName, nullptr); + if (!pszName) + throw CNMRException(NMR_ERROR_COULDNOTGETLOCALXMLNAME); + + std::string sName(pszName); + m_sName = sName; + + if (m_sName == "") + throw CNMRException(NMR_ERROR_NODENAMEISEMPTY); + + m_bIsEmptyElement = pXMLReader->IsEmptyElement() != 0; + } + + std::string CModelReaderNode::getName() + { + return m_sName; + } + + PModelWarnings CModelReaderNode::getWarnings() const + { + return m_pWarnings; + } + + void CModelReaderNode::parseAttributes(_In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pXMLReader); + + if (m_bParsedAttributes) + throw CNMRException(NMR_ERROR_ALREADYPARSEDXMLNODE); + m_bParsedAttributes = true; + + if (!pXMLReader->MoveToFirstAttribute()) + return; + + nfBool bContinue = true; + while (bContinue) { + + if (!pXMLReader->IsDefault()) { + LPCSTR pszLocalName = nullptr; + LPCSTR pszNameSpaceURI = nullptr; + LPCSTR pszValue = nullptr; + UINT nNameCount = 0; + UINT nValueCount = 0; + UINT nNameSpaceCount = 0; + + // Get Attribute Name + pXMLReader->GetNamespaceURI(&pszNameSpaceURI, &nNameSpaceCount); + if (!pszNameSpaceURI) + throw CNMRException(NMR_ERROR_COULDNOTGETNAMESPACE); + + pXMLReader->GetLocalName(&pszLocalName, &nNameCount); + if (!pszLocalName) + throw CNMRException(NMR_ERROR_COULDNOTGETLOCALXMLNAME); + + // Get Attribute Value + pXMLReader->GetValue(&pszValue, &nValueCount); + if (!pszValue) + throw CNMRException(NMR_ERROR_COULDNOTGETXMLVALUE); + + if (nNameCount > 0) { + if (nNameSpaceCount == 0) { + OnAttribute(pszLocalName, pszValue); + } + else { + OnNSAttribute(pszLocalName, pszValue, pszNameSpaceURI); + } + } + } + + bContinue = pXMLReader->MoveToNextAttribute(); + } + } + + void CModelReaderNode::parseContent(_In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pXMLReader); + + if (m_sName == "") + throw CNMRException(NMR_ERROR_NODENAMEISEMPTY); + + if (m_bParsedContent) + throw CNMRException(NMR_ERROR_ALREADYPARSEDXMLNODE); + m_bParsedContent = true; + + if (m_bIsEmptyElement) { + pXMLReader->CloseElement(); + return; + } + + while (!pXMLReader->IsEOF()) { + LPCSTR pszLocalName = nullptr; + LPCSTR pszNameSpaceURI = nullptr; + LPCSTR pszText = nullptr; + UINT nCount = 0; + UINT nNameSpaceCount = 0; + + eXmlReaderNodeType NodeType; + pXMLReader->Read(NodeType); + + switch (NodeType) { + case XMLREADERNODETYPE_STARTELEMENT: + pXMLReader->GetLocalName(&pszLocalName, &nCount); + if (!pszLocalName) + throw CNMRException(NMR_ERROR_COULDNOTGETLOCALXMLNAME); + + pXMLReader->GetNamespaceURI(&pszNameSpaceURI, &nNameSpaceCount); + if (!pszNameSpaceURI) + throw CNMRException(NMR_ERROR_COULDNOTGETNAMESPACE); + + if (nCount > 0) { + if (pszNameSpaceURI == nullptr) { + OnNSChildElement(pszLocalName, "", pXMLReader); + } + else { + OnNSChildElement(pszLocalName, pszNameSpaceURI, pXMLReader); + } + } + break; + + case XMLREADERNODETYPE_TEXT: + pXMLReader->GetValue(&pszText, &nCount); + if (!pszText) + throw CNMRException(NMR_ERROR_COULDNOTGETXMLTEXT); + + if (nCount > 0) + OnText(pszText, pXMLReader); + break; + + case XMLREADERNODETYPE_ENDELEMENT: + pXMLReader->GetLocalName(&pszLocalName, &nCount); + if (!pszLocalName) + throw CNMRException(NMR_ERROR_COULDNOTGETLOCALXMLNAME); + + if (strcmp(pszLocalName, m_sName.c_str()) == 0) { + OnEndElement (pXMLReader); + + pXMLReader->CloseElement(); + return; + } + break; + + case XMLREADERNODETYPE_UNKNOWN: + break; + } + } + } + + void CModelReaderNode::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + // empty on purpose, to be implemented by child classes + } + + void CModelReaderNode::OnText(_In_z_ const nfChar * pText, _In_ CXmlReader * pXMLReader) + { + // empty on purpose, to be implemented by child classes + } + + void CModelReaderNode::OnEndElement(_In_ CXmlReader * pXMLReader) + { + // empty on purpose, to be implemented by child classes + } + + void CModelReaderNode::OnNSAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue, _In_z_ const nfChar * pNameSpace) + { + // empty on purpose, to be implemented by child classes + } + + void CModelReaderNode::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + // empty on purpose, to be implemented by child classes + + } + + +} diff --git a/Source/Model/Reader/NMR_ModelReaderNode_KeyStoreBase.cpp b/Source/Model/Reader/NMR_ModelReaderNode_KeyStoreBase.cpp new file mode 100644 index 0000000..d16d2d6 --- /dev/null +++ b/Source/Model/Reader/NMR_ModelReaderNode_KeyStoreBase.cpp @@ -0,0 +1,42 @@ + +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_KeyStoreBase.h defines the base class for all Model Reader Node classes that are related to . + +--*/ + +#include "Model/Reader/NMR_ModelReaderNode_KeyStoreBase.h" + +namespace NMR { + + CModelReaderNode_KeyStoreBase::CModelReaderNode_KeyStoreBase(_In_ CModel * const pModel, _In_ CKeyStore * const pKeyStore, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings), m_pModel(pModel), m_pKeyStore(pKeyStore) + { + } +} diff --git a/Source/Model/Reader/NMR_ModelReaderNode_ModelBase.cpp b/Source/Model/Reader/NMR_ModelReaderNode_ModelBase.cpp new file mode 100644 index 0000000..710ac88 --- /dev/null +++ b/Source/Model/Reader/NMR_ModelReaderNode_ModelBase.cpp @@ -0,0 +1,295 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_ModelBase.cpp implements the Model Reader Node Class. +A model reader node is an abstract base class for all XML nodes of a 3MF Model Stream. + +--*/ + +#include "Model/Reader/NMR_ModelReaderNode_ModelBase.h" +#include "Model/Reader/v100/NMR_ModelReaderNode100_Resources.h" +#include "Model/Reader/v100/NMR_ModelReaderNode100_Build.h" +#include "Model/Reader/v100/NMR_ModelReaderNode100_MetaData.h" + +#include "Model/Reader/v093/NMR_ModelReaderNode093_Resources.h" +#include "Model/Reader/v093/NMR_ModelReaderNode093_Build.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/3MF_ProgressMonitor.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_StringUtils.h" + +#include +#include +#include +#include + +namespace NMR { + + CModelReaderNode_ModelBase::CModelReaderNode_ModelBase(_In_ CModel * pModel, _In_ PModelWarnings pWarnings, const std::string sPath, + _In_ PProgressMonitor pProgressMonitor) + : CModelReaderNode(pWarnings, pProgressMonitor), m_bIgnoreBuild(false), m_bIgnoreMetaData(false), m_bHaveWarnedAboutV093(false) + { + __NMRASSERT(pModel); + m_pModel = pModel; + m_sRequiredExtensions = ""; + + m_pModel->setLanguage("und"); + + m_bHasResources = false; + m_bHasBuild = false; + m_bWithinIgnoredElement = false; + + m_sPath = sPath; + } + + void CModelReaderNode_ModelBase::CheckRequiredExtensions() { + // check, whether all required extensions are available in this implementation before actually parsing the file + std::istringstream iss(m_sRequiredExtensions); + std::vector tokens{ std::istream_iterator{iss}, + std::istream_iterator{} }; + for (auto token : tokens) { + // is the extension listed? + if (m_ListedExtensions.count(token) < 1) { + throw CNMRException(NMR_ERROR_INVALIDREQUIREDEXTENSIONPREFIX); + } + // is the extension supported? + std::string sExtensionURI = m_ListedExtensions[token]; + if (strcmp(sExtensionURI.c_str(), PACKAGE_XMLNS_100) != 0 && + strcmp(sExtensionURI.c_str(), XML_3MF_NAMESPACE_MATERIALSPEC) != 0 && + strcmp(sExtensionURI.c_str(), XML_3MF_NAMESPACE_PRODUCTIONSPEC) != 0 && + strcmp(sExtensionURI.c_str(), XML_3MF_NAMESPACE_SLICESPEC) != 0 && + strcmp(sExtensionURI.c_str(), XML_3MF_NAMESPACE_BEAMLATTICESPEC) != 0 && + strcmp(sExtensionURI.c_str(), XML_3MF_NAMESPACE_SECURECONTENTSPEC) != 0 ) + { + m_pWarnings->addWarning(NMR_ERROR_REQUIREDEXTENSIONNOTSUPPORTED, mrwInvalidMandatoryValue); + } + } + } + + void CModelReaderNode_ModelBase::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Check required extensions + CheckRequiredExtensions(); + + // Parse Content + parseContent(pXMLReader); + + } + + void CModelReaderNode_ModelBase::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_MODEL_UNIT) == 0) { + + // set unit string and set validity + try { + m_pModel->setUnitString(pAttributeValue); + } + catch (CNMRException & e) { + m_pWarnings->addException(e, mrwInvalidMandatoryValue); + } + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_REQUIREDEXTENSIONS) == 0) { + m_sRequiredExtensions = std::string(pAttributeValue); + } + } + + void CModelReaderNode_ModelBase::OnNSAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue, _In_z_ const nfChar * pNameSpace) + { + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_XML) == 0) { + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_MODEL_LANG) == 0) { + m_pModel->setLanguage(std::string(pAttributeValue)); + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_MODEL_SPACE) == 0) + { + throw CNMRException(NMR_ERROR_FORBIDDENXMLATTRITIBUTE); + } + // lax handling here for other XML_3MF_NAMESPACE_XML-attributes + } + else if (strcmp(pNameSpace, XML_3MF_NAMESPACE_XMLNS) == 0) { + m_ListedExtensions.insert(std::pair(std::string(pAttributeName), std::string(pAttributeValue))); + } + } + + void CModelReaderNode_ModelBase::ReadMetaDataNode(_In_ CXmlReader * pXMLReader) + { + PModelReaderNode100_MetaData pXMLNode = std::make_shared(m_pWarnings); + pXMLNode->parseXML(pXMLReader); + + std::string sKey = pXMLNode->getKey(); + std::string sValue = pXMLNode->getValue(); + std::string sType = pXMLNode->getType(); + nfBool bPreserve = pXMLNode->getPreserve(); + + if (!sKey.empty()) { + if (m_pModel->hasMetaData(sKey)) { + m_pWarnings->addWarning(NMR_ERROR_DUPLICATEMETADATA, mrwInvalidOptionalValue); + } + else { + std::string sNameSpace, sName; + decomposeKeyIntoNamespaceAndName(sKey, sNameSpace, sName); + if (!sNameSpace.empty()) { + std::string sNameSpaceURI; + if (!pXMLReader->GetNamespaceURI(sNameSpace, sNameSpaceURI)) { + m_pWarnings->addException(CNMRException(NMR_ERROR_METADATA_COULDNOTGETNAMESPACE), mrwInvalidOptionalValue); + sNameSpaceURI = sNameSpace; + } + m_pModel->addMetaData(sNameSpaceURI, sName, sValue, sType, bPreserve); + } + else { + // default namespace + if (CModelMetaData::isValidNamespaceAndName("", sName)) { + m_pModel->addMetaData("", sName, sValue, sType, bPreserve); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_UNKNOWNMETADATA), mrwInvalidOptionalValue); + } + } + } + else { + m_pWarnings->addWarning(NMR_ERROR_INVALIDMETADATA, mrwInvalidOptionalValue); + } + } + + void CModelReaderNode_ModelBase::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_CORESPEC100) == 0) { + if (strcmp(pChildName, XML_3MF_ELEMENT_RESOURCES) == 0) { + m_bWithinIgnoredElement = false; + + m_pProgressMonitor->SetProgressIdentifier(ProgressIdentifier::PROGRESS_READRESOURCES); + m_pProgressMonitor->ReportProgressAndQueryCancelled(true); + + PModelReaderNode pXMLNode = std::make_shared(m_pModel, m_pWarnings, m_sPath.c_str(), m_pProgressMonitor); + if (m_bHasResources) + throw CNMRException(NMR_ERROR_DUPLICATERESOURCES); + pXMLNode->parseXML(pXMLReader); + m_bHasResources = true; + } + else if (strcmp(pChildName, XML_3MF_ELEMENT_BUILD) == 0) { + if (m_bHasBuild) + throw CNMRException(NMR_ERROR_DUPLICATEBUILDSECTION); + if (m_bIgnoreBuild) { + m_bWithinIgnoredElement = true; + } + else { + m_bWithinIgnoredElement = false; + m_pProgressMonitor->SetProgressIdentifier(ProgressIdentifier::PROGRESS_READBUILD); + m_pProgressMonitor->ReportProgressAndQueryCancelled(true); + + PModelReaderNode pXMLNode = std::make_shared(m_pModel, m_pWarnings); + pXMLNode->parseXML(pXMLReader); + } + m_bHasBuild = true; + } + else if (strcmp(pChildName, XML_3MF_ELEMENT_METADATA) == 0) { + if (m_bIgnoreMetaData) { + m_bWithinIgnoredElement = true; + } else { + m_bWithinIgnoredElement = false; + ReadMetaDataNode(pXMLReader); + } + } + else { + if (!m_bWithinIgnoredElement) + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT), mrwInvalidOptionalValue); + } + } + else if ((strcmp(pNameSpace, XML_3MF_NAMESPACE_CORESPEC093) == 0) || (strcmp(pNameSpace, "") == 0)) { + + if (!m_bHaveWarnedAboutV093) { + m_pWarnings->addException(CNMRException(NMR_ERROR_VERSION093_NOT_SUPPORTED), mrwInvalidOptionalValue); + m_bHaveWarnedAboutV093 = true; + } + + + if (strcmp(pChildName, XML_3MF_ELEMENT_RESOURCES) == 0) { + PModelReaderNode pXMLNode = std::make_shared(m_pModel, m_pWarnings); + if (m_bHasResources) + throw CNMRException(NMR_ERROR_DUPLICATERESOURCES); + + pXMLNode->parseXML(pXMLReader); + m_bHasResources = true; + } + else if (strcmp(pChildName, XML_3MF_ELEMENT_BUILD) == 0) { + PModelReaderNode pXMLNode = std::make_shared(m_pModel, m_pWarnings); + if (m_bHasBuild) + throw CNMRException(NMR_ERROR_DUPLICATEBUILDSECTION); + + pXMLNode->parseXML(pXMLReader); + m_bHasBuild = true; + } + else if ((strcmp(pChildName, XML_3MF_ELEMENT_METADATA) == 0) || (strcmp(pChildName, XML_3MF_ELEMENT_METADATA_ENRTY) == 0)) { + ReadMetaDataNode(pXMLReader); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT), mrwInvalidOptionalValue); + } + else { + // ignore + } + } + + nfBool CModelReaderNode_ModelBase::getHasResources() + { + return m_bHasResources; + } + + nfBool CModelReaderNode_ModelBase::getHasBuild() + { + return m_bHasBuild; + } + + nfBool CModelReaderNode_ModelBase::ignoreBuild() + { + return m_bIgnoreBuild; + } + void CModelReaderNode_ModelBase::setIgnoreBuild(bool bIgnoreBuild) + { + m_bIgnoreBuild = bIgnoreBuild; + } + + nfBool CModelReaderNode_ModelBase::ignoreMetaData() + { + return m_bIgnoreMetaData; + } + void CModelReaderNode_ModelBase::setIgnoreMetaData(bool bIgnoreMetaData) + { + m_bIgnoreMetaData = bIgnoreMetaData; + } + +} diff --git a/Source/Model/Reader/NMR_ModelReaderNode_StringValue.cpp b/Source/Model/Reader/NMR_ModelReaderNode_StringValue.cpp new file mode 100644 index 0000000..df604cd --- /dev/null +++ b/Source/Model/Reader/NMR_ModelReaderNode_StringValue.cpp @@ -0,0 +1,67 @@ + +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_KeyStoreKeyValue.h defines the Model Reader Node class that is related to . + +--*/ + +#include "Model/Reader/NMR_ModelReaderNode_StringValue.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_StringUtils.h" + +namespace NMR { + + std::string const & CModelReaderNode_StringValue::getValue() const + { + return m_sKeyValue; + } + + void CModelReaderNode_StringValue::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + } + + void CModelReaderNode_StringValue::OnText(_In_z_ const nfChar * pText, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pText); + + m_sKeyValue += std::string(pText); + } + +} diff --git a/Source/Model/Reader/NMR_ModelReader_3MF.cpp b/Source/Model/Reader/NMR_ModelReader_3MF.cpp new file mode 100644 index 0000000..c7010ec --- /dev/null +++ b/Source/Model/Reader/NMR_ModelReader_3MF.cpp @@ -0,0 +1,197 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReader_3MF.cpp implements the Model Reader Class for +3MF Files. A 3MF model reader reads in a 3MF file and generates an in-memory representation of it. + +--*/ + +#include "Model/Reader/NMR_ModelReader_3MF.h" +#include "Model/Reader/NMR_ModelReaderNode_ModelBase.h" +#include "Model/Classes/NMR_ModelObject.h" +#include "Model/Classes/NMR_ModelMeshObject.h" +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_ModelBuildItem.h" +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/MeshImport/NMR_MeshImporter_STL.h" +#include "Common/Platform/NMR_Platform.h" +#include "Model/Classes/NMR_ModelAttachment.h" + +#include "Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceRefModel.h" +#include "Model/Reader/NMR_ModelReader_InstructionElement.h" + +#include "Common/3MF_ProgressMonitor.h" + +namespace NMR { + + CModelReader_3MF::CModelReader_3MF(_In_ PModel pModel) + : CModelReader(pModel) + { + // empty on purpose + } + + void readProductionAttachmentModels(_In_ PModel pModel, _In_ PModelWarnings pWarnings, _In_ PProgressMonitor pProgressMonitor) + { + nfUint32 prodAttCount = pModel->getProductionAttachmentCount(); + for (nfInt32 i = prodAttCount-1; i >=0; i--) + { + if (pProgressMonitor) { + pProgressMonitor->SetProgressIdentifier(ProgressIdentifier::PROGRESS_READNONROOTMODELS); + pProgressMonitor->ReportProgressAndQueryCancelled(true); + } + + PModelAttachment pProdAttachment = pModel->getProductionModelAttachment(i); + std::string sPath = pProdAttachment->getPathURI(); + PImportStream pSubModelStream = pProdAttachment->getStream(); + + // Create XML Reader + PXmlReader pXMLReader = fnCreateXMLReaderInstance(pSubModelStream, pProgressMonitor); + + nfBool bHasModel = false; + eXmlReaderNodeType NodeType; + // Read all XML Root Nodes + while (!pXMLReader->IsEOF()) { + if (!pXMLReader->Read(NodeType)) + break; + + // Get Node Name + LPCSTR pszLocalName = nullptr; + pXMLReader->GetLocalName(&pszLocalName, nullptr); + if (!pszLocalName) + throw CNMRException(NMR_ERROR_COULDNOTGETLOCALXMLNAME); + + if (strcmp(pszLocalName, XML_3MF_ATTRIBUTE_PREFIX_XML) == 0) { + PModelReader_InstructionElement pXMLNode = std::make_shared(pWarnings); + pXMLNode->parseXML(pXMLReader.get()); + } + + // Compare with Model Node Name + if (strcmp(pszLocalName, XML_3MF_ELEMENT_MODEL) == 0) { + if (bHasModel) + throw CNMRException(NMR_ERROR_DUPLICATEMODELNODE); + bHasModel = true; + + PModelReaderNode_ModelBase pXMLNode; + pModel->setCurrentPath(sPath); + + pXMLNode = std::make_shared(pModel.get(), pWarnings, sPath, pProgressMonitor); + pXMLNode->setIgnoreBuild(true); + pXMLNode->setIgnoreMetaData(true); + pXMLNode->parseXML(pXMLReader.get()); + + if (!pXMLNode->getHasResources()) + throw CNMRException(NMR_ERROR_NORESOURCES); + if (!pXMLNode->getHasBuild()) + throw CNMRException(NMR_ERROR_BUILDITEMNOTFOUND); + } + } + } + } + + + void CModelReader_3MF::readStream(_In_ PImportStream pStream) + { + __NMRASSERT(pStream != nullptr); + + nfBool bHasModel = false; + + monitor()->SetProgressIdentifier(ProgressIdentifier::PROGRESS_READSTREAM); + + monitor()->SetProgressIdentifier(ProgressIdentifier::PROGRESS_EXTRACTOPCPACKAGE); + + // Extract Stream from Package + PImportStream pModelStream = extract3MFOPCPackage(pStream); + + // before reading the root model, read the other models in the file + readProductionAttachmentModels(model(), warnings(), monitor()); + + monitor()->SetProgressIdentifier(ProgressIdentifier::PROGRESS_READROOTMODEL); + monitor()->ReportProgressAndQueryCancelled(true); + + // Create XML Reader + PXmlReader pXMLReader = fnCreateXMLReaderInstance(pModelStream, monitor()); + + eXmlReaderNodeType NodeType; + // Read all XML Root Nodes + while (!pXMLReader->IsEOF()) { + if (!pXMLReader->Read(NodeType)) + break; + + // Get Node Name + LPCSTR pszLocalName = nullptr; + pXMLReader->GetLocalName(&pszLocalName, nullptr); + if (!pszLocalName) + throw CNMRException(NMR_ERROR_COULDNOTGETLOCALXMLNAME); + + if (strcmp(pszLocalName, XML_3MF_ATTRIBUTE_PREFIX_XML) == 0) { + PModelReader_InstructionElement pXMLNode = std::make_shared(warnings()); + pXMLNode->parseXML(pXMLReader.get()); + } + + // Compare with Model Node Name + if (strcmp(pszLocalName, XML_3MF_ELEMENT_MODEL) == 0) { + if (bHasModel) + throw CNMRException(NMR_ERROR_DUPLICATEMODELNODE); + bHasModel = true; + + model()->setCurrentPath(model()->rootPath()); + PModelReaderNode_ModelBase pXMLNode = std::make_shared(model().get(), warnings(), model()->rootPath(), monitor()); + pXMLNode->parseXML(pXMLReader.get()); + + if (!pXMLNode->getHasResources()) + throw CNMRException(NMR_ERROR_NORESOURCES); + if (!pXMLNode->getHasBuild()) + throw CNMRException(NMR_ERROR_NOBUILD); + } + + } + + monitor()->SetProgressIdentifier(ProgressIdentifier::PROGRESS_CLEANUP); + monitor()->ReportProgressAndQueryCancelled(false); + + // Release Memory of 3MF Package + release3MFOPCPackage(); + + if (!bHasModel) + throw CNMRException(NMR_ERROR_NOMODELNODE); + + monitor()->SetProgressIdentifier(ProgressIdentifier::PROGRESS_DONE); + monitor()->ReportProgressAndQueryCancelled(false); + } + + void CModelReader_3MF::addTextureAttachment(_In_ std::string sPath, _In_ PImportStream pStream) + { + if (pStream.get() == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + model()->addAttachment(sPath, PACKAGE_TEXTURE_RELATIONSHIP_TYPE, pStream); + } + +} diff --git a/Source/Model/Reader/NMR_ModelReader_3MF_Native.cpp b/Source/Model/Reader/NMR_ModelReader_3MF_Native.cpp new file mode 100644 index 0000000..b531a5d --- /dev/null +++ b/Source/Model/Reader/NMR_ModelReader_3MF_Native.cpp @@ -0,0 +1,252 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReader_3MF_Native.cpp implements the Model Reader Class. +A model reader reads in a 3MF file and generates an in-memory representation of it. +It uses libzip and irrxml to parse the OPC package. + +--*/ + +#include "Model/Reader/NMR_ModelReader_3MF_Native.h" +#include "Model/Reader/NMR_ModelReaderNode_ModelBase.h" +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_ModelAttachment.h" +#include "Model/Classes/NMR_KeyStore.h" +#include "Common/NMR_SecureContext.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_StringUtils.h" +#include "Common/Platform/NMR_Platform.h" +#include "Model/Reader/NMR_ModelReader_InstructionElement.h" + +namespace NMR { + + CModelReader_3MF_Native::CModelReader_3MF_Native(_In_ PModel pModel) + : CModelReader_3MF(pModel) + { + // empty on purpose + } + + + + PImportStream CModelReader_3MF_Native::extract3MFOPCPackage(_In_ PImportStream pPackageStream) + { + m_pPackageReader = std::make_shared(pPackageStream, *this); + + COpcPackageRelationship * pModelRelation = m_pPackageReader->findRootRelation(PACKAGE_START_PART_RELATIONSHIP_TYPE, true); + if (pModelRelation == nullptr) + throw CNMRException(NMR_ERROR_OPCRELATIONSHIPSETREADFAILED); + + std::string sTargetPartURI = pModelRelation->getTargetPartURI(); + POpcPackagePart pModelPart = m_pPackageReader->createPart(sTargetPartURI); + if (pModelPart == nullptr) + throw CNMRException(NMR_ERROR_OPCCOULDNOTGETMODELSTREAM); + + model()->setRootPath(sTargetPartURI.c_str()); + + // calculate current level at this stage + std::string sTargetPartURIDir = fnExtractFileDir(sTargetPartURI); + + extractTexturesFromRelationships(sTargetPartURIDir, pModelPart.get()); + extractCustomDataFromRelationships(sTargetPartURIDir, pModelPart.get()); + extractModelDataFromRelationships(sTargetPartURIDir, pModelPart.get()); + + nfUint32 prodAttCount = model()->getProductionAttachmentCount(); + for (nfUint32 i = 0; i < prodAttCount; i++) + { + PModelAttachment pProdAttachment = model()->getProductionModelAttachment(i); + std::string pathURI = pProdAttachment->getPathURI(); + POpcPackagePart pSubModelPart = m_pPackageReader->createPart(pathURI); + extractModelDataFromRelationships(sTargetPartURIDir, pSubModelPart.get()); + extractTexturesFromRelationships(sTargetPartURIDir, pSubModelPart.get()); + } + + COpcPackageRelationship * pThumbnailRelation = m_pPackageReader->findRootRelation(PACKAGE_THUMBNAIL_RELATIONSHIP_TYPE, true); + if (pThumbnailRelation != nullptr) { + std::string sTargetPartURI = pThumbnailRelation->getTargetPartURI(); + POpcPackagePart pThumbnailPart = m_pPackageReader->createPart(sTargetPartURI); + if (pThumbnailPart == nullptr) + throw CNMRException(NMR_ERROR_OPCCOULDNOTGETTHUMBNAILSTREAM); + PImportStream pThumbnailStream = pThumbnailPart->getImportStream()->copyToMemory(); + model()->addPackageThumbnail()->setStream(pThumbnailStream); + monitor()->IncrementProgress((double)pThumbnailStream->retrieveSize()); + monitor()->ReportProgressAndQueryCancelled(true); + } + + return pModelPart->getImportStream(); + } + + void CModelReader_3MF_Native::release3MFOPCPackage() + { + //foreach part, finalize encryption contexts + m_pPackageReader->close(); + m_pPackageReader = nullptr; + } + + void CModelReader_3MF_Native::extractTexturesFromRelationships(_In_ std::string& sTargetPartURIDir, _In_ COpcPackagePart * pModelPart) + { + if (pModelPart == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + monitor()->SetProgressIdentifier(PROGRESS_READTEXTURETACHMENTS); + + std::multimap& RelationShips = pModelPart->getRelationShips(); + + for (auto iIterator = RelationShips.begin(); iIterator != RelationShips.end(); iIterator++) { + auto theRelationShip = iIterator->second; + std::string sType = theRelationShip->getType(); + + if ( (sType == PACKAGE_TEXTURE_RELATIONSHIP_TYPE) || + (sType == PACKAGE_THUMBNAIL_RELATIONSHIP_TYPE) ) + // this is to allow object thumbnails to come from both + // the Texture or the OPC Thumbnail relationship type + // to comply with older versions of the 3mf specification + { + std::string sURI = theRelationShip->getTargetPartURI(); + // TODO: this logic might not be correct yet + if (!fnStartsWithPathDelimiter(sURI)) + sURI = sTargetPartURIDir + sURI; + + PModelAttachment pModelAttachment = model()->findModelAttachment(sURI); + if (!pModelAttachment) { + POpcPackagePart pTexturePart = m_pPackageReader->createPart(sURI); + PImportStream pTextureAttachmentStream = pTexturePart->getImportStream(); + PImportStream pMemoryStream = pTextureAttachmentStream->copyToMemory(); + + if (pMemoryStream->retrieveSize() == 0) + warnings()->addException(CNMRException(NMR_ERROR_IMPORTSTREAMISEMPTY), mrwMissingMandatoryValue); + + // Add Texture Attachment to Model + addTextureAttachment(sURI, pMemoryStream); + + monitor()->IncrementProgress((double)pMemoryStream->retrieveSize()); + monitor()->ReportProgressAndQueryCancelled(true); + } + } + } + } + + + void CModelReader_3MF_Native::extractCustomDataFromRelationships(_In_ std::string& sTargetPartURIDir, _In_ COpcPackagePart * pModelPart) + { + if (pModelPart == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + monitor()->SetProgressIdentifier(PROGRESS_READCUSTOMATTACHMENTS); + + std::multimap& RelationShips = pModelPart->getRelationShips(); + + for (auto iIterator = RelationShips.begin(); iIterator != RelationShips.end(); iIterator++) { + auto theRelationShip = iIterator->second; + + std::string sRelationShipType = theRelationShip->getType(); + std::string sURI = theRelationShip->getTargetPartURI(); + + if (!fnStartsWithPathDelimiter(sURI)) + sURI = sTargetPartURIDir + sURI; + + auto iRelationIterator = m_RelationsToRead.find(sRelationShipType); + if (iRelationIterator != m_RelationsToRead.end()) { + POpcPackagePart pPart = m_pPackageReader->createPart(sURI); + PImportStream pAttachmentStream = pPart->getImportStream(); + try { + PImportStream pMemoryStream = pAttachmentStream->copyToMemory(); + + if (pMemoryStream->retrieveSize() == 0) + warnings()->addException(CNMRException(NMR_ERROR_IMPORTSTREAMISEMPTY), mrwMissingMandatoryValue); + + // Add Attachment Stream to Model + model()->addAttachment(sURI, sRelationShipType, pMemoryStream); + + monitor()->IncrementProgress((double)pMemoryStream->retrieveSize()); + monitor()->ReportProgressAndQueryCancelled(true); + } + catch (CNMRException &e) { + if (e.getErrorCode() == NMR_ERROR_INVALIDBUFFERSIZE) + warnings()->addException(CNMRException(NMR_ERROR_ATTACHMENTTOOLARGE), mrwMissingMandatoryValue); + else + throw; + } + } + else { + if ( (sRelationShipType != PACKAGE_START_PART_RELATIONSHIP_TYPE) + && (sRelationShipType != PACKAGE_TEXTURE_RELATIONSHIP_TYPE) + && (sRelationShipType != PACKAGE_THUMBNAIL_RELATIONSHIP_TYPE) ) + { + monitor()->DecreaseMaxProgress((double)m_pPackageReader->getPartSize(sURI)); + monitor()->ReportProgressAndQueryCancelled(true); + } + } + } + } + + void CModelReader_3MF_Native::extractModelDataFromRelationships(_In_ std::string& sTargetPartURIDir, _In_ COpcPackagePart * pModelPart) + { + if (pModelPart == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + std::multimap& RelationShips = pModelPart->getRelationShips(); + + for (auto iIterator = RelationShips.begin(); iIterator != RelationShips.end(); iIterator++) { + auto theRelationShip = iIterator->second; + + std::string sRelationShipType = theRelationShip->getType(); + + if (sRelationShipType == PACKAGE_START_PART_RELATIONSHIP_TYPE) { + std::string sURI = theRelationShip->getTargetPartURI(); + if (!fnStartsWithPathDelimiter(sURI)) + sURI = sTargetPartURIDir + sURI; + + POpcPackagePart pPart = m_pPackageReader->createPart(sURI); + + // first, check if this attachment already is in model + PModelAttachment pModelAttachment = model()->findProductionModelAttachment(sURI); + if (pModelAttachment) { + // this attachment is already read + model()->addProductionAttachment(sURI, sRelationShipType, pModelAttachment->getStream(), false); + } + else { + // this is the first time this attachment is read + PImportStream pAttachmentStream = pPart->getImportStream(); + PImportStream pMemoryStream = pAttachmentStream->copyToMemory(); + if (pMemoryStream->retrieveSize() == 0) + warnings()->addException(CNMRException(NMR_ERROR_IMPORTSTREAMISEMPTY), mrwMissingMandatoryValue); + model()->addProductionAttachment(sURI, sRelationShipType, pMemoryStream, true); + } + } + } + } + + + void CModelReader_3MF_Native::checkContentTypes() + { + //throw CNMRException(NMR_ERROR_NOTIMPLEMENTED); + } + + +} diff --git a/Source/Model/Reader/NMR_ModelReader_ColorMapping.cpp b/Source/Model/Reader/NMR_ModelReader_ColorMapping.cpp new file mode 100644 index 0000000..a693beb --- /dev/null +++ b/Source/Model/Reader/NMR_ModelReader_ColorMapping.cpp @@ -0,0 +1,139 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: +NMR_ModelReader_ColorMapping.cpp implements the Model Reader Color Mapping Class. + +--*/ + +#include "Model/Reader/NMR_ModelReader_ColorMapping.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + + +namespace NMR { + + bool operator< (_In_ const READERCOLORMAPPINGTREEENTRY & entry1, _In_ const READERCOLORMAPPINGTREEENTRY & entry2) + { + if (entry1.m_nResourceID < entry2.m_nResourceID) + return true; + if (entry1.m_nResourceID > entry2.m_nResourceID) + return false; + if (entry1.m_nResourceIndex < entry2.m_nResourceIndex) + return true; + return false; + } + + CModelReader_ColorMapping::CModelReader_ColorMapping() + { + } + + void CModelReader_ColorMapping::registerColor(_In_ ModelResourceID nResourceID, _In_ ModelResourceIndex nResourceIndex, _In_ nfColor cColor) + { + READERCOLORMAPPINGTREEENTRY MappingEntry; + MappingEntry.m_nResourceID = nResourceID; + MappingEntry.m_nResourceIndex = nResourceIndex; + + m_ColorEntries.insert(std::make_pair(MappingEntry, cColor)); + m_ResourceIDs.insert(std::make_pair(nResourceID, 1)); + } + + nfBool CModelReader_ColorMapping::findColor(_In_ ModelResourceID nResourceID, _In_ ModelResourceIndex nResourceIndex, _Out_ nfColor & cColor) + { + READERCOLORMAPPINGTREEENTRY MappingEntry; + MappingEntry.m_nResourceID = nResourceID; + MappingEntry.m_nResourceIndex = nResourceIndex; + auto iIterator = m_ColorEntries.find(MappingEntry); + + if (iIterator != m_ColorEntries.end()) { + cColor = iIterator->second; + return true; + } + else { + cColor = 0xffffffff; + return false; + } + } + + nfBool CModelReader_ColorMapping::hasResource(_In_ ModelResourceID nResourceID) + { + auto iIterator = m_ResourceIDs.find(nResourceID); + return (iIterator != m_ResourceIDs.end()); + } + + void CModelReader_ColorMapping::registerTextureReference(_In_ ModelResourceID nResourceID, _In_ ModelResourceID nTextureID) + { + m_TextureMappings.insert(std::make_pair(nResourceID, nTextureID)); + } + + nfBool CModelReader_ColorMapping::hasTextureReference(_In_ ModelResourceID nResourceID) + { + auto iIterator = m_TextureMappings.find(nResourceID); + return (iIterator != m_TextureMappings.end()); + } + + ModelResourceID CModelReader_ColorMapping::getTextureReference(_In_ ModelResourceID nResourceID) + { + auto iIterator = m_TextureMappings.find(nResourceID); + if (iIterator != m_TextureMappings.end()) { + return iIterator->second; + } + return 0; + } + + void CModelReader_ColorMapping::registerMaterialReference(_In_ ModelResourceID nResourceID, _In_ ModelResourceIndex nMaterialIndex) + { + m_MaterialMappings.insert(std::make_pair(nResourceID, nMaterialIndex)); + } + + nfBool CModelReader_ColorMapping::hasMaterialReference(_In_ ModelResourceID nResourceID) + { + auto iIterator = m_MaterialMappings.find(nResourceID); + return (iIterator != m_MaterialMappings.end()); + } + + nfBool CModelReader_ColorMapping::getMaterialReference(_In_ ModelResourceID nResourceID, _Out_ ModelResourceIndex & nMaterialIndex) + { + auto iIterator = m_MaterialMappings.find(nResourceID); + if (iIterator != m_MaterialMappings.end()) { + nMaterialIndex = iIterator->second; + return true; + } + nMaterialIndex = 0; + return false; + } + + nfBool CModelReader_ColorMapping::retrieveAResource(_Out_ ModelResourceID& nResourceID) + { + std::map ::iterator it; + for (it = m_ResourceIDs.begin(); it != m_ResourceIDs.end(); it++) + { + nResourceID = it->first; + return true; + } + return false; + } +} diff --git a/Source/Model/Reader/NMR_ModelReader_InstructionElement.cpp b/Source/Model/Reader/NMR_ModelReader_InstructionElement.cpp new file mode 100644 index 0000000..4c3dbb7 --- /dev/null +++ b/Source/Model/Reader/NMR_ModelReader_InstructionElement.cpp @@ -0,0 +1,90 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReader_InstructionElement.cpp implements a reader for an instruction element + +--*/ + +#include "Model/Reader/NMR_ModelReader_InstructionElement.h" +#include "Model/Classes/NMR_ModelConstants.h" + +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" + +#include + +namespace NMR { + + CModelReader_InstructionElement::CModelReader_InstructionElement(_In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings), m_sName("") + { + } + + void CModelReader_InstructionElement::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + //// Parse Content + //parseContent(pXMLReader); + + } + + void CModelReader_InstructionElement::parseName(_In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pXMLReader); + + LPCSTR pszName = nullptr; + pXMLReader->GetLocalName(&pszName, nullptr); + if (!pszName) + throw CNMRException(NMR_ERROR_COULDNOTGETLOCALXMLNAME); + + m_sName = pszName; + } + + void CModelReader_InstructionElement::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (m_sName == XML_3MF_ATTRIBUTE_PREFIX_XML) { + // only do this if this is the xml declaration + if (strcmp(pAttributeName, "encoding") == 0) { + m_sEncoding = pAttributeValue; + std::transform(m_sEncoding.begin(), m_sEncoding.end(), m_sEncoding.begin(), tolower); + if ((m_sEncoding != "utf-8") && (m_sEncoding != "utf8")) { + throw CNMRException(NMR_ERROR_INVALIDXMLENCODING); + } + } + } + } + +} diff --git a/Source/Model/Reader/NMR_ModelReader_STL.cpp b/Source/Model/Reader/NMR_ModelReader_STL.cpp new file mode 100644 index 0000000..31478da --- /dev/null +++ b/Source/Model/Reader/NMR_ModelReader_STL.cpp @@ -0,0 +1,60 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReader_STL.cpp implements the Model Reader Class for +STL Files. A STL model reader reads in a STL file and generates an in-memory +representation of it. + +--*/ + +#include "Model/Reader/NMR_ModelReader_STL.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/MeshImport/NMR_MeshImporter_STL.h" + +namespace NMR { + + CModelReader_STL::CModelReader_STL(_In_ PModel pModel) + :CModelReader(pModel) + { + // empty on purpose + } + + void CModelReader_STL::readStream(_In_ PImportStream pStream) + { + if (pStream.get() == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + // Create STL Importer + PMeshImporter pImporter = std::make_shared(pStream); + + // Read Mesh and create Model Objects + readFromMeshImporter(pImporter.get()); + } + +} diff --git a/Source/Model/Reader/NMR_ModelReader_TexCoordMapping.cpp b/Source/Model/Reader/NMR_ModelReader_TexCoordMapping.cpp new file mode 100644 index 0000000..db0602e --- /dev/null +++ b/Source/Model/Reader/NMR_ModelReader_TexCoordMapping.cpp @@ -0,0 +1,109 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: +NMR_ModelReader_TexCoordMapping.cpp implements the Model Reader TexCoord Mapping Class. + +--*/ + +#include "Model/Reader/NMR_ModelReader_TexCoordMapping.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + + +namespace NMR { + + bool operator< (_In_ const READERTEXCOORDMAPPINGTREEENTRY & entry1, _In_ const READERTEXCOORDMAPPINGTREEENTRY & entry2) + { + if (entry1.m_nResourceID < entry2.m_nResourceID) + return true; + if (entry1.m_nResourceID > entry2.m_nResourceID) + return false; + if (entry1.m_nResourceIndex < entry2.m_nResourceIndex) + return true; + return false; + } + + + CModelReader_TexCoordMapping::CModelReader_TexCoordMapping() + { + } + + void CModelReader_TexCoordMapping::registerTexCoords(_In_ ModelResourceID nResourceID, _In_ ModelResourceIndex nResourceIndex, _In_ ModelResourceID nTextureID, _In_ nfFloat fU, _In_ nfFloat fV) + { + READERTEXCOORDMAPPINGTREEENTRY MappingEntry; + MappingEntry.m_nResourceID = nResourceID; + MappingEntry.m_nResourceIndex = nResourceIndex; + + READERTEXCOORDMAPPINGVALUE ValueEntry; + ValueEntry.m_nTextureID = nTextureID; + ValueEntry.m_fU = fU; + ValueEntry.m_fV = fV; + + m_TexCoordEntries.insert(std::make_pair(MappingEntry, ValueEntry)); + m_ResourceIDs.insert(std::make_pair(nResourceID, 1)); + } + + nfBool CModelReader_TexCoordMapping::findTexCoords(_In_ ModelResourceID nResourceID, _In_ ModelResourceIndex nResourceIndex, _Out_ ModelResourceID & nTextureID, _Out_ nfFloat & fU, _Out_ nfFloat & fV) + { + READERTEXCOORDMAPPINGTREEENTRY MappingEntry; + MappingEntry.m_nResourceID = nResourceID; + MappingEntry.m_nResourceIndex = nResourceIndex; + auto iIterator = m_TexCoordEntries.find(MappingEntry); + + if (iIterator != m_TexCoordEntries.end()) { + nTextureID = iIterator->second.m_nTextureID; + fU = iIterator->second.m_fU; + fV = iIterator->second.m_fV; + return true; + } + else { + nTextureID = 0; + fU = 0.0f; + fV = 0.0f; + return false; + } + } + + nfBool CModelReader_TexCoordMapping::hasResource(_In_ ModelResourceID nResourceID) + { + auto iIterator = m_ResourceIDs.find(nResourceID); + return (iIterator != m_ResourceIDs.end()); + } + + nfBool CModelReader_TexCoordMapping::retrieveAResource(_Out_ ModelResourceID& nResourceID) + { + std::map ::iterator it; + for (it = m_ResourceIDs.begin(); it != m_ResourceIDs.end(); it++) + { + nResourceID = it->first; + return true; + } + return false; + } + +} + diff --git a/Source/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStore.cpp b/Source/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStore.cpp new file mode 100644 index 0000000..fa41c1b --- /dev/null +++ b/Source/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStore.cpp @@ -0,0 +1,107 @@ + +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_KeyStore.h defines the Model Reader Node class that is related to . + +--*/ + +// TODO: check if needs #include +// https://stackoverflow.com/questions/1646031/strtoull-and-long-long-arithmetic + +#include "Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStore.h" +#include "Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreConsumer.h" +#include "Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreResourceDataGroup.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_KeyStoreResourceData.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_StringUtils.h" + +namespace NMR { + + void CModelReaderNode_KeyStore::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + + // Set references + if (!m_UUID.get()) { + // We do not have to check for secure content spec, because it is the base spec of a keystore + m_pWarnings->addWarning(NMR_ERROR_MISSINGUUID, mrwMissingMandatoryValue); + m_UUID = std::make_shared(); + } + keystore()->setUUID(m_UUID); + } + + void CModelReaderNode_KeyStore::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(XML_3MF_SECURE_CONTENT_UUID, pAttributeName) == 0) { + if (m_UUID.get()) + m_pWarnings->addWarning(NMR_ERROR_DUPLICATEUUID, eModelWarningLevel::mrwInvalidMandatoryValue); + // this can throw for invalid UUIDs and it's ok so according to other reader nodes + m_UUID = std::make_shared(pAttributeValue); + } + else if (strcmp(XML_3MF_ATTRIBUTE_XMLNS, pAttributeName) != 0) + m_pWarnings->addWarning(NMR_ERROR_NAMESPACE_INVALID_ATTRIBUTE, mrwInvalidOptionalValue); + } + + void CModelReaderNode_KeyStore::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pChildName); + __NMRASSERT(pXMLReader); + __NMRASSERT(pNameSpace); + + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_SECURECONTENTSPEC) == 0) { + // Read a consumer + if (strcmp(pChildName, XML_3MF_ELEMENT_CONSUMER) == 0) { + PModelReaderNode_KeyStoreConsumer pXMLNode = extractCopy(); + pXMLNode->parseXML(pXMLReader); + // consumer adds itself to m_pKeyStore, nothing else to do here + } + else if (strcmp(pChildName, XML_3MF_ELEMENT_RESOURCEDATAGROUP) == 0) { + PModelReaderNode_KeyStoreResourceDataGroup pXMLNode = extractCopy(); + pXMLNode->parseXML(pXMLReader); + // resource data adds itself to m_pKeyStore, nothing else to do here + } + else + m_pWarnings->addWarning(NMR_ERROR_NAMESPACE_INVALID_ELEMENT, mrwInvalidOptionalValue); + } + } + +} diff --git a/Source/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreAccessRight.cpp b/Source/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreAccessRight.cpp new file mode 100644 index 0000000..40220fd --- /dev/null +++ b/Source/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreAccessRight.cpp @@ -0,0 +1,121 @@ + +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_KeyStoreAccessRight.h defines the Model Reader Node class that is related to . + +--*/ + +#include "Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreAccessRight.h" +#include "Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreCipherValue.h" +#include "Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreKEKParams.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_KeyStoreFactory.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_StringUtils.h" + +namespace NMR { + + PKeyStoreAccessRight CModelReaderNode_KeyStoreAccessRight::getAccessRight() + { + return CKeyStoreFactory::makeAccessRight( + m_pKeyStore->getConsumer(m_nConsumerIndex), + m_sParams.m_eAlgorithm, + m_sParams.m_eMgf, + m_sParams.m_eDigest, + m_rgCipherValue); + } + + void CModelReaderNode_KeyStoreAccessRight::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + + // this can throw for values that are not numbers and it's ok so according to other reader nodes + if (!m_bHasConsumerIndex) { + m_pWarnings->addWarning(NMR_ERROR_KEYSTOREMISSINGCONSUMERINDEX, eModelWarningLevel::mrwMissingMandatoryValue); + m_nConsumerIndex = 0; + } + if (m_nConsumerIndex >= m_pKeyStore->getConsumerCount()) + m_pWarnings->addWarning(NMR_ERROR_KEYSTOREINVALIDCONSUMERINDEX, eModelWarningLevel::mrwFatal); + if (!m_bHasParams) + m_pWarnings->addWarning(NMR_ERROR_KEYSTOREMISSINGKEKPARAMS, eModelWarningLevel::mrwFatal); + if (!m_bHasCipherData) + m_pWarnings->addWarning(NMR_ERROR_KEYSTOREMISSINGCIPHERDATA, eModelWarningLevel::mrwFatal); + } + + void CModelReaderNode_KeyStoreAccessRight::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(XML_3MF_SECURE_CONTENT_CONSUMER_INDEX, pAttributeName) == 0) { + if (m_bHasConsumerIndex) + m_pWarnings->addWarning(NMR_ERROR_KEYSTOREDUPLICATECONSUMERINDEX, eModelWarningLevel::mrwInvalidMandatoryValue); + m_bHasConsumerIndex = true; + m_nConsumerIndex = fnStringToUint32(pAttributeValue); + } + else + m_pWarnings->addWarning(NMR_ERROR_NAMESPACE_INVALID_ATTRIBUTE, mrwInvalidOptionalValue); + } + + void CModelReaderNode_KeyStoreAccessRight::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pChildName); + __NMRASSERT(pXMLReader); + __NMRASSERT(pNameSpace); + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_SECURECONTENTSPEC) == 0) { + if (strcmp(pChildName, XML_3MF_ELEMENT_KEKPARAMS) == 0) { + if (!m_bHasParams) { + m_bHasParams = true; + PModelReaderNode_KeyStoreKEKParams pXMLNode = extractCopy(); + pXMLNode->parseXML(pXMLReader); + m_sParams = pXMLNode->getKekParams(); + } + } else if (strcmp(pChildName, XML_3MF_ELEMENT_CIPHERDATA) == 0) { + if (!m_bHasCipherData) { + m_bHasCipherData = true; + PModelReaderNode_KeyStoreCipherValue pXMLNode = extractCopy(); + pXMLNode->parseXML(pXMLReader); + m_rgCipherValue = pXMLNode->getCipherValue(); + } + } else { + m_pWarnings->addWarning(NMR_ERROR_NAMESPACE_INVALID_ELEMENT, mrwInvalidOptionalValue); + } + } + } + +} diff --git a/Source/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreCEKParams.cpp b/Source/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreCEKParams.cpp new file mode 100644 index 0000000..c8d533f --- /dev/null +++ b/Source/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreCEKParams.cpp @@ -0,0 +1,128 @@ + +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_KeyStoreCipherValue.h defines the Model Reader Node class that is related to . + +--*/ + +#include "Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreCEKParams.h" +#include "Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreCipherValue.h" +#include "Model/Reader/NMR_ModelReaderNode_StringValue.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_KeyStoreResourceData.h" +#include "Model/Classes/NMR_KeyStoreAccessRight.h" +#include "Model/Classes/NMR_KeyStoreFactory.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_StringUtils.h" + +#include "Libraries/cpp-base64/base64.h" + +namespace NMR { + namespace ParserUtils { + eKeyStoreEncryptAlgorithm parseEncryptionAlgorithm(std::string const & value) { + if (XML_3MF_SECURE_CONTENT_ENCRYPTION_AES256 == value) { + return eKeyStoreEncryptAlgorithm::AES256_GCM; + } + throw CNMRException(NMR_ERROR_KEYSTOREINVALIDALGORITHM); + } + } + + PKeyStoreCEKParams CModelReaderNode_KeyStoreCEKParams::getCEKParams() + { + return CKeyStoreFactory::makeCEKParams(m_bCompressed, m_eAlgorithm, m_aad, m_iv, m_tag); + } + + void CModelReaderNode_KeyStoreCEKParams::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + + if (!m_bHasAlgorithm) + m_pWarnings->addWarning(NMR_ERROR_KEYSTOREMISSINGALGORTHM, eModelWarningLevel::mrwMissingMandatoryValue); + } + + void CModelReaderNode_KeyStoreCEKParams::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(XML_3MF_SECURE_CONTENT_ENCRYPTION_ALGORITHM, pAttributeName) == 0) { + try { + m_bHasAlgorithm = true; + m_eAlgorithm = ParserUtils::parseEncryptionAlgorithm(pAttributeValue); + } catch (CNMRException const &) { + m_eAlgorithm = eKeyStoreEncryptAlgorithm::AES256_GCM; + m_pWarnings->addWarning(NMR_ERROR_KEYSTOREINVALIDALGORITHM, eModelWarningLevel::mrwInvalidMandatoryValue); + } + } + else if (strcmp(XML_3MF_SECURE_CONTENT_COMPRESSION, pAttributeName) == 0) { + if (strcmp(XML_3MF_SECURE_CONTENT_COMPRESSION_DEFLATE, pAttributeValue) == 0) { + m_bCompressed = true; + } else if (strcmp(XML_3MF_SECURE_CONTENT_COMPRESSION_NONE, pAttributeValue) == 0) { + m_bCompressed = false; + } else { + m_pWarnings->addWarning(NMR_ERROR_KEYSTOREINVALIDCOMPRESSION, mrwInvalidOptionalValue); + } + } + else + m_pWarnings->addWarning(NMR_ERROR_NAMESPACE_INVALID_ATTRIBUTE, mrwInvalidOptionalValue); + } + + void CModelReaderNode_KeyStoreCEKParams::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pChildName); + __NMRASSERT(pXMLReader); + __NMRASSERT(pNameSpace); + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_SECURECONTENTSPEC) == 0) { + if (strcmp(pChildName, XML_3MF_SECURE_CONTENT_IV) == 0) { + PModelReaderNode_StringValue pXMLNode = std::make_shared(m_pWarnings); + pXMLNode->parseXML(pXMLReader); + m_iv = base64_decode(pXMLNode->getValue()); + } else if (strcmp(pChildName, XML_3MF_SECURE_CONTENT_TAG) == 0) { + PModelReaderNode_StringValue pXMLNode = std::make_shared(m_pWarnings); + pXMLNode->parseXML(pXMLReader); + m_tag = base64_decode(pXMLNode->getValue()); + } else if (strcmp(pChildName, XML_3MF_SECURE_CONTENT_AAD) == 0) { + PModelReaderNode_StringValue pXMLNode = std::make_shared(m_pWarnings); + pXMLNode->parseXML(pXMLReader); + m_aad = base64_decode(pXMLNode->getValue()); + } else { + m_pWarnings->addWarning(NMR_ERROR_NAMESPACE_INVALID_ELEMENT, mrwInvalidOptionalValue); + } + } + } +} diff --git a/Source/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreCipherValue.cpp b/Source/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreCipherValue.cpp new file mode 100644 index 0000000..d0a0420 --- /dev/null +++ b/Source/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreCipherValue.cpp @@ -0,0 +1,78 @@ + +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_KeyStoreCipherValue.h defines the Model Reader Node class that is related to . + +--*/ + +#include "Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreCipherValue.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_KeyStoreResourceData.h" +#include "Model/Classes/NMR_KeyStoreAccessRight.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_StringUtils.h" + +#include "Model/Reader/NMR_ModelReaderNode_StringValue.h" +#include "Libraries/cpp-base64/base64.h" + +namespace NMR { + + std::vector const & CModelReaderNode_KeyStoreCipherValue::getCipherValue() const + { + return m_sCipherValue; + } + + void CModelReaderNode_KeyStoreCipherValue::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + + if (m_sCipherValue.empty()) { + m_pWarnings->addWarning(NMR_ERROR_KEYSTOREINVALIDCIPHERVALUE, eModelWarningLevel::mrwMissingMandatoryValue); + } + } + + void CModelReaderNode_KeyStoreCipherValue::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) { + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_CIPHERVALUESPEC) == 0 + && strcmp(pChildName, XML_3MF_ELEMENT_CIPHERVALUE) == 0) { + PModelReaderNode_StringValue pNode = std::make_shared(m_pWarnings); + pNode->parseXML(pXMLReader); + m_sCipherValue = base64_decode(pNode->getValue()); + } + } + +} diff --git a/Source/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreConsumer.cpp b/Source/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreConsumer.cpp new file mode 100644 index 0000000..6156c7d --- /dev/null +++ b/Source/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreConsumer.cpp @@ -0,0 +1,103 @@ + +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_KeyStoreConsumer.h defines the Model Reader Node class that is related to . + +--*/ + +#include "Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreConsumer.h" +#include "Model/Reader/NMR_ModelReaderNode_StringValue.h" +#include "Model/Classes/NMR_KeyStoreFactory.h" +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_StringUtils.h" + +namespace NMR { + + void CModelReaderNode_KeyStoreConsumer::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + + // check consumer id + if (m_sConsumerID.empty()) { + m_pWarnings->addWarning(NMR_ERROR_KEYSTOREMISSINGCONSUMERID, mrwMissingMandatoryValue); + //add some default value + m_sConsumerID = "ConsumerID" + fnInt32ToString(m_pWarnings->getWarningCount()); + } + + PKeyStoreConsumer c = CKeyStoreFactory::makeConsumer(m_sConsumerID, m_sKeyID, m_sKeyValue); + m_pKeyStore->addConsumer(c); + } + + void CModelReaderNode_KeyStoreConsumer::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(XML_3MF_SECURE_CONTENT_CONSUMER_ID, pAttributeName) == 0) { + if (!m_sConsumerID.empty()) + m_pWarnings->addWarning(NMR_ERROR_KEYSTOREDUPLICATECONSUMERID, eModelWarningLevel::mrwInvalidMandatoryValue); + m_sConsumerID = pAttributeValue; + } + else if (strcmp(XML_3MF_SECURE_CONTENT_KEY_ID, pAttributeName) == 0) { + if (!m_sKeyID.empty()) + m_pWarnings->addWarning(NMR_ERROR_KEYSTOREDUPLICATECONSUMERKEYID, eModelWarningLevel::mrwInvalidOptionalValue); + m_sKeyID = pAttributeValue; + } + else + m_pWarnings->addWarning(NMR_ERROR_NAMESPACE_INVALID_ATTRIBUTE, mrwInvalidOptionalValue); + } + + void CModelReaderNode_KeyStoreConsumer::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pChildName); + __NMRASSERT(pXMLReader); + __NMRASSERT(pNameSpace); + + + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_SECURECONTENTSPEC) == 0) { + if (strcmp(pChildName, XML_3MF_ELEMENT_KEYVALUE) == 0) { + PModelReaderNode_StringValue pXMLNode = std::make_shared(m_pWarnings); + pXMLNode->parseXML(pXMLReader); + m_sKeyValue = pXMLNode->getValue(); + } + else + m_pWarnings->addWarning(NMR_ERROR_NAMESPACE_INVALID_ELEMENT, mrwInvalidOptionalValue); + } + } + +} diff --git a/Source/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreKEKParams.cpp b/Source/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreKEKParams.cpp new file mode 100644 index 0000000..b1ac663 --- /dev/null +++ b/Source/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreKEKParams.cpp @@ -0,0 +1,129 @@ + +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_KeyStoreCipherValue.h defines the Model Reader Node class that is related to . + +--*/ + +#include "Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreKEKParams.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_KeyStoreResourceData.h" +#include "Model/Classes/NMR_KeyStoreAccessRight.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_StringUtils.h" + +#include "Libraries/cpp-base64/base64.h" + +namespace NMR { + + namespace ParserUtils { + eKeyStoreWrapAlgorithm parseWrapAlgorithm(std::string const & value, bool & hasMgf1) { + if (XML_3MF_SECURE_CONTENT_KEYWRAPPING_RSA == value) { + hasMgf1 = true; + return eKeyStoreWrapAlgorithm::RSA_OAEP; + } else if (XML_3MF_SECURE_CONTENT_KEYWRAPPING_RSASHORT == value) { + return eKeyStoreWrapAlgorithm::RSA_OAEP; + } + throw CNMRException(NMR_ERROR_KEYSTOREINVALIDALGORITHM); + } + + eKeyStoreMaskGenerationFunction parseMgf(std::string const & value) { + if (XML_3MF_SECURE_CONTENT_MGF1_SHA1 == value) + return eKeyStoreMaskGenerationFunction::MGF1_SHA1; + else if (XML_3MF_SECURE_CONTENT_MGF1_SHA224 == value) + return eKeyStoreMaskGenerationFunction::MGF1_SHA224; + else if (XML_3MF_SECURE_CONTENT_MGF1_SHA256 == value) + return eKeyStoreMaskGenerationFunction::MGF1_SHA256; + else if (XML_3MF_SECURE_CONTENT_MGF1_SHA384 == value) + return eKeyStoreMaskGenerationFunction::MGF1_SHA384; + else if (XML_3MF_SECURE_CONTENT_MGF1_SHA512 == value) + return eKeyStoreMaskGenerationFunction::MGF1_SHA512; + throw CNMRException(NMR_ERROR_KEYSTOREINVALIDMGF); + } + + eKeyStoreMessageDigest parseMessageDigest(std::string const & value) { + if (XML_3MF_SECURE_CONTENT_MD_SHA1 == value) + return eKeyStoreMessageDigest::SHA1; + else if (XML_3MF_SECURE_CONTENT_MD_SHA256 == value) + return eKeyStoreMessageDigest::SHA256; + else if (XML_3MF_SECURE_CONTENT_MD_SHA384 == value) + return eKeyStoreMessageDigest::SHA384; + else if (XML_3MF_SECURE_CONTENT_MD_SHA512 == value) + return eKeyStoreMessageDigest::SHA512; + throw CNMRException(NMR_ERROR_KEYSTOREINVALIDDIGEST); + } + } + + KEKPARAMS CModelReaderNode_KeyStoreKEKParams::getKekParams() + { + return m_sKekParams; + } + + void CModelReaderNode_KeyStoreKEKParams::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + if (!m_bHasAlgorithm) + m_pWarnings->addWarning(NMR_ERROR_KEYSTOREMISSINGALGORTHM, eModelWarningLevel::mrwMissingMandatoryValue); + + if (m_bAlgHasMgf && m_sKekParams.m_eMgf != eKeyStoreMaskGenerationFunction::MGF1_SHA1) + m_pWarnings->addWarning(NMR_ERROR_KEYSTOREINCONSISTENTKEKPARAMS, eModelWarningLevel::mrwInvalidOptionalValue); + } + + void CModelReaderNode_KeyStoreKEKParams::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + try { + if (strcmp(XML_3MF_SECURE_CONTENT_WRAPPINGALGORITHM, pAttributeName) == 0) { + m_bHasAlgorithm = true; + m_sKekParams.m_eAlgorithm = ParserUtils::parseWrapAlgorithm(pAttributeValue, m_bAlgHasMgf); + } else if (strcmp(XML_3MF_SECURE_CONTENT_MGFALGORITHM, pAttributeName) == 0) { + m_sKekParams.m_eMgf = ParserUtils::parseMgf(pAttributeValue); + } else if (strcmp(XML_3MF_SECURE_CONTENT_DIGESTMETHOD, pAttributeName) == 0) { + m_sKekParams.m_eDigest = ParserUtils::parseMessageDigest(pAttributeValue); + } else { + m_pWarnings->addWarning(NMR_ERROR_NAMESPACE_INVALID_ATTRIBUTE, mrwInvalidOptionalValue); + } + } + catch (CNMRException const & e) { + m_pWarnings->addException(e, eModelWarningLevel::mrwInvalidMandatoryValue); + } + } + +} diff --git a/Source/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreResourceData.cpp b/Source/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreResourceData.cpp new file mode 100644 index 0000000..0be40da --- /dev/null +++ b/Source/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreResourceData.cpp @@ -0,0 +1,102 @@ + +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_KeyStoreResourceData.h defines the Model Reader Node class that is related to . + +--*/ + +#include "Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreResourceData.h" +#include "Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreCEKParams.h" +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_KeyStoreResourceData.h" +#include "Model/Classes/NMR_KeyStoreFactory.h" +#include "Model/Classes/NMR_PackageResourceID.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_StringUtils.h" + +namespace NMR { + + PKeyStoreResourceData CModelReaderNode_KeyStoreResourceData::getResourceData(PKeyStoreResourceDataGroup const & rdg) + { + PPackageModelPath p = model()->findOrCreateModelPath(m_sPath); + return CKeyStoreFactory::makeResourceData(rdg, p, m_pCekParams); + } + + void CModelReaderNode_KeyStoreResourceData::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + + if (m_sPath.empty()) + m_pWarnings->addWarning(NMR_ERROR_KEYSTOREMISSINGPATH, eModelWarningLevel::mrwFatal); + if (nullptr == m_pCekParams) + m_pWarnings->addWarning(NMR_ERROR_KEYSTOREMISSINGCEKPARAMS, eModelWarningLevel::mrwFatal); + } + + void CModelReaderNode_KeyStoreResourceData::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(XML_3MF_SECURE_CONTENT_PATH, pAttributeName) == 0) { + if (!m_sPath.empty()) + m_pWarnings->addWarning(NMR_ERROR_KEYSTOREDUPLICATERESOURCEDATAPATH, eModelWarningLevel::mrwInvalidMandatoryValue); + m_sPath = pAttributeValue; + } + else + m_pWarnings->addWarning(NMR_ERROR_NAMESPACE_INVALID_ATTRIBUTE, mrwInvalidOptionalValue); + } + + void CModelReaderNode_KeyStoreResourceData::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pChildName); + __NMRASSERT(pXMLReader); + __NMRASSERT(pNameSpace); + + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_SECURECONTENTSPEC) == 0) { + if (strcmp(pChildName, XML_3MF_ELEMENT_CEKPARAMS) == 0) { + if (nullptr == m_pCekParams) { + PModelReaderNode_KeyStoreCEKParams pXMLNode = extractCopy(); + pXMLNode->parseXML(pXMLReader); + m_pCekParams = pXMLNode->getCEKParams(); + } + } + else + m_pWarnings->addWarning(NMR_ERROR_NAMESPACE_INVALID_ELEMENT, mrwInvalidOptionalValue); + } + } + +} diff --git a/Source/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreResourceDataGroup.cpp b/Source/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreResourceDataGroup.cpp new file mode 100644 index 0000000..21518e9 --- /dev/null +++ b/Source/Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreResourceDataGroup.cpp @@ -0,0 +1,110 @@ + +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode_KeyStoreResourceDataGroup.h defines the Model Reader Node class that is related to . + +--*/ + +#include "Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreResourceDataGroup.h" +#include "Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreAccessRight.h" +#include "Model/Reader/SecureContent101/NMR_ModelReaderNode_KeyStoreResourceData.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_KeyStoreResourceData.h" +#include "Model/Classes/NMR_KeyStoreAccessRight.h" + +#include "Model/Classes/NMR_KeyStoreFactory.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_StringUtils.h" + +namespace NMR { + + void CModelReaderNode_KeyStoreResourceDataGroup::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + if (!m_pGroup) { + if (!m_bHasUuid) + m_pWarnings->addWarning(NMR_ERROR_KEYSTOREMISSINGKEYUUID, eModelWarningLevel::mrwInvalidMandatoryValue); + m_pGroup = CKeyStoreFactory::makeResourceDataGroup(); + } + + // Parse Content + parseContent(pXMLReader); + + keystore()->addResourceDataGroup(m_pGroup); + } + + void CModelReaderNode_KeyStoreResourceDataGroup::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(XML_3MF_SECURE_CONTENT_KEY_UUID, pAttributeName) == 0) { + m_bHasUuid = true; + if (m_pGroup != nullptr) + m_pWarnings->addWarning(NMR_ERROR_KEYSTOREDUPLICATERESOURCEDATAGROUP, eModelWarningLevel::mrwInvalidMandatoryValue); + try { + m_pGroup = CKeyStoreFactory::makeResourceDataGroup(std::make_shared(pAttributeValue)); + } catch (CNMRException const &) { + m_pWarnings->addWarning(NMR_ERROR_KEYSTOREINVALIDKEYUUID, eModelWarningLevel::mrwInvalidMandatoryValue); + } + } + else + m_pWarnings->addWarning(NMR_ERROR_NAMESPACE_INVALID_ATTRIBUTE, mrwInvalidOptionalValue); + } + + void CModelReaderNode_KeyStoreResourceDataGroup::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pChildName); + __NMRASSERT(pXMLReader); + __NMRASSERT(pNameSpace); + + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_SECURECONTENTSPEC) == 0) { + if (strcmp(pChildName, XML_3MF_ELEMENT_RESOURCEDATA) == 0) { + PModelReaderNode_KeyStoreResourceData pXMLNode = extractCopy(); + pXMLNode->parseXML(pXMLReader); + PKeyStoreResourceData rd = pXMLNode->getResourceData(m_pGroup); + m_pKeyStore->addResourceData(rd); + } else if (strcmp(pChildName, XML_3MF_ELEMENT_ACCESSRIGHT) == 0) { + PModelReaderNode_KeyStoreAccessRight pXMLNode = extractCopy(); + pXMLNode->parseXML(pXMLReader); + PKeyStoreAccessRight ar = pXMLNode->getAccessRight(); + m_pGroup->addAccessRight(ar); + } else + m_pWarnings->addWarning(NMR_ERROR_NAMESPACE_INVALID_ELEMENT, mrwInvalidOptionalValue); + } + } + +} diff --git a/Source/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Polygon.cpp b/Source/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Polygon.cpp new file mode 100644 index 0000000..a659c5a --- /dev/null +++ b/Source/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Polygon.cpp @@ -0,0 +1,82 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +--*/ + +#include "Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Polygon.h" +#include "Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Segment.h" + +#include "Model/Classes/NMR_ModelAttachment.h" + +#include "Common/NMR_StringUtils.h" + +#include "Model/Classes/NMR_ModelConstants.h" + +namespace NMR { + void CModelReaderNode_Slices1507_Polygon::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) { + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_SLICEPOLYGON_STARTV) == 0) { + m_StartV = fnStringToUint32(pAttributeValue); + } + else + throw CNMRException(NMR_ERROR_SLICE_INVALIDATTRIBUTE); + } + + void CModelReaderNode_Slices1507_Polygon::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) { + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_SLICESPEC) == 0) { + if (strcmp(pChildName, XML_3MF_ELEMENT_SLICESEGMENT) == 0) { + PModelReaderNode_Slices1507_Segment pXMLNode = std::make_shared(m_pSlice, m_PolygonIndex, m_pWarnings); + pXMLNode->parseXML(pXMLReader); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT), mrwInvalidOptionalValue); + } + } + + CModelReaderNode_Slices1507_Polygon::CModelReaderNode_Slices1507_Polygon(_In_ CSlice *pSlice, _In_ PModelWarnings pWarnings) : CModelReaderNode(pWarnings) { + m_pSlice = pSlice; + } + + void CModelReaderNode_Slices1507_Polygon::parseXML(_In_ CXmlReader * pXMLReader) { + m_PolygonIndex = m_pSlice->beginPolygon(); + + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + m_pSlice->addPolygonIndex(m_PolygonIndex, m_StartV); + + // Parse Content + parseContent(pXMLReader); + + if (!m_pSlice->isPolygonValid(m_PolygonIndex)) { + throw CNMRException(NMR_ERROR_CLOSED_SLICE_POLYGON_IS_LINE); + } + } +} diff --git a/Source/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Segment.cpp b/Source/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Segment.cpp new file mode 100644 index 0000000..dfb7678 --- /dev/null +++ b/Source/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Segment.cpp @@ -0,0 +1,61 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +--*/ + +#include "Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Segment.h" +#include "Common/NMR_StringUtils.h" +#include "Model/Classes/NMR_ModelConstants.h" + +namespace NMR { + void CModelReaderNode_Slices1507_Segment::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) { + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_SLICESEGMENT_V2) == 0) { + m_pSlice->addPolygonIndex(m_PolygonIndex, fnStringToInt32(pAttributeValue)); + } + } + + void CModelReaderNode_Slices1507_Segment::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) { + + } + + CModelReaderNode_Slices1507_Segment::CModelReaderNode_Slices1507_Segment(_In_ CSlice *pSlice, nfUint32 nPolygonIndex, _In_ PModelWarnings pWarnings) : CModelReaderNode(pWarnings) { + m_pSlice = pSlice; + m_PolygonIndex = nPolygonIndex; + } + + void CModelReaderNode_Slices1507_Segment::parseXML(_In_ CXmlReader * pXMLReader) { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + } +} diff --git a/Source/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Slice.cpp b/Source/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Slice.cpp new file mode 100644 index 0000000..21a5b29 --- /dev/null +++ b/Source/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Slice.cpp @@ -0,0 +1,82 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +--*/ + +#include "Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Slice.h" +#include "Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Vertices.h" +#include "Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Polygon.h" + +#include "Common/NMR_StringUtils.h" +#include "Model/Classes/NMR_ModelConstants.h" + +namespace NMR { + void CModelReaderNode_Slices1507_Slice::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) { + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_SLICEZTOP) == 0) { + if (m_bHasZTop) + throw CNMRException(NMR_ERROR_DUPLICATETEZTOP); + m_TopZ = fnStringToFloat(pAttributeValue); + m_bHasZTop = true; + } + } + + void CModelReaderNode_Slices1507_Slice::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) { + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_SLICESPEC) == 0) { + if (strcmp(pChildName, XML_3MF_ELEMENT_SLICEVERTICES) == 0) { + PModelReaderNode_Slices1507_Vertices pXMLNode = std::make_shared(m_Slice.get(), m_pWarnings); + pXMLNode->parseXML(pXMLReader); + } + else if (strcmp(pChildName, XML_3MF_ELEMENT_SLICEPOLYGON) == 0) { + PModelReaderNode_Slices1507_Polygon pXMLNode = std::make_shared(m_Slice.get(), m_pWarnings); + pXMLNode->parseXML(pXMLReader); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT), mrwInvalidOptionalValue); + } + } + + CModelReaderNode_Slices1507_Slice::CModelReaderNode_Slices1507_Slice(_In_ CModelSliceStack *pSliceStack, _In_ PModelWarnings pWarnings) : CModelReaderNode(pWarnings) { + m_pSliceStack = pSliceStack; + m_bHasZTop = false; + } + + void CModelReaderNode_Slices1507_Slice::parseXML(_In_ CXmlReader * pXMLReader) { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + m_Slice = m_pSliceStack->AddSlice(m_TopZ); + + // Parse Content + parseContent(pXMLReader); + if (!m_bHasZTop) + throw CNMRException(NMR_ERROR_MISSINGTEZTOP); + } +} diff --git a/Source/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceRef.cpp b/Source/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceRef.cpp new file mode 100644 index 0000000..ac99b7c --- /dev/null +++ b/Source/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceRef.cpp @@ -0,0 +1,84 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +--*/ + +#include "Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceRef.h" + +#include "Model/Classes/NMR_ModelAttachment.h" + +#include "Common/NMR_StringUtils.h" + +#include "Model/Classes/NMR_ModelConstants.h" + +namespace NMR { + void CModelReaderNode_Slice1507_SliceRef::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) { + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_SLICEREF_ID) == 0) { + m_SliceStackId = fnStringToUint32(pAttributeValue); + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_SLICEREF_PATH) == 0) { + m_Path = pAttributeValue; + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_SLICEZTOP) == 0) { + // according to spec, the attribute "ztop" is not allowed in a SliceRef + // We we only warn here + m_pWarnings->addException(CNMRException(NMR_ERROR_SLICE_INVALIDATTRIBUTE), mrwInvalidMandatoryValue); + } + else + throw CNMRException(NMR_ERROR_SLICE_INVALIDATTRIBUTE); + } + + void CModelReaderNode_Slice1507_SliceRef::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) { + + } + + CModelReaderNode_Slice1507_SliceRef::CModelReaderNode_Slice1507_SliceRef(_In_ PModelWarnings pWarnings) : CModelReaderNode(pWarnings) { + m_SliceStackId = -1; + m_Path = ""; + } + + void CModelReaderNode_Slice1507_SliceRef::parseXML(_In_ CXmlReader * pXMLReader) { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + } + + std::string CModelReaderNode_Slice1507_SliceRef::Path() + { + return m_Path; + } + nfUint32 CModelReaderNode_Slice1507_SliceRef::SliceStackId() + { + return m_SliceStackId; + } +} diff --git a/Source/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceRefModel.cpp b/Source/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceRefModel.cpp new file mode 100644 index 0000000..0ec26dd --- /dev/null +++ b/Source/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceRefModel.cpp @@ -0,0 +1,74 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +--*/ + +#include "Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceRefResources.h" +#include "Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceRefModel.h" +#include "Common/NMR_StringUtils.h" +#include "Model/Classes/NMR_ModelConstants.h" + +namespace NMR { + void CModelReader_Slice1507_SliceRefModel::OnNSChildElement( + _In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + if (strcmp(pChildName, XML_3MF_ELEMENT_BUILD) == 0) { + if (m_bHasBuild) + throw CNMRException(NMR_ERROR_DUPLICATEBUILDSECTION); + m_bHasBuild = true; + } + else if (strcmp(pChildName, XML_3MF_ELEMENT_RESOURCES) == 0) + { + if (m_bHasResources) + throw CNMRException(NMR_ERROR_DUPLICATERESOURCES); + std::shared_ptr pXmlNode = + std::make_shared( + m_pModel, m_pWarnings, m_sSliceRefPath); + pXmlNode->parseXML(pXMLReader); + m_bHasResources = true; + } + } + + CModelReader_Slice1507_SliceRefModel::CModelReader_Slice1507_SliceRefModel( + _In_ CModel *pModel, _In_ PModelWarnings pWarnings, _In_z_ std::string sSliceRefPath) + : CModelReaderNode_ModelBase(pModel, pWarnings, sSliceRefPath.c_str(), nullptr) + { + m_sSliceRefPath = sSliceRefPath; + } + + void CModelReader_Slice1507_SliceRefModel::parseXML(_In_ CXmlReader * pXMLReader) { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + } +} diff --git a/Source/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceRefResources.cpp b/Source/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceRefResources.cpp new file mode 100644 index 0000000..50b3f19 --- /dev/null +++ b/Source/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceRefResources.cpp @@ -0,0 +1,70 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +--*/ + +#include "Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceRefResources.h" +#include "Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceStack.h" +#include "Common/NMR_StringUtils.h" +#include "Model/Classes/NMR_ModelConstants.h" + +namespace NMR { + void CModelReader_Slice1507_SliceRefResources::OnNSChildElement( + _In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_SLICESPEC) == 0) { + if (strcmp(pChildName, XML_3MF_ELEMENT_SLICESTACKRESOURCE) == 0) + { + PModelReaderNode_Slice1507_SliceStack pXmlNode = + std::make_shared(m_pModel, m_pWarnings, nullptr, m_sSliceRefPath); + pXmlNode->parseXML(pXMLReader); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT), mrwInvalidOptionalValue); + } + } + + CModelReader_Slice1507_SliceRefResources::CModelReader_Slice1507_SliceRefResources( + _In_ CModel *pModel, _In_ PModelWarnings pWarnings, _In_z_ const std::string sSliceRefPath) + : CModelReaderNode(pWarnings) + { + m_pModel = pModel; + m_sSliceRefPath = sSliceRefPath; + } + + void CModelReader_Slice1507_SliceRefResources::parseXML(_In_ CXmlReader * pXMLReader) { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + } +} diff --git a/Source/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceStack.cpp b/Source/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceStack.cpp new file mode 100644 index 0000000..c840527 --- /dev/null +++ b/Source/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceStack.cpp @@ -0,0 +1,123 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +--*/ + +#include "Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceStack.h" +#include "Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceRef.h" +#include "Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Slice.h" +#include "Common/NMR_StringUtils.h" +#include "Model/Classes/NMR_ModelConstants.h" + +namespace NMR { + void CModelReaderNode_Slice1507_SliceStack::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) { + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_SLICESTACKZBOTTOM) == 0) { + m_BottomZ = fnStringToFloat(pAttributeValue); + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_SLICESTACKID) == 0) { + m_Id = fnStringToUint32(pAttributeValue); + } + else + throw CNMRException(NMR_ERROR_SLICE_INVALIDATTRIBUTE); + } + + void CModelReaderNode_Slice1507_SliceStack::OnNSChildElement( + _In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + if (strcmp(pChildName, XML_3MF_ELEMENT_SLICE) == 0) { + if (!m_pSliceStackResource->AllowsGeometry()) + throw CNMRException(NMR_ERROR_SLICESTACK_SLICESANDSLICEREF); + PModelReaderNode_Slices1507_Slice pXMLNode = nullptr; + + if (m_pSliceStackResource->getSliceCount() % PROGRESS_READSLICESUPDATE == PROGRESS_READSLICESUPDATE - 1 ) { + m_pProgressMonitor->SetProgressIdentifier(ProgressIdentifier::PROGRESS_READSLICES); + m_pProgressMonitor->ReportProgressAndQueryCancelled(true); + } + + pXMLNode = std::make_shared(m_pSliceStackResource.get(), m_pWarnings); + pXMLNode->parseXML(pXMLReader); + } + else if (strcmp(pChildName, XML_3MF_ELEMENT_SLICEREFRESOURCE) == 0) { + if (!m_pSliceStackResource->AllowsReferences()) + throw CNMRException(NMR_ERROR_SLICESTACK_SLICESANDSLICEREF); + PModelReaderNode_Slice1507_SliceRef pXmlNode = std::make_shared(m_pWarnings); + pXmlNode->parseXML(pXMLReader); + + std::string path = pXmlNode->Path(); + if (path.empty()) { + path = m_pModel->currentPath(); + } + PModelResource pResource = m_pModel->findResource(path, pXmlNode->SliceStackId()); + PModelSliceStack pSliceStackResource = std::dynamic_pointer_cast(pResource); + if (!pSliceStackResource) + throw CNMRException(NMR_ERROR_SLICESTACKRESOURCE_NOT_FOUND); + if (m_pSliceStackResource->OwnPath() != m_pModel->rootPath() ) + throw CNMRException(NMR_ERROR_SLICEREFSTOODEEP); + + try { + m_pSliceStackResource->AddSliceRef(pSliceStackResource, true); + } catch (const CNMRException& e) + { + if (e.getErrorCode() == NMR_ERROR_SLICES_REFS_Z_NOTINCREASING) + { + getWarnings()->addException(e, mrwInvalidMandatoryValue); + m_pSliceStackResource->AddSliceRef(pSliceStackResource, false); + } + else + throw; + } + } + } + + CModelReaderNode_Slice1507_SliceStack::CModelReaderNode_Slice1507_SliceStack( + _In_ CModel * pModel, _In_ PModelWarnings pWarnings, + _In_ PProgressMonitor pProgressMonitor,_In_ const std::string sSlicePath) + : CModelReaderNode(pWarnings, pProgressMonitor) + { + m_sSlicePath = sSlicePath; + m_pModel = pModel; + } + + void CModelReaderNode_Slice1507_SliceStack::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + m_pSliceStackResource = std::make_shared(m_Id, m_pModel, m_BottomZ); + + // Parse Content + parseContent(pXMLReader); + + m_pSliceStackResource->SetOwnPath(m_sSlicePath); + + m_pModel->addResource(m_pSliceStackResource); + } +} diff --git a/Source/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Vertex.cpp b/Source/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Vertex.cpp new file mode 100644 index 0000000..4077761 --- /dev/null +++ b/Source/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Vertex.cpp @@ -0,0 +1,67 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +--*/ + +#include "Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Vertex.h" +#include "Common/NMR_StringUtils.h" +#include "Model/Classes/NMR_ModelConstants.h" + +namespace NMR { + void CModelReaderNode_Slices1507_Vertex::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) { + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_SLICEVERTEX_X) == 0) { + m_x = fnStringToFloat(pAttributeValue); + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_SLICEVERTEX_Y) == 0) { + m_y = fnStringToFloat(pAttributeValue); + } + else + throw CNMRException(NMR_ERROR_SLICE_INVALIDATTRIBUTE); + } + + void CModelReaderNode_Slices1507_Vertex::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) { + + } + + CModelReaderNode_Slices1507_Vertex::CModelReaderNode_Slices1507_Vertex(_In_ CSlice *pSlice, _In_ PModelWarnings pWarnings) : CModelReaderNode(pWarnings) { + m_pSlice = pSlice; + } + + void CModelReaderNode_Slices1507_Vertex::parseXML(_In_ CXmlReader * pXMLReader) { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + + m_pSlice->addVertex(m_x, m_y); + } +} diff --git a/Source/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Vertices.cpp b/Source/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Vertices.cpp new file mode 100644 index 0000000..f7292d1 --- /dev/null +++ b/Source/Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Vertices.cpp @@ -0,0 +1,66 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +--*/ + +#include "Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Vertices.h" +#include "Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Vertex.h" +#include "Common/NMR_StringUtils.h" +#include "Model/Classes/NMR_ModelConstants.h" + +namespace NMR { + + void CModelReaderNode_Slices1507_Vertices::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) { + + } + + void CModelReaderNode_Slices1507_Vertices::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) { + if (strcmp(pChildName, XML_3MF_ELEMENT_SLICEVERTEX) == 0) { + PModelReaderNode_Slices1507_Vertex pXMLNode = std::make_shared(m_pSlice, m_pWarnings); + pXMLNode->parseXML(pXMLReader); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT), mrwInvalidOptionalValue); + } + + CModelReaderNode_Slices1507_Vertices::CModelReaderNode_Slices1507_Vertices(_In_ CSlice *pSlice, _In_ PModelWarnings pWarnings) : CModelReaderNode(pWarnings) { + m_pSlice = pSlice; + } + + void CModelReaderNode_Slices1507_Vertices::parseXML(_In_ CXmlReader * pXMLReader) { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + + // Parse Content + parseContent(pXMLReader); + } +} diff --git a/Source/Model/Reader/v093/NMR_ModelReaderNode093_Build.cpp b/Source/Model/Reader/v093/NMR_ModelReaderNode093_Build.cpp new file mode 100644 index 0000000..740166b --- /dev/null +++ b/Source/Model/Reader/v093/NMR_ModelReaderNode093_Build.cpp @@ -0,0 +1,85 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode093_Build.cpp implements the Model Reader Build Node Class. +A build reader model node is a parser for the build node of an XML Model Stream. + +--*/ + +#include "Model/Reader/v093/NMR_ModelReaderNode093_Build.h" +#include "Model/Reader/v093/NMR_ModelReaderNode093_BuildItem.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CModelReaderNode093_Build::CModelReaderNode093_Build(_In_ CModel * pModel, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + __NMRASSERT(pModel); + m_pModel = pModel; + } + + void CModelReaderNode093_Build::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + } + + void CModelReaderNode093_Build::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + } + + void CModelReaderNode093_Build::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pChildName); + __NMRASSERT(pXMLReader); + __NMRASSERT(pNameSpace); + + if ((strcmp(pNameSpace, XML_3MF_NAMESPACE_CORESPEC093) == 0 ) || (strcmp(pNameSpace, "") == 0)) { + + if (strcmp(pChildName, XML_3MF_ELEMENT_ITEM) == 0) { + PModelReaderNode pXMLNode = std::make_shared(m_pModel, m_pWarnings); + pXMLNode->parseXML(pXMLReader); + + } + } + } + +} diff --git a/Source/Model/Reader/v093/NMR_ModelReaderNode093_BuildItem.cpp b/Source/Model/Reader/v093/NMR_ModelReaderNode093_BuildItem.cpp new file mode 100644 index 0000000..db3a75a --- /dev/null +++ b/Source/Model/Reader/v093/NMR_ModelReaderNode093_BuildItem.cpp @@ -0,0 +1,102 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode093_BuildItem.cpp implements the Model Reader BuildItem Node Class. +A builditem reader model node is a parser for the builditem node of an XML Model Stream. + +--*/ + +#include "Model/Reader/v093/NMR_ModelReaderNode093_BuildItem.h" +#include "Model/Classes/NMR_ModelBuildItem.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_StringUtils.h" + +namespace NMR { + + CModelReaderNode093_BuildItem::CModelReaderNode093_BuildItem(_In_ CModel * pModel, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + __NMRASSERT(pModel); + m_pModel = pModel; + m_ObjectID = 0; + m_bHasID = false; + + m_mTransform = fnMATRIX3_identity(); + } + + void CModelReaderNode093_BuildItem::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + + if (!m_bHasID) + throw CNMRException(NMR_ERROR_MISSINGBUILDITEMOBJECTID); + + PPackageResourceID pID = m_pModel->findPackageResourceID(m_pModel->currentPath(), m_ObjectID); + if (!pID.get()) + throw CNMRException(NMR_ERROR_COULDNOTFINDBUILDITEMOBJECT); + CModelObject * pObject = m_pModel->findObject(pID->getUniqueID()); + if (!pObject) + throw CNMRException(NMR_ERROR_COULDNOTFINDBUILDITEMOBJECT); + + + // Create Build Item + PModelBuildItem pBuildItem = std::make_shared(pObject, m_mTransform, m_pModel->createHandle()); + m_pModel->addBuildItem(pBuildItem); + } + + void CModelReaderNode093_BuildItem::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_ITEM_OBJECTID) == 0) { + if (m_bHasID) + throw CNMRException(NMR_ERROR_DUPLICATEBUILDITEMOBJECTID); + + m_ObjectID = fnStringToUint32(pAttributeValue); + m_ObjectID++; + m_bHasID = true; + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_ITEM_TRANSFORM) == 0) { + m_mTransform = fnMATRIX3_fromString(pAttributeValue); + } + } + + +} diff --git a/Source/Model/Reader/v093/NMR_ModelReaderNode093_Color.cpp b/Source/Model/Reader/v093/NMR_ModelReaderNode093_Color.cpp new file mode 100644 index 0000000..6758f81 --- /dev/null +++ b/Source/Model/Reader/v093/NMR_ModelReaderNode093_Color.cpp @@ -0,0 +1,168 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: +NMR_ModelReaderNode093_Color.cpp implements the Model Reader Color Node Class. +A color reader model node is a parser for the color node of an XML Model Stream. + +--*/ + +#include "Model/Reader/v093/NMR_ModelReaderNode093_Color.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_StringUtils.h" +#include +#include + +namespace NMR { + + CModelReaderNode093_Color::CModelReaderNode093_Color(_In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + m_nResourceID = 0; + m_nTextureID = 0; + } + + void CModelReaderNode093_Color::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + + // Parse Color + parseColor(); + } + + nfColor CModelReaderNode093_Color::retrieveColor() + { + return m_cColor; + } + + void CModelReaderNode093_Color::parseColor() + { + m_cColor = 0; + + try { + if (m_sColorString.length() > 0) { + nfChar bFirstChar = m_sColorString[0]; + if (bFirstChar == '#') { + if (fnStringToSRGBColor(m_sColorString.c_str(), m_cColor)) { + return; + } + } + + if (bFirstChar == 's') { + std::string sSubStr = m_sColorString.substr(0, 5); + if (sSubStr == "scRGB") { + // parse scRGB String + throw CNMRException(NMR_ERROR_NOTIMPLEMENTED); + } + } + + if (bFirstChar == L't') { + std::string sSubStr = m_sColorString.substr(0, 4); + if (sSubStr == "tex(") { + // parse Texture String + + if (m_sColorString.length() > 4) { + std::string sTexID = m_sColorString.substr(4, m_sColorString.length() - sSubStr.length() - 1); + nfInt32 nValue = fnStringToInt32(sTexID.c_str()); + if ((nValue < 0) || (nValue >= XML_3MF_MAXRESOURCEINDEX)) + throw CNMRException(NMR_ERROR_INVALIDTEXTUREREFERENCE); + + m_nTextureID = nValue + 1; + return; + } + else { + throw CNMRException(NMR_ERROR_INVALIDTEXTUREREFERENCE); + } + } + } + + if (bFirstChar == 'C') { + std::string sSubStr4 = m_sColorString.substr(0, 4); + if (sSubStr4 == "CMYK") { + throw CNMRException(NMR_ERROR_NOTSUPPORTINGLEGACYCMYK); + } + } + + } + + throw CNMRException(NMR_ERROR_INVALIDVALUEINCOLORSTRING); + } + catch (CNMRException & Exception) { + m_pWarnings->addException(Exception, mrwMissingMandatoryValue); + } + + } + + + ModelResourceID CModelReaderNode093_Color::retrieveID() + { + try { + //if (m_nUniqueResourceID == 0) + //throw CNMRException(NMR_ERROR_MISSINGMODELCOLORID); + } + catch (CNMRException & Exception) { + m_pWarnings->addException(Exception, mrwMissingMandatoryValue); + } + + return m_nResourceID; + } + + void CModelReaderNode093_Color::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_COLOR_VALUE) == 0) { + m_sColorString = pAttributeValue; + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_COLOR_ID) == 0) { + if (m_nResourceID != 0) + throw CNMRException(NMR_ERROR_DUPLICATECOLORID); + + // Convert to integer and make a input and range check! + m_nResourceID = fnStringToUint32(pAttributeValue); + m_nResourceID++; + } + + } + + ModelResourceID CModelReaderNode093_Color::retrieveTextureID() + { + return m_nTextureID; + } + +} diff --git a/Source/Model/Reader/v093/NMR_ModelReaderNode093_Component.cpp b/Source/Model/Reader/v093/NMR_ModelReaderNode093_Component.cpp new file mode 100644 index 0000000..e103340 --- /dev/null +++ b/Source/Model/Reader/v093/NMR_ModelReaderNode093_Component.cpp @@ -0,0 +1,102 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode093_Component.cpp implements the Model Component Reader +Node Class. + +--*/ + +#include "Model/Reader/v093/NMR_ModelReaderNode093_Component.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_ModelResource.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/Math/NMR_Matrix.h" + +namespace NMR { + + CModelReaderNode093_Component::CModelReaderNode093_Component(_In_ CModel * pModel, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + __NMRASSERT(pModel); + m_pModel = pModel; + m_ObjectID = 0; + m_bHasID = false; + m_mTransform = fnMATRIX3_identity(); + } + + void CModelReaderNode093_Component::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + } + + void CModelReaderNode093_Component::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_COMPONENT_OBJECTID) == 0) { + if (m_bHasID) + throw CNMRException(NMR_ERROR_DUPLICATECOMPONENTOBJECTID); + + m_ObjectID = fnStringToUint32(pAttributeValue); + m_ObjectID++; + m_bHasID = true; + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_COMPONENT_TRANSFORM) == 0) { + m_mTransform = fnMATRIX3_fromString(pAttributeValue); + } + } + + CModelObject * CModelReaderNode093_Component::getObject() + { + if (!m_bHasID) + throw CNMRException(NMR_ERROR_MISSINGMODELOBJECTID); + + PPackageResourceID pRID = m_pModel->findPackageResourceID(m_pModel->currentPath(), m_ObjectID); + if (pRID.get()) + return m_pModel->findObject(pRID->getUniqueID()); + return nullptr; + } + + NMATRIX3 CModelReaderNode093_Component::getTransform() + { + return m_mTransform; + } + +} diff --git a/Source/Model/Reader/v093/NMR_ModelReaderNode093_Components.cpp b/Source/Model/Reader/v093/NMR_ModelReaderNode093_Components.cpp new file mode 100644 index 0000000..6a11a37 --- /dev/null +++ b/Source/Model/Reader/v093/NMR_ModelReaderNode093_Components.cpp @@ -0,0 +1,96 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode093_Components.cpp implements the Model Components Reader +Node Class. + +--*/ + +#include "Model/Reader/v093/NMR_ModelReaderNode093_Components.h" +#include "Model/Reader/v093/NMR_ModelReaderNode093_Component.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CModelReaderNode093_Components::CModelReaderNode093_Components(_In_ CModelComponentsObject * pComponentsObject, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + __NMRASSERT(pComponentsObject); + m_pComponentsObject = pComponentsObject; + } + + void CModelReaderNode093_Components::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + } + + void CModelReaderNode093_Components::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + } + + void CModelReaderNode093_Components::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pChildName); + __NMRASSERT(pXMLReader); + __NMRASSERT(pNameSpace); + + if ((strcmp(pNameSpace, XML_3MF_NAMESPACE_CORESPEC093) == 0) || (strcmp(pNameSpace, "") == 0)) { + if (strcmp(pChildName, XML_3MF_ELEMENT_COMPONENT) == 0) { + // Read Component + PModelReaderNode093_Component pXMLNode = std::make_shared(m_pComponentsObject->getModel(), m_pWarnings); + pXMLNode->parseXML(pXMLReader); + + // Retrieve object and transform + CModelObject * pObject = pXMLNode->getObject(); + NMATRIX3 mTransform = pXMLNode->getTransform(); + + // Check, if we have an associated object + if (!pObject) + throw CNMRException(NMR_ERROR_COULDNOTFINDCOMPONENTOBJECT); + + // Create component + PModelComponent pComponent = std::make_shared(pObject, mTransform); + m_pComponentsObject->addComponent(pComponent); + } + } + } + +} diff --git a/Source/Model/Reader/v093/NMR_ModelReaderNode093_Material.cpp b/Source/Model/Reader/v093/NMR_ModelReaderNode093_Material.cpp new file mode 100644 index 0000000..4cefc2b --- /dev/null +++ b/Source/Model/Reader/v093/NMR_ModelReaderNode093_Material.cpp @@ -0,0 +1,119 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: +NMR_ModelReaderNode093_Material.cpp implements the Model Reader Material Node Class. +A material reader model node is a parser for the material node of an XML Model Stream. + +--*/ + +#include "Model/Reader/v093/NMR_ModelReaderNode093_Material.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_StringUtils.h" +#include +#include + +namespace NMR { + + CModelReaderNode093_Material::CModelReaderNode093_Material(_In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + m_nResourceID = 0; + m_nColorID = 0; + m_sName = "material"; + } + + void CModelReaderNode093_Material::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + } + + std::string CModelReaderNode093_Material::retrieveName() + { + return m_sName; + } + + ModelResourceID CModelReaderNode093_Material::retrieveColorID() + { + return m_nColorID; + } + + + ModelResourceID CModelReaderNode093_Material::retrieveID() + { + try { + if (m_nResourceID == 0) + throw CNMRException(NMR_ERROR_MISSINGMODELMATERIALID); + } + catch (CNMRException & Exception) { + m_pWarnings->addException(Exception, mrwMissingMandatoryValue); + } + + return m_nResourceID; + } + + + + void CModelReaderNode093_Material::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_MATERIAL_ID) == 0) { + if (m_nResourceID != 0) + throw CNMRException(NMR_ERROR_DUPLICATEMATERIALID); + + // Convert to integer and make a input and range check! + m_nResourceID = fnStringToUint32(pAttributeValue); + m_nResourceID++; + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_MATERIAL_COLORID) == 0) { + // Convert to integer and make a input and range check! + m_nColorID = fnStringToUint32(pAttributeValue); + m_nColorID++; + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_MATERIAL_NAME) == 0) { + // Convert to integer and make a input and range check! + m_sName = pAttributeValue; + } + + } + + +} + diff --git a/Source/Model/Reader/v093/NMR_ModelReaderNode093_Mesh.cpp b/Source/Model/Reader/v093/NMR_ModelReaderNode093_Mesh.cpp new file mode 100644 index 0000000..5c06ea6 --- /dev/null +++ b/Source/Model/Reader/v093/NMR_ModelReaderNode093_Mesh.cpp @@ -0,0 +1,108 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode093_Mesh.cpp implements the Model Reader Mesh Node Class. +A mesh reader model node is a parser for the mesh node of an XML Model Stream. + +--*/ + +#include "Model/Reader/v093/NMR_ModelReaderNode093_Mesh.h" +#include "Model/Reader/v093/NMR_ModelReaderNode093_Vertices.h" +#include "Model/Reader/v093/NMR_ModelReaderNode093_Triangles.h" +#include "Model/Reader/v093/NMR_ModelReaderNode093_TextureVertices.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CModelReaderNode093_Mesh::CModelReaderNode093_Mesh(_In_ CModel * pModel, _In_ CMesh * pMesh, _In_ PModelReader_ColorMapping pColorMapping, _In_ PModelBaseMaterialResource pMaterialResource, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + __NMRASSERT(pMesh); + __NMRASSERT(pModel); + __NMRASSERT(pColorMapping.get() != nullptr); + + m_pMesh = pMesh; + m_pModel = pModel; + + m_pTexCoordMapping = std::make_shared(); + m_pColorMapping = pColorMapping; + m_pMaterialResource = pMaterialResource; + } + + void CModelReaderNode093_Mesh::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + } + + void CModelReaderNode093_Mesh::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + } + + void CModelReaderNode093_Mesh::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pChildName); + __NMRASSERT(pXMLReader); + __NMRASSERT(pNameSpace); + + if ((strcmp(pNameSpace, XML_3MF_NAMESPACE_CORESPEC093) == 0) || (strcmp(pNameSpace, "") == 0)) { + + if (strcmp(pChildName, XML_3MF_ELEMENT_VERTICES) == 0) + { + PModelReaderNode pXMLNode = std::make_shared(m_pMesh, m_pWarnings); + pXMLNode->parseXML(pXMLReader); + } + + if (strcmp(pChildName, XML_3MF_ELEMENT_TRIANGLES) == 0) + { + PModelReaderNode pXMLNode = std::make_shared(m_pModel, m_pMesh, m_pColorMapping, m_pTexCoordMapping, m_pMaterialResource, m_pWarnings); + pXMLNode->parseXML(pXMLReader); + } + + if (strcmp(pChildName, XML_3MF_ELEMENT_TEXTUREVERTICES) == 0) + { + PModelReaderNode pXMLNode = std::make_shared(m_pMesh, m_pWarnings, m_pTexCoordMapping); + pXMLNode->parseXML(pXMLReader); + } + + } + } + +} diff --git a/Source/Model/Reader/v093/NMR_ModelReaderNode093_Object.cpp b/Source/Model/Reader/v093/NMR_ModelReaderNode093_Object.cpp new file mode 100644 index 0000000..14860a0 --- /dev/null +++ b/Source/Model/Reader/v093/NMR_ModelReaderNode093_Object.cpp @@ -0,0 +1,207 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode093_Object.cpp implements the Model Reader Object Node Class. +A object reader model node is a parser for the object node of an XML Model +Stream. + +--*/ + +#include "Model/Reader/v093/NMR_ModelReaderNode093_Object.h" +#include "Model/Reader/v093/NMR_ModelReaderNode093_Mesh.h" +#include "Model/Reader/v093/NMR_ModelReaderNode093_Components.h" + +#include "Common/MeshInformation/NMR_MeshInformation_Properties.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_ModelMeshObject.h" + +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CModelReaderNode093_Object::CModelReaderNode093_Object(_In_ CModel * pModel, _In_ PModelReader_ColorMapping pColorMapping, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + __NMRASSERT(pColorMapping.get() != nullptr); + + m_nID = 0; + m_sType = ""; + m_bHasType = false; + + m_pModel = pModel; + m_pObject = NULL; + m_sThumbnail = ""; + m_sName = ""; + + m_nObjectLevelColorID = 0; + m_nObjectLevelMaterialID = 0; + + m_pColorMapping = pColorMapping; + } + + void CModelReaderNode093_Object::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Use parameter and assign to model Object + if (m_nID == 0) + throw CNMRException(NMR_ERROR_MISSINGMODELOBJECTID); + + // Parse Content + parseContent(pXMLReader); + + // Check, if we have created an object + if (!m_pObject.get()) + throw CNMRException(NMR_ERROR_MISSINGOBJECTCONTENT); + + // Set Object Parameters + m_pObject->setName(m_sName); + + // Set Object Type (might fail, if string is invalid) + if (m_sType.length() > 0) { + if (!m_pObject->setObjectTypeString(m_sType, false)) + m_pWarnings->addWarning(NMR_ERROR_INVALIDMODELOBJECTTYPE, mrwInvalidOptionalValue); + } + } + + void CModelReaderNode093_Object::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_OBJECT_ID) == 0) { + if (m_nID != 0) + throw CNMRException(NMR_ERROR_DUPLICATEOBJECTID); + + // Convert to integer and make a input and range check! + m_nID = fnStringToUint32(pAttributeValue); + + // Increase ID to avoid 0 (was allowed for 0.9.3) + m_nID++; + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_OBJECT_TYPE) == 0) { + if (m_bHasType) + throw CNMRException(NMR_ERROR_DUPLICATEOBJECTTYPE); + + // Convert to integer and make a input and range check! + m_sType = pAttributeValue; + m_bHasType = true; + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_OBJECT_NAME) == 0) { + m_sName = pAttributeValue; + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_OBJECT_COLOR_ID) == 0) { + + nfInt32 nValue = fnStringToInt32(pAttributeValue); + if ((nValue >= 0) && (nValue < XML_3MF_MAXRESOURCEINDEX)) { + m_nObjectLevelColorID = nValue + 1; + } + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_OBJECT_MATERIALID) == 0) { + nfInt32 nValue = fnStringToInt32(pAttributeValue); + if ((nValue >= 0) && (nValue < XML_3MF_MAXRESOURCEINDEX)) + m_nObjectLevelMaterialID = nValue + 1; + } + + + } + + void CModelReaderNode093_Object::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pChildName); + __NMRASSERT(pXMLReader); + __NMRASSERT(pNameSpace); + + if ((strcmp(pNameSpace, XML_3MF_NAMESPACE_CORESPEC093) == 0) || (strcmp(pNameSpace, "") == 0)) { + + // Read a mesh object + if (strcmp(pChildName, XML_3MF_ELEMENT_MESH) == 0) { + // If we already have parsed an object, the node is duplicate + if (m_pObject.get()) + throw CNMRException(NMR_ERROR_AMBIGUOUSOBJECTDEFINITON); + + // Create Empty Mesh + PMesh pMesh = std::make_shared(); + // Create Mesh Object + m_pObject = std::make_shared(m_nID, m_pModel, pMesh); + + PModelBaseMaterialResource pBaseMaterialResource; + if (m_nObjectLevelMaterialID > 0) { + // every v93 material becomes its own v100 base material group resource + pBaseMaterialResource = std::dynamic_pointer_cast(m_pModel->findResource(m_pModel->currentPath(), m_nObjectLevelMaterialID)); + if (pBaseMaterialResource.get() == nullptr) { + m_pWarnings->addException(CNMRException(NMR_ERROR_INVALIDMODELRESOURCE), mrwInvalidOptionalValue); + } + } + + // Read Mesh + PModelReaderNode pXMLNode = std::make_shared(m_pModel, pMesh.get(), m_pColorMapping, pBaseMaterialResource, m_pWarnings); + pXMLNode->parseXML(pXMLReader); + + // Add Object to Parent + m_pModel->addResource(m_pObject); + + } + + + // Read a component object + if (strcmp(pChildName, XML_3MF_ELEMENT_COMPONENTS) == 0) { + // If we already have parsed an object, the node is duplicate + if (m_pObject.get()) + throw CNMRException(NMR_ERROR_AMBIGUOUSOBJECTDEFINITON); + + // Create Component List Object + PModelComponentsObject pComponentsObject = std::make_shared(m_nID, m_pModel); + m_pObject = pComponentsObject; + + // Read Components + PModelReaderNode pXMLNode = std::make_shared(pComponentsObject.get(), m_pWarnings); + pXMLNode->parseXML(pXMLReader); + + // Add Object to Parent + m_pModel->addResource(m_pObject); + + } + + + } + } + + +} diff --git a/Source/Model/Reader/v093/NMR_ModelReaderNode093_Resources.cpp b/Source/Model/Reader/v093/NMR_ModelReaderNode093_Resources.cpp new file mode 100644 index 0000000..0537211 --- /dev/null +++ b/Source/Model/Reader/v093/NMR_ModelReaderNode093_Resources.cpp @@ -0,0 +1,137 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: +NMR_ModelReaderNode093_Resources.cpp implements the Model Reader Resources Node +Class. A resources reader model node is a parser for the resources node of an +XML Model Stream. + +--*/ + +#include "Model/Reader/v093/NMR_ModelReaderNode093_Resources.h" +#include "Model/Reader/v093/NMR_ModelReaderNode093_Object.h" +#include "Model/Reader/v093/NMR_ModelReaderNode093_Color.h" +#include "Model/Reader/v093/NMR_ModelReaderNode093_Material.h" +#include "Model/Reader/v093/NMR_ModelReaderNode093_Texture.h" + +#include "Model/Reader/NMR_ModelReader_ColorMapping.h" +#include "Model/Reader/NMR_ModelReader_TexCoordMapping.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_ModelResource.h" +#include "Model/Classes/NMR_ModelTexture2D.h" +#include "Model/Classes/NMR_ModelBaseMaterials.h" +#include "Model/Classes/NMR_Model.h" + +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CModelReaderNode093_Resources::CModelReaderNode093_Resources(_In_ CModel * pModel, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + __NMRASSERT(pModel); + m_pModel = pModel; + + m_pColorMapping = std::make_shared(); + + } + + void CModelReaderNode093_Resources::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + + } + + void CModelReaderNode093_Resources::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + } + + void CModelReaderNode093_Resources::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pChildName); + __NMRASSERT(pXMLReader); + __NMRASSERT(pNameSpace); + + if ((strcmp(pNameSpace, XML_3MF_NAMESPACE_CORESPEC093) == 0) || (strcmp(pNameSpace, "") == 0)) { + + if (strcmp(pChildName, XML_3MF_ELEMENT_OBJECT) == 0) { + PModelReaderNode pXMLNode = std::make_shared(m_pModel, m_pColorMapping, m_pWarnings); + pXMLNode->parseXML(pXMLReader); + } + else if (strcmp(pChildName, XML_3MF_ELEMENT_COLOR) == 0) { + PModelReaderNode093_Color pXMLNode = std::make_shared(m_pWarnings); + pXMLNode->parseXML(pXMLReader); + + ModelResourceID nResourceID = pXMLNode->retrieveID(); + ModelResourceID nTextureRefID = pXMLNode->retrieveTextureID(); + + if (nTextureRefID > 0) { + m_pColorMapping->registerTextureReference(nResourceID, nTextureRefID); + } + else { + m_pColorMapping->registerColor(nResourceID, 0, pXMLNode->retrieveColor()); + } + } + else if (strcmp(pChildName, XML_3MF_ELEMENT_TEXTURE) == 0) { + PModelReaderNode093_Texture pXMLNode = std::make_shared(m_pModel, m_pWarnings); + pXMLNode->parseXML(pXMLReader); + } + else if (strcmp(pChildName, XML_3MF_ELEMENT_MATERIAL) == 0) { + PModelReaderNode093_Material pXMLNode = std::make_shared(m_pWarnings); + pXMLNode->parseXML(pXMLReader); + + ModelResourceID nResourceID = pXMLNode->retrieveID(); + auto pMaterialResource = std::make_shared(nResourceID, m_pModel); + m_pModel->addResource(pMaterialResource); + + nfColor cColor; + if (!m_pColorMapping->findColor(pXMLNode->retrieveColorID(), 0, cColor)) { + cColor = 0xffffffff; + } + + ModelResourceIndex nMaterialIndex; + nMaterialIndex = pMaterialResource->addBaseMaterial(pXMLNode->retrieveName(), cColor); + m_pColorMapping->registerMaterialReference(pXMLNode->retrieveID(), nMaterialIndex); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT), mrwInvalidOptionalValue); + } + } + + +} diff --git a/Source/Model/Reader/v093/NMR_ModelReaderNode093_Texture.cpp b/Source/Model/Reader/v093/NMR_ModelReaderNode093_Texture.cpp new file mode 100644 index 0000000..9ae0176 --- /dev/null +++ b/Source/Model/Reader/v093/NMR_ModelReaderNode093_Texture.cpp @@ -0,0 +1,162 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode093_Texture.cpp implements the Model Reader Texture Class. + +--*/ + +#include "Model/Reader/v093/NMR_ModelReaderNode093_Texture.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_ModelMeshObject.h" +#include "Model/Classes/NMR_ModelResource.h" +#include "Model/Classes/NMR_ModelTexture2D.h" +#include "Model/Classes/NMR_Model.h" + +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CModelReaderNode093_Texture::CModelReaderNode093_Texture(_In_ CModel * pModel, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + // Initialize variables + m_nID = 0; + + m_pModel = pModel; + } + + void CModelReaderNode093_Texture::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Use parameter and assign to model Object + if (m_nID == 0) + throw CNMRException(NMR_ERROR_MISSINGMODELRESOURCEID); + + + PModelAttachment pAttachment = m_pModel->findModelAttachment(m_sPath); + m_pTexture2DResource = CModelTexture2DResource::make(m_nID, m_pModel, pAttachment); + m_pModel->addResource(m_pTexture2DResource); + + m_pTexture2DResource->setContentTypeString(m_sContentType, true); + + if (!m_sTileStyleU.empty()) { + try { + m_pTexture2DResource->setTileStyleUString(m_sTileStyleU); + } + catch (CNMRException & e) { + if (e.getErrorCode() == NMR_ERROR_INVALIDTILESTYLE) + m_pWarnings->addException(e, mrwInvalidOptionalValue); + else + throw e; + } + } + if (!m_sTileStyleV.empty()) { + try { + m_pTexture2DResource->setTileStyleVString(m_sTileStyleV); + } + catch (CNMRException & e) { + if (e.getErrorCode() == NMR_ERROR_INVALIDTILESTYLE) + m_pWarnings->addException(e, mrwInvalidOptionalValue); + else + throw e; + } + } + + // Parse Content + parseContent(pXMLReader); + + } + + void CModelReaderNode093_Texture::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TEXTURE2D_ID) == 0) { + if (m_nID != 0) + throw CNMRException(NMR_ERROR_DUPLICATERESOURCEID); + + // Convert to integer and make a input and range check! + m_nID = fnStringToUint32(pAttributeValue); + // Increase ID to avoid 0 (was allowed for 0.9.3) + m_nID++; + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TEXTURE2D_PATH) == 0) { + m_sPath = std::string(pAttributeValue); + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TEXTURE2D_CONTENTTYPE) == 0) { + m_sContentType = std::string(pAttributeValue); + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TEXTURE2D_TILESTYLEU) == 0) { + m_sTileStyleU = std::string(pAttributeValue); + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TEXTURE2D_TILESTYLEV) == 0) { + m_sTileStyleV = std::string(pAttributeValue); + } + + } + + ModelResourceID CModelReaderNode093_Texture::getID() + { + return m_nID; + } + + std::string CModelReaderNode093_Texture::getPath() + { + return m_sPath; + } + + std::string CModelReaderNode093_Texture::getContentType() + { + return m_sContentType; + } + + std::string CModelReaderNode093_Texture::getTileStyleU() + { + return m_sTileStyleU; + } + + std::string CModelReaderNode093_Texture::getTileStyleV() + { + return m_sTileStyleV; + } + +} + diff --git a/Source/Model/Reader/v093/NMR_ModelReaderNode093_TextureVertex.cpp b/Source/Model/Reader/v093/NMR_ModelReaderNode093_TextureVertex.cpp new file mode 100644 index 0000000..3f79b97 --- /dev/null +++ b/Source/Model/Reader/v093/NMR_ModelReaderNode093_TextureVertex.cpp @@ -0,0 +1,109 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: +NMR_ModelReaderNode093_TextureVertex.cpp implements the Model Reader Texture Vertex Node Class. +A texture vertex reader model node is a parser for the vertex node of an XML Model Stream. + +--*/ + +#include "Model/Reader/v093/NMR_ModelReaderNode093_TextureVertex.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include +#include +#include + +namespace NMR { + + CModelReaderNode093_TextureVertex::CModelReaderNode093_TextureVertex(_In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + m_fU = 0.0f; + m_fV = 0.0f; + m_bHasU = false; + m_bHasV = false; + } + + void CModelReaderNode093_TextureVertex::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + } + + void CModelReaderNode093_TextureVertex::retrieveTexCoords(_Out_ nfFloat & fU, _Out_ nfFloat & fV) + { + try + { + // Texture Coordinate is missing + if ((!m_bHasU) || (!m_bHasV)) + throw CNMRException(NMR_ERROR_MODELTEXTURECOORDINATEMISSING); + } + catch (CNMRException & Exception) + { + m_pWarnings->addException(Exception, mrwInvalidOptionalValue); + } + + fU = m_fU; + fV = m_fV; + } + + void CModelReaderNode093_TextureVertex::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TEXTURE_U) == 0) { + m_fU = strtof(pAttributeValue, nullptr); + if (std::isnan (m_fU)) + throw CNMRException(NMR_ERROR_INVALIDMODELTEXTURECOORDINATES); + if (fabs (m_fU) > XML_3MF_MAXIMUMCOORDINATEVALUE) + throw CNMRException(NMR_ERROR_INVALIDMODELTEXTURECOORDINATES); + m_bHasU = true; + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TEXTURE_V) == 0) { + m_fV = strtof(pAttributeValue, nullptr); + if (std::isnan (m_fV)) + throw CNMRException(NMR_ERROR_INVALIDMODELTEXTURECOORDINATES); + if (fabs(m_fV) > XML_3MF_MAXIMUMCOORDINATEVALUE) + throw CNMRException(NMR_ERROR_INVALIDMODELTEXTURECOORDINATES); + m_bHasV = true; + } + + } + + +} diff --git a/Source/Model/Reader/v093/NMR_ModelReaderNode093_TextureVertices.cpp b/Source/Model/Reader/v093/NMR_ModelReaderNode093_TextureVertices.cpp new file mode 100644 index 0000000..32e922a --- /dev/null +++ b/Source/Model/Reader/v093/NMR_ModelReaderNode093_TextureVertices.cpp @@ -0,0 +1,100 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode093_TextureVertices.cpp defines the Model Reader Texture Vertices Node Class. +A texture vertices reader model node is a parser for the texture vertices node of an +XML Model Stream. + +--*/ + +#include "Model/Reader/v093/NMR_ModelReaderNode093_TextureVertices.h" +#include "Model/Reader/v093/NMR_ModelReaderNode093_TextureVertex.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CModelReaderNode093_TextureVertices::CModelReaderNode093_TextureVertices(_In_ CMesh * pMesh, _In_ PModelWarnings pWarnings, _In_ PModelReader_TexCoordMapping pTexCoordMapping) + : CModelReaderNode(pWarnings) + { + __NMRASSERT(pMesh); + if (pTexCoordMapping.get() == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + m_pMesh = pMesh; + m_pTexCoordMapping = pTexCoordMapping; + m_nTexCoordIndex = 0; + } + + void CModelReaderNode093_TextureVertices::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse Name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + } + + void CModelReaderNode093_TextureVertices::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + } + + void CModelReaderNode093_TextureVertices::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pChildName); + __NMRASSERT(pXMLReader); + __NMRASSERT(pNameSpace); + + if ((strcmp(pNameSpace, XML_3MF_NAMESPACE_CORESPEC093) == 0) || (strcmp(pNameSpace, "") == 0)) { + if (strcmp(pChildName, XML_3MF_ELEMENT_TEXTUREVERTEX) == 0) + { + PModelReaderNode093_TextureVertex pXMLNode = std::make_shared(m_pWarnings); + pXMLNode->parseXML(pXMLReader); + + // Create Mesh Node + nfFloat fU, fV; + pXMLNode->retrieveTexCoords(fU, fV); + + m_pTexCoordMapping->registerTexCoords(1, m_nTexCoordIndex, 1, fU, fV); + m_nTexCoordIndex++; + + if (m_nTexCoordIndex > XML_3MF_MAXRESOURCEINDEX) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + } + } + } + +} diff --git a/Source/Model/Reader/v093/NMR_ModelReaderNode093_Triangle.cpp b/Source/Model/Reader/v093/NMR_ModelReaderNode093_Triangle.cpp new file mode 100644 index 0000000..a45d0d4 --- /dev/null +++ b/Source/Model/Reader/v093/NMR_ModelReaderNode093_Triangle.cpp @@ -0,0 +1,219 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode093_Triangle.cpp implements the Model Reader Triangle Node +Class. A triangle reader model node is a parser for the triangle node of an +XML Model Stream. + +--*/ + +#include "Model/Reader/v093/NMR_ModelReaderNode093_Triangle.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_StringUtils.h" +#include +#include +#include + +namespace NMR { + + CModelReaderNode093_Triangle::CModelReaderNode093_Triangle(_In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + // Initialise default values + m_nIndex1 = -1; + m_nIndex2 = -1; + m_nIndex3 = -1; + + m_nTextureIndex1 = -1; + m_nTextureIndex2 = -1; + m_nTextureIndex3 = -1; + m_nColorID1 = 0; + m_nColorID2 = 0; + m_nColorID3 = 0; + m_nMaterialID = 0; + m_nTextureID = 0; + } + + void CModelReaderNode093_Triangle::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + } + + void CModelReaderNode093_Triangle::retrieveIndices(_Out_ nfInt32 & nIndex1, _Out_ nfInt32 & nIndex2, _Out_ nfInt32 & nIndex3, nfInt32 nNodeCount) + { + if ((m_nIndex1 < 0) || (m_nIndex2 < 0) || (m_nIndex3 < 0)) + throw CNMRException(NMR_ERROR_INVALIDMODELNODEINDEX); + + if ((m_nIndex1 >= nNodeCount) || (m_nIndex2 >= nNodeCount) || (m_nIndex3 >= nNodeCount)) + throw CNMRException(NMR_ERROR_INVALIDMODELNODEINDEX); + + nIndex1 = m_nIndex1; + nIndex2 = m_nIndex2; + nIndex3 = m_nIndex3; + } + + nfBool CModelReaderNode093_Triangle::retrieveTextureIndices(_Out_ nfInt32 & nIndex1, _Out_ nfInt32 & nIndex2, _Out_ nfInt32 & nIndex3) + { + + nIndex1 = m_nTextureIndex1; + nIndex2 = m_nTextureIndex2; + nIndex3 = m_nTextureIndex3; + + return ((nIndex1 >= 0) && (nIndex2 >= 0) && (nIndex3 >= 0)); + } + + + + void CModelReaderNode093_Triangle::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + nfInt32 nValue; + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TRIANGLE_V1) == 0) { + nValue = fnStringToInt32(pAttributeValue); + if ((nValue >= 0) && (nValue < XML_3MF_MAXRESOURCEINDEX)) + m_nIndex1 = nValue; + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TRIANGLE_V2) == 0) { + nValue = fnStringToInt32(pAttributeValue); + if ((nValue >= 0) && (nValue < XML_3MF_MAXRESOURCEINDEX)) + m_nIndex2 = nValue; + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TRIANGLE_V3) == 0) { + nValue = fnStringToInt32(pAttributeValue); + if ((nValue >= 0) && (nValue < XML_3MF_MAXRESOURCEINDEX)) + m_nIndex3 = nValue; + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TRIANGLE_CV1) == 0) { + nValue = fnStringToInt32(pAttributeValue); + if ((nValue >= 0) && (nValue < XML_3MF_MAXRESOURCEINDEX)) + m_nTextureIndex1 = nValue; + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TRIANGLE_CV2) == 0) { + nValue = fnStringToInt32(pAttributeValue); + if ((nValue >= 0) && (nValue < XML_3MF_MAXRESOURCEINDEX)) + m_nTextureIndex2 = nValue; + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TRIANGLE_CV3) == 0) { + nValue = fnStringToInt32(pAttributeValue); + if ((nValue >= 0) && (nValue < XML_3MF_MAXRESOURCEINDEX)) + m_nTextureIndex3 = nValue; + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TRIANGLE_COLORID) == 0) { + std::string sValue(pAttributeValue); + std::string sSubStr = sValue.substr(0, 4); + if (sSubStr == "tex(") { + if (sValue.length() > 4) { + std::string sTexID = sValue.substr(4, sValue.length() - sSubStr.length() - 1); + nfInt32 nValue = fnStringToInt32(sTexID.c_str()); + if ((nValue < 0) || (nValue >= XML_3MF_MAXRESOURCEINDEX)) + throw CNMRException(NMR_ERROR_INVALIDTEXTUREREFERENCE); + + m_nTextureID = nValue + 1; + + } + else { + throw CNMRException(NMR_ERROR_INVALIDTEXTUREREFERENCE); + } + + } + else { + const nfChar * pCommaValue = strchr(pAttributeValue, ','); + + // Check, if we have a single value + if (pCommaValue == nullptr) { + + nValue = fnStringToInt32(pAttributeValue); + if ((nValue >= 0) && (nValue < XML_3MF_MAXRESOURCEINDEX)) { + m_nColorID1 = nValue + 1; + m_nColorID2 = nValue + 1; + m_nColorID3 = nValue + 1; + } + } + else { + // Check, if we have a color triplet + nfInt32 nColorID1 = -1; + nfInt32 nColorID2 = -1; + nfInt32 nColorID3 = -1; + + fnStringToCommaSeparatedIntegerTriplet(pAttributeValue, nColorID1, nColorID2, nColorID3); + + if ((nColorID1 >= 0) && (nColorID1 < XML_3MF_MAXRESOURCEINDEX)) + m_nColorID1 = nColorID1 + 1; + if ((nColorID2 >= 0) && (nColorID2 < XML_3MF_MAXRESOURCEINDEX)) + m_nColorID2 = nColorID2 + 1; + if ((nColorID3 >= 0) && (nColorID3 < XML_3MF_MAXRESOURCEINDEX)) + m_nColorID3 = nColorID3 + 1; + } + } + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TRIANGLE_MATERIALID) == 0) { + nValue = fnStringToInt32(pAttributeValue); + if ((nValue >= 0) && (nValue < XML_3MF_MAXRESOURCEINDEX)) + m_nMaterialID = nValue + 1; + } + + } + + nfBool CModelReaderNode093_Triangle::retrieveColorIDs(_Out_ nfInt32 & nColorID1, _Out_ nfInt32 & nColorID2, _Out_ nfInt32 & nColorID3) + { + nColorID1 = m_nColorID1; + nColorID2 = m_nColorID2; + nColorID3 = m_nColorID3; + return ((nColorID1 != 0) && (nColorID2 != 0) && (nColorID3 != 0)); + } + + nfInt32 CModelReaderNode093_Triangle::retrieveTextureID() + { + return m_nTextureID; + } + + nfInt32 CModelReaderNode093_Triangle::retrieveMaterialID() + { + return m_nMaterialID; + } + +} diff --git a/Source/Model/Reader/v093/NMR_ModelReaderNode093_Triangles.cpp b/Source/Model/Reader/v093/NMR_ModelReaderNode093_Triangles.cpp new file mode 100644 index 0000000..c498c58 --- /dev/null +++ b/Source/Model/Reader/v093/NMR_ModelReaderNode093_Triangles.cpp @@ -0,0 +1,243 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode093_Triangles.cpp implements the Model Reader Triangles Node +Class. A triangles reader model node is a parser for the triangles node of an +XML Model Stream. + +--*/ + +#include "Model/Reader/v093/NMR_ModelReaderNode093_Triangles.h" +#include "Model/Reader/v093/NMR_ModelReaderNode093_Triangle.h" + +#include "Model/Classes/NMR_ModelTexture2D.h" +#include "Model/Classes/NMR_ModelTexture2DGroup.h" +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CModelReaderNode093_Triangles::CModelReaderNode093_Triangles(_In_ CModel * pModel, _In_ CMesh * pMesh, _In_ PModelReader_ColorMapping pColorMapping, _In_ PModelReader_TexCoordMapping pTexCoordMapping, _In_ PModelBaseMaterialResource pMaterialResource, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + __NMRASSERT(pMesh); + __NMRASSERT(pModel); + __NMRASSERT(pColorMapping.get() != nullptr); + __NMRASSERT(pTexCoordMapping.get() != nullptr); + + m_pModel = pModel; + m_pMesh = pMesh; + + m_pColorMapping = pColorMapping; + m_pTexCoordMapping = pTexCoordMapping; + m_pDefaultMaterialResource = pMaterialResource; + } + + void CModelReaderNode093_Triangles::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse Name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + } + + void CModelReaderNode093_Triangles::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + } + + void CModelReaderNode093_Triangles::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pChildName); + __NMRASSERT(pXMLReader); + __NMRASSERT(pNameSpace); + + if ((strcmp(pNameSpace, XML_3MF_NAMESPACE_CORESPEC093) == 0) || (strcmp(pNameSpace, "") == 0)) { + + if (strcmp(pChildName, XML_3MF_ELEMENT_TRIANGLE) == 0) { + // Parse XML + PModelReaderNode093_Triangle pXMLNode = std::make_shared(m_pWarnings); + pXMLNode->parseXML(pXMLReader); + + // Retrieve node indices + nfInt32 nIndex1, nIndex2, nIndex3; + pXMLNode->retrieveIndices(nIndex1, nIndex2, nIndex3, m_pMesh->getNodeCount()); + + nfInt32 nTextureIndex1, nTextureIndex2, nTextureIndex3; + + // Create face if valid + if ((nIndex1 != nIndex2) && (nIndex1 != nIndex3) && (nIndex2 != nIndex3)) { + MESHNODE * pNode1 = m_pMesh->getNode(nIndex1); + MESHNODE * pNode2 = m_pMesh->getNode(nIndex2); + MESHNODE * pNode3 = m_pMesh->getNode(nIndex3); + MESHFACE * pFace = m_pMesh->addFace(pNode1, pNode2, pNode3); + + nfInt32 nColorID1, nColorID2, nColorID3; + pXMLNode->retrieveColorIDs(nColorID1, nColorID2, nColorID3); + nfInt32 nMaterialID = pXMLNode->retrieveMaterialID(); + nfInt32 nTextureID = pXMLNode->retrieveTextureID(); + + // map colors to textures + if ((nColorID1 == nColorID2) && (nColorID1 == nColorID3)) { + if (m_pColorMapping->hasTextureReference(nColorID1)) { + nTextureID = m_pColorMapping->getTextureReference(nColorID1); + pXMLNode->retrieveTextureIndices(nTextureIndex1, nTextureIndex2, nTextureIndex3); + } + } + + // Create Texture Info + if (nTextureID > 0) { + CMeshInformation_Properties * pProperties = createPropertiesInformation(); + MESHINFORMATION_PROPERTIES* pFaceData = (MESHINFORMATION_PROPERTIES*)pProperties->getFaceData(pFace->m_index); + if (pFaceData) { + + PModelTexture2DResource pTexture2dResource; + + // Convert Texture Coordinates to in memory representation + PPackageResourceID pID = m_pModel->findPackageResourceID(m_pModel->currentPath(), nTextureID); + if (pID.get()) { + pTexture2dResource = std::dynamic_pointer_cast(m_pModel->findResource(pID->getUniqueID())); + } + if (!pTexture2dResource) + throw CNMRException(NMR_ERROR_RESOURCENOTFOUND); + + // find or create ModelTexture2DGroup that points to this texture + CModelTexture2DGroupResource* pTextureGroup = nullptr; + for (nfUint32 iGroup = 0; iGroup < m_pModel->getTexture2DGroupCount(); iGroup++) { + auto p = m_pModel->getTexture2DGroup(iGroup); + if (p->getTexture2D() == pTexture2dResource) { + pTextureGroup = p; + break; + } + } + if (!pTextureGroup) { + // Create Resource + // This is pretty bad way to set a new Model ResourceID, but we do not have read all resources yet... + ModelResourceID nNewModelResourceID = (ModelResourceID)((long)XML_3MF_MAXRESOURCEINDEX - 1 - (long)m_pModel->getTexture2DGroupCount()); + + PModelTexture2DGroupResource pSharedTextureGroup = std::make_shared(nNewModelResourceID, m_pModel, pTexture2dResource); + m_pModel->addResource(pSharedTextureGroup); + pTextureGroup = pSharedTextureGroup.get(); + } + + pFaceData->m_nUniqueResourceID = pTextureGroup->getPackageResourceID()->getUniqueID(); + ModelResourceIndex nResourceIndex; + MODELTEXTURE2DCOORDINATE sUV; + nfFloat fU; + nfFloat fV; + m_pTexCoordMapping->findTexCoords(1, nTextureIndex1, nResourceIndex, fU, fV); + sUV.m_dU = fU; + sUV.m_dV = fV; + pFaceData->m_nPropertyIDs[0] = pTextureGroup->addUVCoordinate(sUV); + + m_pTexCoordMapping->findTexCoords(1, nTextureIndex2, nResourceIndex, fU, fV); + sUV.m_dU = fU; + sUV.m_dV = fV; + pFaceData->m_nPropertyIDs[1] = pTextureGroup->addUVCoordinate(sUV); + + m_pTexCoordMapping->findTexCoords(1, nTextureIndex3, nResourceIndex, fU, fV); + sUV.m_dU = fU; + sUV.m_dV = fV; + pFaceData->m_nPropertyIDs[2] = pTextureGroup->addUVCoordinate(sUV); + } + } + else { + if ((nColorID1 > 0) && (nColorID2 > 0) && (nColorID3 > 0)) { + throw CNMRException(NMR_ERROR_RESOURCENOTFOUND); + } + else { + if (nMaterialID > 0) { + // every v93 material becomes its own v100 base material group resource + PModelBaseMaterialResource pBaseMaterialResource = std::dynamic_pointer_cast(m_pModel->findResource(m_pModel->currentPath(), nMaterialID)); + if (pBaseMaterialResource.get() != nullptr) { + if (!pBaseMaterialResource->hasResourceIndexMap()) + pBaseMaterialResource->buildResourceIndexMap(); + + CMeshInformation_Properties * pProperties = createPropertiesInformation(); + MESHINFORMATION_PROPERTIES* pFaceData = (MESHINFORMATION_PROPERTIES*)pProperties->getFaceData(pFace->m_index); + if (pFaceData) { + pFaceData->m_nUniqueResourceID = pBaseMaterialResource->getPackageResourceID()->getUniqueID(); + pFaceData->m_nPropertyIDs[0] = 1; + pFaceData->m_nPropertyIDs[1] = 1; + pFaceData->m_nPropertyIDs[2] = 1; + } + + MESHINFORMATION_PROPERTIES* pDefaultData = (MESHINFORMATION_PROPERTIES*)pProperties->getDefaultData(); + if (m_pDefaultMaterialResource != nullptr) { + if (!pDefaultData) { + pDefaultData = new MESHINFORMATION_PROPERTIES; + pDefaultData->m_nUniqueResourceID = 0; + pDefaultData->m_nPropertyIDs[0] = 1; + pDefaultData->m_nPropertyIDs[1] = 1; + pDefaultData->m_nPropertyIDs[2] = 1; + pProperties->setDefaultData((MESHINFORMATIONFACEDATA*)pDefaultData); + } + if (pDefaultData->m_nUniqueResourceID == 0) { + pDefaultData->m_nUniqueResourceID = m_pDefaultMaterialResource->getPackageResourceID()->getUniqueID(); + } + } + } + } + + } + } + } + } + } + } + + _Ret_notnull_ CMeshInformation_Properties * CModelReaderNode093_Triangles::createPropertiesInformation() + { + CMeshInformationHandler * pMeshInformationHandler = m_pMesh->createMeshInformationHandler(); + + CMeshInformation * pInformation = pMeshInformationHandler->getInformationByType(0, emiProperties); + CMeshInformation_Properties * pProperties = nullptr; + + if (pInformation) + pProperties = dynamic_cast (pInformation); + + if (!pProperties) { + PMeshInformation_Properties pNewMeshInformation = std::make_shared(m_pMesh->getFaceCount()); + pMeshInformationHandler->addInformation(pNewMeshInformation); + + pProperties = pNewMeshInformation.get(); + } + + return pProperties; + } +} + + + diff --git a/Source/Model/Reader/v093/NMR_ModelReaderNode093_Vertex.cpp b/Source/Model/Reader/v093/NMR_ModelReaderNode093_Vertex.cpp new file mode 100644 index 0000000..a7502b5 --- /dev/null +++ b/Source/Model/Reader/v093/NMR_ModelReaderNode093_Vertex.cpp @@ -0,0 +1,113 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: +NMR_ModelReaderNode093_Vertex.cpp implements the Model Reader Vertex Node Class. +A vertex reader model node is a parser for the vertex node of an XML Model Stream. + +--*/ + +#include "Model/Reader/v093/NMR_ModelReaderNode093_Vertex.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include +#include +#include + +namespace NMR { + + CModelReaderNode093_Vertex::CModelReaderNode093_Vertex(_In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + m_fX = 0.0f; + m_fY = 0.0f; + m_fZ = 0.0f; + m_bHasX = false; + m_bHasY = false; + m_bHasZ = false; + } + + void CModelReaderNode093_Vertex::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + } + + void CModelReaderNode093_Vertex::retrievePosition(_Out_ nfFloat & fX, _Out_ nfFloat & fY, _Out_ nfFloat & fZ) + { + // Model Coordinate is missing + if ((!m_bHasX) || (!m_bHasY) || (!m_bHasZ)) + throw CNMRException(NMR_ERROR_MODELCOORDINATEMISSING); + + fX = m_fX; + fY = m_fY; + fZ = m_fZ; + } + + void CModelReaderNode093_Vertex::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_VERTEX_X) == 0) { + m_fX = strtof(pAttributeValue, nullptr); + if (std::isnan (m_fX)) + throw CNMRException(NMR_ERROR_INVALIDMODELCOORDINATES); + if (fabs (m_fX) > XML_3MF_MAXIMUMCOORDINATEVALUE) + throw CNMRException(NMR_ERROR_INVALIDMODELCOORDINATES); + m_bHasX = true; + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_VERTEX_Y) == 0) { + m_fY = strtof(pAttributeValue, nullptr); + if (std::isnan (m_fY)) + throw CNMRException(NMR_ERROR_INVALIDMODELCOORDINATES); + if (fabs(m_fY) > XML_3MF_MAXIMUMCOORDINATEVALUE) + throw CNMRException(NMR_ERROR_INVALIDMODELCOORDINATES); + m_bHasY = true; + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_VERTEX_Z) == 0) { + m_fZ = strtof(pAttributeValue, nullptr); + if (std::isnan (m_fZ)) + throw CNMRException(NMR_ERROR_INVALIDMODELCOORDINATES); + if (fabs(m_fZ) > XML_3MF_MAXIMUMCOORDINATEVALUE) + throw CNMRException(NMR_ERROR_INVALIDMODELCOORDINATES); + m_bHasZ = true; + } + } + + +} diff --git a/Source/Model/Reader/v093/NMR_ModelReaderNode093_Vertices.cpp b/Source/Model/Reader/v093/NMR_ModelReaderNode093_Vertices.cpp new file mode 100644 index 0000000..1b5d985 --- /dev/null +++ b/Source/Model/Reader/v093/NMR_ModelReaderNode093_Vertices.cpp @@ -0,0 +1,91 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode093_Vertices.cpp defines the Model Reader Vertices Node Class. +A vertices reader model node is a parser for the vertices node of an +XML Model Stream. + +--*/ + +#include "Model/Reader/v093/NMR_ModelReaderNode093_Vertices.h" +#include "Model/Reader/v093/NMR_ModelReaderNode093_Vertex.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CModelReaderNode093_Vertices::CModelReaderNode093_Vertices(_In_ CMesh * pMesh, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + __NMRASSERT(pMesh); + m_pMesh = pMesh; + } + + void CModelReaderNode093_Vertices::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse Name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + } + + void CModelReaderNode093_Vertices::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + } + + void CModelReaderNode093_Vertices::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pChildName); + __NMRASSERT(pXMLReader); + __NMRASSERT(pNameSpace); + + if ((strcmp(pNameSpace, XML_3MF_NAMESPACE_CORESPEC093) == 0) || (strcmp(pNameSpace, "") == 0)) { + + if (strcmp(pChildName, XML_3MF_ELEMENT_VERTEX) == 0) + { + PModelReaderNode093_Vertex pXMLNode = std::make_shared(m_pWarnings); + pXMLNode->parseXML(pXMLReader); + + // Create Mesh Node + nfFloat fX, fY, fZ; + pXMLNode->retrievePosition(fX, fY, fZ); + m_pMesh->addNode(fnVEC3_make(fX, fY, fZ)); + } + } + } + +} diff --git a/Source/Model/Reader/v100/NMR_ModelReaderNode100_BaseMaterial.cpp b/Source/Model/Reader/v100/NMR_ModelReaderNode100_BaseMaterial.cpp new file mode 100644 index 0000000..eb69cec --- /dev/null +++ b/Source/Model/Reader/v100/NMR_ModelReaderNode100_BaseMaterial.cpp @@ -0,0 +1,104 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_BaseMaterial.cpp implements the Model Reader Base Material Node Class. + +--*/ + +#include "Model/Reader/v100/NMR_ModelReaderNode100_BaseMaterial.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_ModelMeshObject.h" + +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CModelReaderNode100_BaseMaterial::CModelReaderNode100_BaseMaterial(_In_ CModel * pModel, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + + m_pModel = pModel; + m_bHasName = false; + m_bHasDisplayColor = false; + m_cDisplayColor = 0xffffffff; + } + + void CModelReaderNode100_BaseMaterial::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + + } + + void CModelReaderNode100_BaseMaterial::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_BASEMATERIAL_NAME) == 0) { + m_sName = pAttributeValue; + m_bHasName = true; + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_BASEMATERIAL_DISPLAYCOLOR) == 0) { + // Convert to color and make a input and range check! + m_bHasDisplayColor = fnStringToSRGBColor(pAttributeValue, m_cDisplayColor); + } + } + + + nfColor CModelReaderNode100_BaseMaterial::getDisplayColor() + { + return m_cDisplayColor; + } + + std::string CModelReaderNode100_BaseMaterial::getMaterialName() + { + return m_sName; + } + + nfBool CModelReaderNode100_BaseMaterial::hasDisplayColor() + { + return m_bHasDisplayColor; + } + + nfBool CModelReaderNode100_BaseMaterial::hasName() + { + return m_bHasName; + } + +} diff --git a/Source/Model/Reader/v100/NMR_ModelReaderNode100_BaseMaterials.cpp b/Source/Model/Reader/v100/NMR_ModelReaderNode100_BaseMaterials.cpp new file mode 100644 index 0000000..3c90498 --- /dev/null +++ b/Source/Model/Reader/v100/NMR_ModelReaderNode100_BaseMaterials.cpp @@ -0,0 +1,112 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_BaseMaterials.cpp implements the Model Reader Base Materials Class. + +--*/ + +#include "Model/Reader/v100/NMR_ModelReaderNode100_BaseMaterials.h" +#include "Model/Reader/v100/NMR_ModelReaderNode100_BaseMaterial.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_ModelMeshObject.h" +#include "Model/Classes/NMR_ModelResource.h" +#include "Model/Classes/NMR_ModelBaseMaterials.h" +#include "Model/Classes/NMR_Model.h" + +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CModelReaderNode100_BaseMaterials::CModelReaderNode100_BaseMaterials(_In_ CModel * pModel, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + // Initialize variables + m_nID = 0; + + m_pModel = pModel; + } + + void CModelReaderNode100_BaseMaterials::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Use parameter and assign to model Object + if (m_nID == 0) + throw CNMRException(NMR_ERROR_MISSINGMODELRESOURCEID); + + // Create Resource + m_pBaseMaterialResource = std::make_shared (m_nID, m_pModel); + + m_pModel->addResource(m_pBaseMaterialResource); + + // Parse Content + parseContent(pXMLReader); + + } + + void CModelReaderNode100_BaseMaterials::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_BASEMATERIALS_ID) == 0) { + if (m_nID != 0) + throw CNMRException(NMR_ERROR_DUPLICATERESOURCEID); + + // Convert to integer and make a input and range check! + m_nID = fnStringToUint32(pAttributeValue); + } + + } + + void CModelReaderNode100_BaseMaterials::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pChildName); + __NMRASSERT(pXMLReader); + __NMRASSERT(pNameSpace); + + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_CORESPEC100) == 0) { + if (strcmp(pChildName, XML_3MF_ELEMENT_BASE) == 0) { + PModelReaderNode100_BaseMaterial pXMLNode = std::make_shared(m_pModel, m_pWarnings); + pXMLNode->parseXML(pXMLReader); + + if (m_pBaseMaterialResource.get() != nullptr) { + m_pBaseMaterialResource->addBaseMaterial(pXMLNode->getMaterialName(), pXMLNode->getDisplayColor()); + } + } + } + } + +} diff --git a/Source/Model/Reader/v100/NMR_ModelReaderNode100_Build.cpp b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Build.cpp new file mode 100644 index 0000000..c7ae2de --- /dev/null +++ b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Build.cpp @@ -0,0 +1,112 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_Build.cpp implements the Model Reader Build Node Class. +A build reader model node is a parser for the build node of an XML Model Stream. + +--*/ + +#include "Model/Reader/v100/NMR_ModelReaderNode100_Build.h" +#include "Model/Reader/v100/NMR_ModelReaderNode100_BuildItem.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CModelReaderNode100_Build::CModelReaderNode100_Build(_In_ CModel * pModel, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + __NMRASSERT(pModel); + m_pModel = pModel; + } + + void CModelReaderNode100_Build::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + + if (!m_UUID.get()) { + if ( (m_pModel->rootPath() == m_pModel->currentPath()) + && (pXMLReader->NamespaceRegistered(XML_3MF_NAMESPACE_PRODUCTIONSPEC)) ) + { + m_pWarnings->addException(CNMRException(NMR_ERROR_MISSINGUUID), mrwMissingMandatoryValue); + } + m_UUID = std::make_shared(); + } + m_pModel->setBuildUUID(m_UUID); + } + + void CModelReaderNode100_Build::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + } + + void CModelReaderNode100_Build::OnNSAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue, _In_z_ const nfChar * pNameSpace) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + __NMRASSERT(pNameSpace); + + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_PRODUCTIONSPEC) == 0) { + if (strcmp(pAttributeName, XML_3MF_PRODUCTION_UUID) == 0) { + if (m_UUID.get()) + throw CNMRException(NMR_ERROR_DUPLICATEUUID); + m_UUID = std::make_shared(pAttributeValue); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ATTRIBUTE), mrwInvalidOptionalValue); + } + } + + void CModelReaderNode100_Build::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pChildName); + __NMRASSERT(pXMLReader); + __NMRASSERT(pNameSpace); + + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_CORESPEC100) == 0) { + if (strcmp(pChildName, XML_3MF_ELEMENT_ITEM) == 0) { + PModelReaderNode pXMLNode = std::make_shared(m_pModel, m_pWarnings); + pXMLNode->parseXML(pXMLReader); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT), mrwInvalidOptionalValue); + } + } + +} diff --git a/Source/Model/Reader/v100/NMR_ModelReaderNode100_BuildItem.cpp b/Source/Model/Reader/v100/NMR_ModelReaderNode100_BuildItem.cpp new file mode 100644 index 0000000..702d974 --- /dev/null +++ b/Source/Model/Reader/v100/NMR_ModelReaderNode100_BuildItem.cpp @@ -0,0 +1,188 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_BuildItem.cpp implements the Model Reader BuildItem Node Class. +A builditem reader model node is a parser for the builditem node of an XML Model Stream. + +--*/ + +#include "Model/Reader/v100/NMR_ModelReaderNode100_BuildItem.h" +#include "Model/Reader/v100/NMR_ModelReaderNode100_MetaDataGroup.h" +#include "Model/Classes/NMR_ModelBuildItem.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_StringUtils.h" + +namespace NMR { + + CModelReaderNode100_BuildItem::CModelReaderNode100_BuildItem(_In_ CModel * pModel, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + __NMRASSERT(pModel); + m_pModel = pModel; + m_ObjectID = 0; + m_bHasID = false; + m_sPartNumber = ""; + + m_hasPath = false; + + m_mTransform = fnMATRIX3_identity(); + } + + void CModelReaderNode100_BuildItem::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + + if (!m_bHasID) + throw CNMRException(NMR_ERROR_MISSINGBUILDITEMOBJECTID); + + CModelObject * pObject; + PPackageResourceID pID; + if (m_hasPath) { + if (m_pModel->currentPath() != m_pModel->rootPath() ) + throw CNMRException(NMR_ERROR_REFERENCESTOODEEP); + pID = m_pModel->findPackageResourceID(m_sPath, m_ObjectID); + } + else + pID = m_pModel->findPackageResourceID(m_pModel->currentPath(), m_ObjectID); + if (!pID) + throw CNMRException(NMR_ERROR_COULDNOTFINDBUILDITEMOBJECT); + + pObject = m_pModel->findObject(pID->getUniqueID()); + if (!pObject) + throw CNMRException(NMR_ERROR_COULDNOTFINDBUILDITEMOBJECT); + + if (MODELOBJECTTYPE_OTHER == pObject->getObjectType()) { + m_pWarnings->addException(CNMRException(NMR_ERROR_BUILDITEMOBJECT_MUSTNOTBE_OTHER), mrwInvalidMandatoryValue); + } + + // Create Build Item + PModelBuildItem pBuildItem = std::make_shared(pObject, m_mTransform, m_pModel->createHandle()); + if (!pBuildItem->isValidForSlices()) { + m_pWarnings->addException(CNMRException(NMR_ERROR_SLICETRANSFORMATIONPLANAR), mrwInvalidMandatoryValue); + } + + if (m_MetaDataGroup.get()) { + pBuildItem->metaDataGroup()->mergeMetaData(m_MetaDataGroup.get()); + } + + m_pModel->addBuildItem(pBuildItem); + + // Set Item Reference + pBuildItem->setPartNumber(m_sPartNumber); + + // Set Production references + if (!m_UUID.get()) { + if (pXMLReader->NamespaceRegistered(XML_3MF_NAMESPACE_PRODUCTIONSPEC)) { + m_pWarnings->addException(CNMRException(NMR_ERROR_MISSINGUUID), mrwMissingMandatoryValue); + } + m_UUID = std::make_shared(); + } + pBuildItem->setUUID(m_UUID); + pBuildItem->setPath(m_sPath); + } + + void CModelReaderNode100_BuildItem::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_ITEM_OBJECTID) == 0) { + if (m_bHasID) + throw CNMRException(NMR_ERROR_DUPLICATEBUILDITEMOBJECTID); + + m_ObjectID = fnStringToUint32(pAttributeValue); + m_bHasID = true; + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_ITEM_TRANSFORM) == 0) { + m_mTransform = fnMATRIX3_fromString(pAttributeValue); + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_ITEM_PARTNUMBER) == 0) { + m_sPartNumber = std::string(pAttributeValue); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ATTRIBUTE), mrwInvalidOptionalValue); + } + + void CModelReaderNode100_BuildItem::OnNSAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue, _In_z_ const nfChar * pNameSpace) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + __NMRASSERT(pNameSpace); + + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_PRODUCTIONSPEC) == 0) { + if (strcmp(pAttributeName, XML_3MF_PRODUCTION_UUID) == 0) { + if (m_UUID.get()) + throw CNMRException(NMR_ERROR_DUPLICATEUUID); + m_UUID = std::make_shared(pAttributeValue); + } + if (strcmp(pAttributeName, XML_3MF_PRODUCTION_PATH) == 0) { + if (m_hasPath) + throw CNMRException(NMR_ERROR_DUPLICATEPATH); + m_sPath = std::string(pAttributeValue); + if (!fnStartsWithPathDelimiter(m_sPath)) { + m_pWarnings->addException(CNMRException(NMR_ERROR_PATH_NOT_ABSOLUTE), mrwInvalidOptionalValue); + } + m_hasPath = true; + } + } + } + + void CModelReaderNode100_BuildItem::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pChildName); + __NMRASSERT(pXMLReader); + __NMRASSERT(pNameSpace); + + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_CORESPEC100) == 0) { + // Read a metadatagroup object + if (strcmp(pChildName, XML_3MF_ELEMENT_METADATAGROUP) == 0) { + PModelReaderNode pXMLNode = std::make_shared(m_pWarnings); + pXMLNode->parseXML(pXMLReader); + + if (m_MetaDataGroup.get()) { + m_pWarnings->addException(CNMRException(NMR_ERROR_DUPLICATEMETADATAGROUP), mrwInvalidOptionalValue); + } + m_MetaDataGroup = dynamic_cast(pXMLNode.get())->getMetaDataGroup(); + } + else { + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT), mrwInvalidOptionalValue); + } + } + } + +} diff --git a/Source/Model/Reader/v100/NMR_ModelReaderNode100_Color.cpp b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Color.cpp new file mode 100644 index 0000000..e9c3c6a --- /dev/null +++ b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Color.cpp @@ -0,0 +1,88 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_Color.cpp implements the Model Reader Color Node Class. + +--*/ + +#include "Model/Reader/v100/NMR_ModelReaderNode100_Color.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_ModelMeshObject.h" + +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CModelReaderNode100_Color::CModelReaderNode100_Color(_In_ CModel * pModel, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + m_pModel = pModel; + m_bHasColor = false; + m_cColor = 0xffffffff; + } + + void CModelReaderNode100_Color::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + + } + + void CModelReaderNode100_Color::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_COLORS_COLOR) == 0) { + // Convert to color and make a input and range check! + m_bHasColor = fnStringToSRGBColor(pAttributeValue, m_cColor); + } + } + + nfColor CModelReaderNode100_Color::getColor() + { + return m_cColor; + } + + nfBool CModelReaderNode100_Color::hasColor() + { + return m_bHasColor; + } + + +} diff --git a/Source/Model/Reader/v100/NMR_ModelReaderNode100_Colors.cpp b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Colors.cpp new file mode 100644 index 0000000..3207bfe --- /dev/null +++ b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Colors.cpp @@ -0,0 +1,115 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_Colors.cpp implements the Model Reader Color Group Class. + +--*/ + +#include "Model/Reader/v100/NMR_ModelReaderNode100_Colors.h" +#include "Model/Reader/v100/NMR_ModelReaderNode100_Color.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_ModelResource.h" +#include "Model/Classes/NMR_Model.h" +#include "Model/Classes/NMR_ModelColorGroup.h" + +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CModelReaderNode100_Colors::CModelReaderNode100_Colors(_In_ CModel * pModel, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + // Initialize variables + m_nID = 0; + m_nColorIndex = 0; + + m_pModel = pModel; + } + + void CModelReaderNode100_Colors::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Use parameter and assign to model Object + if (m_nID == 0) + throw CNMRException(NMR_ERROR_MISSINGMODELRESOURCEID); + + // Create Resource + m_pColorGroup = std::make_shared(m_nID, m_pModel); + + m_pModel->addResource(m_pColorGroup); + + + // Parse Content + parseContent(pXMLReader); + + } + + void CModelReaderNode100_Colors::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_COLORS_ID) == 0) { + if (m_nID != 0) + throw CNMRException(NMR_ERROR_DUPLICATERESOURCEID); + + // Convert to integer and make a input and range check! + m_nID = fnStringToUint32(pAttributeValue); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ATTRIBUTE), mrwInvalidOptionalValue); + } + + void CModelReaderNode100_Colors::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_MATERIALSPEC) == 0) { + if (strcmp(pChildName, XML_3MF_ELEMENT_COLOR) == 0) { + PModelReaderNode100_Color pXMLNode = std::make_shared(m_pModel, m_pWarnings); + pXMLNode->parseXML(pXMLReader); + + if (m_pColorGroup.get() != nullptr) { + m_pColorGroup->addColor(pXMLNode->getColor()); + } + + if (m_nColorIndex > XML_3MF_MAXRESOURCEINDEX) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT), mrwInvalidOptionalValue); + } + } + +} diff --git a/Source/Model/Reader/v100/NMR_ModelReaderNode100_Component.cpp b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Component.cpp new file mode 100644 index 0000000..e7c479a --- /dev/null +++ b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Component.cpp @@ -0,0 +1,147 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_Component.cpp implements the Model Component Reader +Node Class. + +--*/ + +#include "Model/Reader/v100/NMR_ModelReaderNode100_Component.h" + +#include "Model/Classes/NMR_ModelResource.h" +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/Math/NMR_Matrix.h" + +namespace NMR { + + CModelReaderNode100_Component::CModelReaderNode100_Component(_In_ CModel * pModel, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + __NMRASSERT(pModel); + m_pModel = pModel; + m_ObjectID = 0; + m_bHasID = false; + m_sPath = ""; + m_mTransform = fnMATRIX3_identity(); + + m_bHasPath = false; + } + + void CModelReaderNode100_Component::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + } + + void CModelReaderNode100_Component::OnNSAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue, _In_z_ const nfChar * pNameSpace) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + __NMRASSERT(pNameSpace); + + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_PRODUCTIONSPEC) == 0) { + if (strcmp(pAttributeName, XML_3MF_PRODUCTION_PATH) == 0) { + if (m_bHasPath) + throw CNMRException(NMR_ERROR_DUPLICATEPATH); + m_sPath = pAttributeValue; + if (!fnStartsWithPathDelimiter(m_sPath)) { + m_pWarnings->addException(CNMRException(NMR_ERROR_PATH_NOT_ABSOLUTE), mrwInvalidOptionalValue); + } + m_bHasPath = true; + } + else if (strcmp(pAttributeName, XML_3MF_PRODUCTION_UUID) == 0) { + if (m_UUID.get()) + throw CNMRException(NMR_ERROR_DUPLICATEUUID); + m_UUID = std::make_shared(pAttributeValue); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ATTRIBUTE), mrwInvalidOptionalValue); + } + + + } + + void CModelReaderNode100_Component::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_COMPONENT_OBJECTID) == 0) { + if (m_bHasID) + throw CNMRException(NMR_ERROR_DUPLICATECOMPONENTOBJECTID); + + m_ObjectID = fnStringToUint32(pAttributeValue); + m_bHasID = true; + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_COMPONENT_TRANSFORM) == 0) { + m_mTransform = fnMATRIX3_fromString(pAttributeValue); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ATTRIBUTE), mrwInvalidOptionalValue); + } + + + CModelObject * CModelReaderNode100_Component::getObject() + { + if (!m_bHasID) + throw CNMRException(NMR_ERROR_MISSINGMODELOBJECTID); + + PPackageResourceID pRID; + if (m_bHasPath) { + if (m_pModel->currentPath() != m_pModel->rootPath()) + throw CNMRException(NMR_ERROR_REFERENCESTOODEEP); + pRID = m_pModel->findPackageResourceID(m_sPath, m_ObjectID); + } + else { + pRID = m_pModel->findPackageResourceID(m_pModel->currentPath(), m_ObjectID); + } + if (pRID.get()) + return m_pModel->findObject(pRID->getUniqueID()); + return nullptr; + } + + NMATRIX3 CModelReaderNode100_Component::getTransform() + { + return m_mTransform; + } + + PUUID CModelReaderNode100_Component::uuid() { + return m_UUID; + } + + +} diff --git a/Source/Model/Reader/v100/NMR_ModelReaderNode100_Components.cpp b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Components.cpp new file mode 100644 index 0000000..9ea5177 --- /dev/null +++ b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Components.cpp @@ -0,0 +1,109 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_Components.cpp implements the Model Components Reader +Node Class. + +--*/ + +#include "Model/Reader/v100/NMR_ModelReaderNode100_Components.h" +#include "Model/Reader/v100/NMR_ModelReaderNode100_Component.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CModelReaderNode100_Components::CModelReaderNode100_Components(_In_ CModelComponentsObject * pComponentsObject, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + __NMRASSERT(pComponentsObject); + m_pComponentsObject = pComponentsObject; + } + + void CModelReaderNode100_Components::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + } + + void CModelReaderNode100_Components::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + } + + void CModelReaderNode100_Components::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pChildName); + __NMRASSERT(pXMLReader); + __NMRASSERT(pNameSpace); + + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_CORESPEC100) == 0) { + if (strcmp(pChildName, XML_3MF_ELEMENT_COMPONENT) == 0) { + // Read Component + PModelReaderNode100_Component pXMLNode = std::make_shared(m_pComponentsObject->getModel(), m_pWarnings); + pXMLNode->parseXML(pXMLReader); + + // Retrieve object and transform + CModelObject * pObject = pXMLNode->getObject(); + NMATRIX3 mTransform = pXMLNode->getTransform(); + + // Check, if we have an associated object + if (!pObject) + throw CNMRException(NMR_ERROR_COULDNOTFINDCOMPONENTOBJECT); + + // Create component + PModelComponent pComponent = std::make_shared(pObject, mTransform); + + // Set Production references + PUUID uuid = pXMLNode->uuid(); + if (!uuid.get()) { + if (pXMLReader->NamespaceRegistered(XML_3MF_NAMESPACE_PRODUCTIONSPEC)) { + m_pWarnings->addException(CNMRException(NMR_ERROR_MISSINGUUID), mrwMissingMandatoryValue); + } + uuid = std::make_shared(); + } + pComponent->setUUID(uuid); + + m_pComponentsObject->addComponent(pComponent); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT), mrwInvalidOptionalValue); + } + } + +} diff --git a/Source/Model/Reader/v100/NMR_ModelReaderNode100_Composite.cpp b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Composite.cpp new file mode 100644 index 0000000..a63e385 --- /dev/null +++ b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Composite.cpp @@ -0,0 +1,98 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_Color.cpp implements the Model Reader Color Node Class. + +--*/ + +#include "Model/Reader/v100/NMR_ModelReaderNode100_Composite.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_ModelMeshObject.h" + +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CModelReaderNode100_Composite::CModelReaderNode100_Composite(_In_ CModel * pModel, _In_ PModelWarnings pWarnings, + _In_z_ const std::vector& baseMaterialPropertyIds) + : CModelReaderNode(pWarnings), m_vctBaseMaterialPropertyIds(baseMaterialPropertyIds) + { + m_pModel = pModel; + } + + void CModelReaderNode100_Composite::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + + } + + PModelComposite CModelReaderNode100_Composite::getComposite() + { + return m_pModelComposite; + } + + void CModelReaderNode100_Composite::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_COMPOSITE_VALUES) == 0) { + m_pModelComposite = std::make_shared(); + std::vector vctMixingRatios = fnVctType_fromString(pAttributeValue); + for (size_t i = 0; i < m_vctBaseMaterialPropertyIds.size(); i++) { + MODELCOMPOSITECONSTITUENT constituent; + constituent.m_nPropertyID = m_vctBaseMaterialPropertyIds[i]; + if (i < vctMixingRatios.size()) { + constituent.m_dMixingRatio = vctMixingRatios[i]; + } + else { + constituent.m_dMixingRatio = 0; + } + m_pModelComposite->push_back(constituent); + } + if (vctMixingRatios.size() < m_vctBaseMaterialPropertyIds.size()) + m_pWarnings->addException(CNMRException(NMR_ERROR_MIXINGRATIO_MISSING), mrwInvalidOptionalValue); + else if (vctMixingRatios.size() > m_vctBaseMaterialPropertyIds.size()) { + m_pWarnings->addException(CNMRException(NMR_ERROR_MIXINGRATIO_TOOMANY), mrwInvalidOptionalValue); + } + } else { + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ATTRIBUTE), mrwInvalidOptionalValue); + } + } + +} diff --git a/Source/Model/Reader/v100/NMR_ModelReaderNode100_CompositeMaterials.cpp b/Source/Model/Reader/v100/NMR_ModelReaderNode100_CompositeMaterials.cpp new file mode 100644 index 0000000..70f1141 --- /dev/null +++ b/Source/Model/Reader/v100/NMR_ModelReaderNode100_CompositeMaterials.cpp @@ -0,0 +1,156 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_CompositeMaterials.cpp implements the Model Reader Composite Materials Class. + +--*/ + +#include "Model/Reader/v100/NMR_ModelReaderNode100_CompositeMaterials.h" +#include "Model/Reader/v100/NMR_ModelReaderNode100_Composite.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_ModelMeshObject.h" +#include "Model/Classes/NMR_ModelResource.h" +#include "Model/Classes/NMR_Model.h" + +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CModelReaderNode100_CompositeMaterials::CModelReaderNode100_CompositeMaterials(_In_ CModel * pModel, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + // Initialize variables + m_nID = 0; + m_nBaseMaterialID = 0; + + m_pModel = pModel; + } + + void CModelReaderNode100_CompositeMaterials::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Use parameter and assign to model Object + if (m_nID == 0) + throw CNMRException(NMR_ERROR_MISSINGMODELRESOURCEID); + + if (m_nBaseMaterialID == 0) + throw CNMRException(NMR_ERROR_MISSINGMODELRESOURCEID); + + PPackageResourceID pID = m_pModel->findPackageResourceID(m_pModel->currentPath(), m_nBaseMaterialID); + if (!pID) + throw CNMRException(NMR_ERROR_INVALIDMODELRESOURCE); + + PModelBaseMaterialResource pBaseMaterial = m_pModel->findBaseMaterial(pID); + + // Create Resource + m_pCompositeMaterials = std::make_shared(m_nID, m_pModel, pBaseMaterial); + + if (m_pMatIndices) { + pBaseMaterial->buildResourceIndexMap(); + + if (m_pMatIndices->size() > XML_3MF_MAXRESOURCECOUNT) + throw CNMRException(NMR_ERROR_INVALIDBUFFERSIZE); + + + m_vctMaterialPropertyIDs.resize(m_pMatIndices->size()); + for (size_t i = 0; i < m_vctMaterialPropertyIDs.size(); i++) { + ModelPropertyID nPropertyID; + if (!pBaseMaterial->mapResourceIndexToPropertyID((ModelResourceIndex)i, nPropertyID)) { + throw CNMRException(NMR_ERROR_INVALIDBASEMATERIAL); + } + m_vctMaterialPropertyIDs[i] = nPropertyID; + } + } + + m_pModel->addResource(m_pCompositeMaterials); + + // Parse Content + parseContent(pXMLReader); + + } + + void CModelReaderNode100_CompositeMaterials::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_COMPOSITEMATERIALS_ID) == 0) { + if (m_nID != 0) + throw CNMRException(NMR_ERROR_DUPLICATERESOURCEID); + + // Convert to integer and make a input and range check! + m_nID = fnStringToUint32(pAttributeValue); + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_COMPOSITEMATERIALS_MATID) == 0) { + if (m_nBaseMaterialID != 0) + throw CNMRException(NMR_ERROR_DUPLICATERESOURCEID); + + // Convert to integer and make a input and range check! + ModelResourceID nID = fnStringToUint32(pAttributeValue); + if (nID == 0) + m_pWarnings->addException(CNMRException(NMR_ERROR_INVALIDMODELRESOURCE), mrwInvalidMandatoryValue); + + m_nBaseMaterialID = nID; + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_COMPOSITEMATERIALS_MATINDICES) == 0) { + if (m_pMatIndices) { + throw CNMRException(NMR_ERROR_DUPLICATE_MATINDICES_ATTRIBUTE); + } + + m_pMatIndices = std::make_shared>( fnVctType_fromString(std::string(pAttributeValue)) ) ; + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ATTRIBUTE), mrwInvalidOptionalValue); + } + + + void CModelReaderNode100_CompositeMaterials::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_MATERIALSPEC) == 0) { + if (strcmp(pChildName, XML_3MF_ELEMENT_COMPOSITE) == 0) { + PModelReaderNode100_Composite pXMLNode = std::make_shared(m_pModel, m_pWarnings, m_vctMaterialPropertyIDs); + pXMLNode->parseXML(pXMLReader); + + PModelComposite pComposite = pXMLNode->getComposite(); + + m_pCompositeMaterials->addComposite(pComposite); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT), mrwInvalidOptionalValue); + } + } + +} diff --git a/Source/Model/Reader/v100/NMR_ModelReaderNode100_Mesh.cpp b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Mesh.cpp new file mode 100644 index 0000000..16d2fcc --- /dev/null +++ b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Mesh.cpp @@ -0,0 +1,155 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_Mesh.cpp implements the Model Reader Mesh Node Class. +A mesh reader model node is a parser for the mesh node of an XML Model Stream. + +--*/ + +#include "Model/Reader/v100/NMR_ModelReaderNode100_Mesh.h" +#include "Model/Reader/v100/NMR_ModelReaderNode100_Vertices.h" +#include "Model/Reader/v100/NMR_ModelReaderNode100_Triangles.h" +#include "Model/Reader/BeamLattice1702/NMR_ModelReaderNode_BeamLattice1702_BeamLattice.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CModelReaderNode100_Mesh::CModelReaderNode100_Mesh(_In_ CModel * pModel, _In_ CMesh * pMesh, _In_ PModelWarnings pWarnings, + _In_ PProgressMonitor pProgressMonitor, _In_ PPackageResourceID pObjectLevelPropertyID, _In_ ModelResourceIndex nDefaultPropertyIndex) + : CModelReaderNode(pWarnings, pProgressMonitor) + { + __NMRASSERT(pMesh); + __NMRASSERT(pModel); + + m_pObjectLevelPropertyID = pObjectLevelPropertyID; + m_nObjectLevelPropertyIndex = nDefaultPropertyIndex; + + m_pMesh = pMesh; + m_pModel = pModel; + + m_bHasClippingMeshID = false; + m_nClippingMeshID = 0; + m_eClipMode = eModelBeamLatticeClipMode::MODELBEAMLATTICECLIPMODE_NONE; + m_bHasRepresentationMeshID = false; + m_nRepresentationMeshID = 0; + } + + void CModelReaderNode100_Mesh::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + } + + void CModelReaderNode100_Mesh::retrieveClippingInfo(_Out_ eModelBeamLatticeClipMode &eClipMode, _Out_ nfBool & bHasClippingMode, _Out_ ModelResourceID & nClippingMeshID) + { + bHasClippingMode = m_bHasClippingMeshID; + nClippingMeshID = m_nClippingMeshID; + eClipMode = m_eClipMode; + } + + void CModelReaderNode100_Mesh::retrieveRepresentationInfo(_Out_ nfBool & bHasRepresentation, _Out_ ModelResourceID & nRepresentationMeshID) + { + bHasRepresentation = m_bHasRepresentationMeshID; + nRepresentationMeshID = m_nRepresentationMeshID; + } + + void CModelReaderNode100_Mesh::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + } + + void CModelReaderNode100_Mesh::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pChildName); + __NMRASSERT(pXMLReader); + __NMRASSERT(pNameSpace); + + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_CORESPEC100) == 0) { + + if (strcmp(pChildName, XML_3MF_ELEMENT_VERTICES) == 0) + { + if (m_pMesh->getNodeCount() % PROGRESS_READUPDATE == PROGRESS_READUPDATE - 1) { + m_pProgressMonitor->SetProgressIdentifier(ProgressIdentifier::PROGRESS_READMESH); + m_pProgressMonitor->ReportProgressAndQueryCancelled(true); + } + PModelReaderNode pXMLNode = std::make_shared(m_pMesh, m_pWarnings); + pXMLNode->parseXML(pXMLReader); + } + else if (strcmp(pChildName, XML_3MF_ELEMENT_TRIANGLES) == 0) + { + if (m_pMesh->getFaceCount() % PROGRESS_READUPDATE == PROGRESS_READUPDATE - 1) { + m_pProgressMonitor->SetProgressIdentifier(ProgressIdentifier::PROGRESS_READMESH); + m_pProgressMonitor->ReportProgressAndQueryCancelled(true); + } + PModelReaderNode100_Triangles pXMLNode = std::make_shared(m_pModel, m_pMesh, m_pWarnings, + m_pObjectLevelPropertyID, m_nObjectLevelPropertyIndex); + pXMLNode->parseXML(pXMLReader); + if (m_pObjectLevelPropertyID && m_pObjectLevelPropertyID->getPackageModelPath() == 0) { + // warn, if object does not have an object-level property, but a triangle has one + if (pXMLNode->getUsedPropertyID() != 0) { + m_pWarnings->addException(CNMRException(NMR_ERROR_MISSINGOBJECTLEVELPID), mrwMissingMandatoryValue); + } + // Try and define an object-level property as some PropertyID used by a triangle in the meshobject + ModelResourceID nObjectLevelPropertyID = pXMLNode->getUsedPropertyID(); + m_pObjectLevelPropertyID = m_pModel->findPackageResourceID(m_pModel->currentPath(), nObjectLevelPropertyID); + m_nObjectLevelPropertyIndex = 0; + } + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT), mrwInvalidOptionalValue); + } + + + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_BEAMLATTICESPEC) == 0) { + if (strcmp(pChildName, XML_3MF_ELEMENT_BEAMLATTICE) == 0) + { + PModelReaderNode_BeamLattice1702_BeamLattice pXMLNode = std::make_shared(m_pModel, m_pMesh, m_pWarnings); + pXMLNode->parseXML(pXMLReader); + + pXMLNode->retrieveClippingInfo(m_eClipMode, m_bHasClippingMeshID, m_nClippingMeshID); + pXMLNode->retrieveRepresentationInfo(m_bHasRepresentationMeshID, m_nRepresentationMeshID); + pXMLNode->validateBallOptions(m_pWarnings); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT), mrwInvalidOptionalValue); + } + + } + +} diff --git a/Source/Model/Reader/v100/NMR_ModelReaderNode100_MetaData.cpp b/Source/Model/Reader/v100/NMR_ModelReaderNode100_MetaData.cpp new file mode 100644 index 0000000..8916afb --- /dev/null +++ b/Source/Model/Reader/v100/NMR_ModelReaderNode100_MetaData.cpp @@ -0,0 +1,105 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_MetaData.cpp implements the Model Reader MetaData +Node Class. A metadata reader model node is a parser for the triangle node +of an XML Model Stream. + +--*/ + +#include "Model/Reader/v100/NMR_ModelReaderNode100_MetaData.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CModelReaderNode100_MetaData::CModelReaderNode100_MetaData(_In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + m_sKey = ""; + m_sValue = ""; + m_bPreserve = true; + m_sType = "xs:string"; + } + + void CModelReaderNode100_MetaData::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + } + + void CModelReaderNode100_MetaData::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_METADATA_NAME) == 0) { + m_sKey = std::string(pAttributeValue); + } else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_METADATA_PRESERVE) == 0) { + m_bPreserve = !(std::string(pAttributeValue) == "0"); + } else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_METADATA_TYPE) == 0) { + m_sType = std::string(pAttributeValue); + } + + } + + void CModelReaderNode100_MetaData::OnText(_In_z_ const nfChar * pText, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pText); + m_sValue += std::string(pText); + } + + std::string CModelReaderNode100_MetaData::getKey() + { + return m_sKey; + } + + std::string CModelReaderNode100_MetaData::getValue() + { + return m_sValue; + } + + std::string CModelReaderNode100_MetaData::getType() + { + return m_sType; + } + + nfBool CModelReaderNode100_MetaData::getPreserve() + { + return m_bPreserve; + } + +} diff --git a/Source/Model/Reader/v100/NMR_ModelReaderNode100_MetaDataGroup.cpp b/Source/Model/Reader/v100/NMR_ModelReaderNode100_MetaDataGroup.cpp new file mode 100644 index 0000000..4f26023 --- /dev/null +++ b/Source/Model/Reader/v100/NMR_ModelReaderNode100_MetaDataGroup.cpp @@ -0,0 +1,124 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_MetaDataGroup.cpp implements the Model Reader MetaDataGroup +Node Class. A metadatagroup reader node is a parser for the metadatagroup node +of an XML Model Stream. + +--*/ + +#include "Model/Reader/v100/NMR_ModelReaderNode100_MetaDataGroup.h" + +#include "Model/Reader/v100/NMR_ModelReaderNode100_MetaData.h" +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" + +namespace NMR { + + CModelReaderNode100_MetaDataGroup::CModelReaderNode100_MetaDataGroup(_In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + m_MetaDataGroup = std::make_shared(); + } + + void CModelReaderNode100_MetaDataGroup::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + } + + void CModelReaderNode100_MetaDataGroup::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_CORESPEC100) == 0) { + + if (strcmp(pChildName, XML_3MF_ELEMENT_METADATA) == 0) { + PModelReaderNode100_MetaData pXMLNode = std::make_shared(m_pWarnings); + pXMLNode->parseXML(pXMLReader); + + std::string sKey = pXMLNode->getKey(); + std::string sValue = pXMLNode->getValue(); + std::string sType = pXMLNode->getType(); + nfBool bPreserve = pXMLNode->getPreserve(); + + if (!sKey.empty()) { + if (m_MetaDataGroup->hasMetaData(sKey)) { + m_pWarnings->addWarning(NMR_ERROR_DUPLICATEMETADATA, mrwInvalidOptionalValue); + } + else { + std::string sNameSpace, sName; + decomposeKeyIntoNamespaceAndName(sKey, sNameSpace, sName); + if (!sNameSpace.empty()) { + std::string sNameSpaceURI; + if (!pXMLReader->GetNamespaceURI(sNameSpace, sNameSpaceURI)) { + m_pWarnings->addException(CNMRException(NMR_ERROR_METADATA_COULDNOTGETNAMESPACE), mrwInvalidOptionalValue); + sNameSpaceURI = sNameSpace; + } + m_MetaDataGroup->addMetaData(sNameSpaceURI, sName, sValue, sType, bPreserve); + } + else { + // default namespace + if (CModelMetaData::isValidNamespaceAndName("", sName)) { + m_MetaDataGroup->addMetaData("", sName, sValue, sType, bPreserve); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_UNKNOWNMETADATA), mrwInvalidOptionalValue); + } + } + } + else { + m_pWarnings->addWarning(NMR_ERROR_INVALIDMETADATA, mrwInvalidOptionalValue); + } + } + } + } + + void CModelReaderNode100_MetaDataGroup::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + } + + void CModelReaderNode100_MetaDataGroup::OnText(_In_z_ const nfChar * pText, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pText); + } + + PModelMetaDataGroup CModelReaderNode100_MetaDataGroup::getMetaDataGroup() + { + return m_MetaDataGroup; + } + +} diff --git a/Source/Model/Reader/v100/NMR_ModelReaderNode100_Multi.cpp b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Multi.cpp new file mode 100644 index 0000000..a708986 --- /dev/null +++ b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Multi.cpp @@ -0,0 +1,85 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_Multi.cpp implements the Model Reader Multi Node Class. + +--*/ + +#include "Model/Reader/v100/NMR_ModelReaderNode100_Multi.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_ModelMultiPropertyGroup.h" + +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CModelReaderNode100_Multi::CModelReaderNode100_Multi(_In_ CModel * pModel, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + m_pModel = pModel; + m_bHasPIndices = false; + } + + void CModelReaderNode100_Multi::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + + if (!m_bHasPIndices) { + m_pWarnings->addException(CNMRException(NMR_ERROR_MULTIPROPERTIES_INVALID_MULTI_ELEMENT), mrwInvalidMandatoryValue); + } + } + + std::vector& CModelReaderNode100_Multi::getPIndices() + { + return m_vctPIndices; + } + + void CModelReaderNode100_Multi::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_MULTI_PINDICES) == 0) { + m_bHasPIndices = true; + m_vctPIndices = fnVctType_fromString(pAttributeValue); + } else { + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ATTRIBUTE), mrwInvalidOptionalValue); + } + } + +} diff --git a/Source/Model/Reader/v100/NMR_ModelReaderNode100_MultiProperties.cpp b/Source/Model/Reader/v100/NMR_ModelReaderNode100_MultiProperties.cpp new file mode 100644 index 0000000..1b2fc75 --- /dev/null +++ b/Source/Model/Reader/v100/NMR_ModelReaderNode100_MultiProperties.cpp @@ -0,0 +1,193 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_MultiProperties.cpp implements the Model Reader MultiProperties Class. + +--*/ + +#include "Model/Reader/v100/NMR_ModelReaderNode100_MultiProperties.h" +#include "Model/Reader/v100/NMR_ModelReaderNode100_Multi.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_ModelResource.h" +#include "Model/Classes/NMR_Model.h" + +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CModelReaderNode100_MultiProperties::CModelReaderNode100_MultiProperties(_In_ CModel * pModel, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + // Initialize variables + m_nID = 0; + + m_pModel = pModel; + } + + void CModelReaderNode100_MultiProperties::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Use parameter and assign to model Object + if (m_nID == 0) + throw CNMRException(NMR_ERROR_MISSINGMODELRESOURCEID); + + std::vector vctLayers; + + if (m_pPIDs) { + if (!m_pBlendMethods) { + m_pBlendMethods = std::make_shared>(); + m_pBlendMethods->resize(m_pPIDs->size() - 1); + for (size_t i = 0; i < m_pBlendMethods->size(); i++) { + (*m_pBlendMethods)[i] = eModelBlendMethod::MODELBLENDMETHOD_MIX; + } + } + + if (m_pBlendMethods->size() != m_pPIDs->size() - 1) { + m_pWarnings->addException(CNMRException(NMR_ERROR_MULTIPROPERTIES_DIFFERNT_NUMBER_OF_BLENDMETHODS_AND_PIDS), mrwInvalidMandatoryValue); + } + + for (size_t i = 0; i < m_pPIDs->size(); i++) { + PPackageResourceID pID = m_pModel->findPackageResourceID(m_pModel->currentPath(), (*m_pPIDs)[i]); + if (!pID) + throw CNMRException(NMR_ERROR_RESOURCENOTFOUND); + + eModelBlendMethod method = eModelBlendMethod::MODELBLENDMETHOD_MIX; + if (m_pBlendMethods && (i > 0) && (i < m_pBlendMethods->size() + 1 )) { + method = (*m_pBlendMethods)[i-1]; + } + vctLayers.push_back(MODELMULTIPROPERTYLAYER({ pID->getUniqueID() , method })); + } + } + else { + { + m_pWarnings->addException(CNMRException(NMR_ERROR_MULTIPROPERTIES_MISSING_PIDS), mrwInvalidMandatoryValue); + } + } + + m_pMultiPropertyGroup = std::make_shared(m_nID, m_pModel); + m_pModel->addResource(m_pMultiPropertyGroup); + + for (auto layer : vctLayers) { + PModelResource pResource = m_pModel->findResource(layer.m_nUniqueResourceID); + if (!pResource) { + throw CNMRException(NMR_ERROR_RESOURCENOTFOUND); + } + pResource->buildResourceIndexMap(); + + m_pMultiPropertyGroup->addLayer(layer); + } + + // Parse Content + parseContent(pXMLReader); + } + + void CModelReaderNode100_MultiProperties::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_MULTIPROPERTIES_ID) == 0) { + if (m_nID != 0) + throw CNMRException(NMR_ERROR_DUPLICATERESOURCEID); + + // Convert to integer and make a input and range check! + m_nID = fnStringToUint32(pAttributeValue); + } else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_MULTIPROPERTIES_PIDS) == 0) { + if (m_pPIDs) + throw CNMRException(NMR_ERROR_DUPLICATE_PIDS); + + m_pPIDs = std::make_shared>(fnVctType_fromString(std::string(pAttributeValue))); + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_MULTIPROPERTIES_BLENDMETHODS) == 0) { + if (m_pBlendMethods) + throw CNMRException(NMR_ERROR_DUPLICATE_BLENDMETHOS); + + std::vector vctBlendMethodStrings = fnVctType_fromString(std::string(pAttributeValue)); + + m_pBlendMethods = std::make_shared>(); + m_pBlendMethods->reserve(vctBlendMethodStrings.size()); + for (std::string blendMethodString : vctBlendMethodStrings) { + eModelBlendMethod method = MODELBLENDMETHOD_MIX; + try { + method = CModelMultiPropertyGroupResource::stringToBlendMethod(blendMethodString); + } catch (CNMRException e) { + m_pWarnings->addException(e, mrwInvalidMandatoryValue); + } + m_pBlendMethods->push_back(method); + } + + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ATTRIBUTE), mrwInvalidOptionalValue); + } + + + void CModelReaderNode100_MultiProperties::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_MATERIALSPEC) == 0) { + if (strcmp(pChildName, XML_3MF_ELEMENT_MULTI) == 0) { + PModelReaderNode100_Multi pXMLNode = std::make_shared(m_pModel, m_pWarnings); + pXMLNode->parseXML(pXMLReader); + + std::vector vctPIndices = pXMLNode->getPIndices(); + + nfUint32 nLayers = m_pMultiPropertyGroup->getLayerCount(); + + while (vctPIndices.size() < nLayers) { + vctPIndices.push_back(0); + } + PModelMultiProperty pMultiProperty = std::make_shared(nLayers); + + for (nfUint32 iLayer=0; iLayer < nLayers; iLayer++) { + PModelResource pResource = m_pModel->findResource(m_pMultiPropertyGroup->getLayer(iLayer).m_nUniqueResourceID); + if (!pResource) { + throw CNMRException(NMR_ERROR_RESOURCENOTFOUND); + } + ModelPropertyID nPropertyID; + if (!pResource->mapResourceIndexToPropertyID(vctPIndices[iLayer], nPropertyID)) { + throw CNMRException(NMR_ERROR_INVALID_RESOURCE_INDEX); + } + (*pMultiProperty)[iLayer] = nPropertyID; + } + + m_pMultiPropertyGroup->addMultiProperty(pMultiProperty); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT), mrwInvalidOptionalValue); + } + } + +} diff --git a/Source/Model/Reader/v100/NMR_ModelReaderNode100_Object.cpp b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Object.cpp new file mode 100644 index 0000000..504e42d --- /dev/null +++ b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Object.cpp @@ -0,0 +1,426 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_Object.cpp implements the Model Reader Object Node Class. +A object reader model node is a parser for the object node of an XML Model +Stream. + +--*/ + +#include "Model/Reader/v100/NMR_ModelReaderNode100_Object.h" +#include "Model/Reader/v100/NMR_ModelReaderNode100_Mesh.h" +#include "Model/Reader/v100/NMR_ModelReaderNode100_MetaDataGroup.h" +#include "Model/Reader/v100/NMR_ModelReaderNode100_Components.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_ModelMeshObject.h" +#include "Model/Classes/NMR_ModelAttachment.h" + +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/MeshInformation/NMR_MeshInformation_Properties.h" + +namespace NMR { + + CModelReaderNode100_Object::CModelReaderNode100_Object(_In_ CModel * pModel, _In_ PModelWarnings pWarnings, _In_ PProgressMonitor pProgressMonitor) + : CModelReaderNode(pWarnings, pProgressMonitor) + { + // Initialize variables + m_nID = 0; + m_sType = ""; + m_bHasType = false; + + m_pModel = pModel; + m_pObject = NULL; + m_sThumbnailPath = ""; + m_sPartNumber = ""; + m_sName = ""; + + m_bHasThumbnail = false; + m_bHasDefaultPropertyID = false; + m_bHasDefaultPropertyIndex = false; + m_nObjectLevelPropertyModelID = 0; + m_nObjectLevelPropertyIndex = 0; + + m_nSliceStackId = 0; + m_eSlicesMeshResolution = MODELSLICESMESHRESOLUTION_FULL; + m_bHasMeshResolution = false; + } + + void CModelReaderNode100_Object::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Use parameter and assign to model Object + if (m_nID == 0) + throw CNMRException(NMR_ERROR_MISSINGMODELOBJECTID); + + if (m_nObjectLevelPropertyModelID != 0) { + m_pObjectLevelPropertyID = m_pModel->findPackageResourceID(m_pModel->currentPath(), m_nObjectLevelPropertyModelID); + } + + // Parse Content + parseContent(pXMLReader); + + // Check, if we have created an object + if (!m_pObject.get()) + throw CNMRException(NMR_ERROR_MISSINGOBJECTCONTENT); + + // Set Object Parameters + m_pObject->setName(m_sName); + m_pObject->setPartNumber(m_sPartNumber); + + if (m_MetaDataGroup.get()) { + m_pObject->metaDataGroup()->mergeMetaData(m_MetaDataGroup.get()); + } + + if (m_bHasThumbnail) + { + PModelAttachment pModelAttachment = m_pModel->findModelAttachment(m_sThumbnailPath); + if (pModelAttachment) { + if (!((pModelAttachment->getRelationShipType() == PACKAGE_TEXTURE_RELATIONSHIP_TYPE) || (pModelAttachment->getRelationShipType() == PACKAGE_THUMBNAIL_RELATIONSHIP_TYPE))) + m_pWarnings->addException(CNMRException(NMR_ERROR_NOTEXTURESTREAM), mrwInvalidMandatoryValue); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NOTEXTURESTREAM), mrwInvalidMandatoryValue); + + m_pObject->setThumbnailAttachment(pModelAttachment, false); + } + + // Set Production references + if (!m_UUID.get()) { + if (pXMLReader->NamespaceRegistered(XML_3MF_NAMESPACE_PRODUCTIONSPEC)) { + m_pWarnings->addException(CNMRException(NMR_ERROR_MISSINGUUID), mrwMissingMandatoryValue); + } + m_UUID = std::make_shared(); + } + m_pObject->setUUID(m_UUID); + } + + void CModelReaderNode100_Object::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_OBJECT_ID) == 0) { + if (m_nID != 0) + throw CNMRException(NMR_ERROR_DUPLICATEOBJECTID); + + // Convert to integer and make a input and range check! + m_nID = fnStringToUint32(pAttributeValue); + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_OBJECT_TYPE) == 0) { + if (m_bHasType) + throw CNMRException(NMR_ERROR_DUPLICATEOBJECTTYPE); + + // Convert to integer and make a input and range check! + m_sType = pAttributeValue; + m_bHasType = true; + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_OBJECT_THUMBNAIL) == 0) { + if (m_bHasThumbnail) + throw CNMRException(NMR_ERROR_DUPLICATEOBJECTTHUMBNAIL); + m_sThumbnailPath = pAttributeValue; + m_bHasThumbnail = true; + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_OBJECT_NAME) == 0) { + m_sName = pAttributeValue; + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_OBJECT_PARTNUMBER) == 0) { + m_sPartNumber = pAttributeValue; + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_OBJECT_PID) == 0) { + if (m_bHasDefaultPropertyID) + throw CNMRException(NMR_ERROR_DUPLICATEPID); + m_bHasDefaultPropertyID = true; + m_nObjectLevelPropertyModelID = fnStringToUint32(pAttributeValue); + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_OBJECT_PINDEX) == 0) { + if (m_bHasDefaultPropertyIndex) + throw CNMRException(NMR_ERROR_DUPLICATEPINDEX); + m_bHasDefaultPropertyIndex = true; + m_nObjectLevelPropertyIndex = fnStringToUint32(pAttributeValue); + } + + } + + void CModelReaderNode100_Object::OnNSAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue, _In_z_ const nfChar * pNameSpace) { + __NMRASSERT(pAttributeName); + __NMRASSERT(pNameSpace); + __NMRASSERT(pAttributeValue); + + if (strcmp(XML_3MF_NAMESPACE_SLICESPEC, pNameSpace) == 0) { + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_OBJECT_SLICESTACKID) == 0) { + if (m_nSliceStackId != 0) + m_pWarnings->addException(CNMRException(NMR_ERROR_DUPLICATE_SLICESTACKID), eModelWarningLevel::mrwInvalidOptionalValue); + m_nSliceStackId = fnStringToUint32(pAttributeValue); + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_OBJECT_MESHRESOLUTION) == 0) { + if (m_bHasMeshResolution) + m_pWarnings->addException(CNMRException(NMR_ERROR_DUPLICATE_MESHRESOLUTION), eModelWarningLevel::mrwInvalidOptionalValue); + m_bHasMeshResolution = true; + if (strcmp(pAttributeValue, XML_3MF_VALUE_OBJECT_MESHRESOLUTION_FULL)==0) { + m_eSlicesMeshResolution = MODELSLICESMESHRESOLUTION_FULL; + } + else if (strcmp(pAttributeValue, XML_3MF_VALUE_OBJECT_MESHRESOLUTION_LOW) == 0) { + m_eSlicesMeshResolution = MODELSLICESMESHRESOLUTION_LOW; + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_INVALID_MESHRESOLUTION), eModelWarningLevel::mrwInvalidOptionalValue); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ATTRIBUTE), mrwInvalidOptionalValue); + } + + + if (strcmp(XML_3MF_NAMESPACE_PRODUCTIONSPEC, pNameSpace) == 0) { + if (strcmp(XML_3MF_PRODUCTION_UUID, pAttributeName) == 0) { + if (m_UUID.get()) + m_pWarnings->addException(CNMRException(NMR_ERROR_DUPLICATEUUID), eModelWarningLevel::mrwInvalidMandatoryValue); + m_UUID = std::make_shared(pAttributeValue); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ATTRIBUTE), mrwInvalidOptionalValue); + } + } + + void CModelReaderNode100_Object::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pChildName); + __NMRASSERT(pXMLReader); + __NMRASSERT(pNameSpace); + + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_CORESPEC100) == 0) { + // Read a mesh object + if (strcmp(pChildName, XML_3MF_ELEMENT_MESH) == 0) { + // If we already have parsed an object, the node is duplicate + if (m_pObject.get()) + throw CNMRException(NMR_ERROR_AMBIGUOUSOBJECTDEFINITON); + + // Create Empty Mesh + PMesh pMesh = std::make_shared(); + // Create Mesh Object + m_pObject = std::make_shared(m_nID, m_pModel, pMesh); + // Set Object Type (might fail, if string is invalid) + if (m_bHasType) { + if (!m_pObject->setObjectTypeString(m_sType, false)) + m_pWarnings->addWarning(NMR_ERROR_INVALIDMODELOBJECTTYPE, mrwInvalidOptionalValue); + } + + // Read Mesh + PModelReaderNode100_Mesh pXMLNode = std::make_shared(m_pModel, pMesh.get(), + m_pWarnings, m_pProgressMonitor, m_pObjectLevelPropertyID, m_nObjectLevelPropertyIndex); + pXMLNode->parseXML(pXMLReader); + + // Add Object to Parent + m_pModel->addResource(m_pObject); + + // Handle BeamLattice Data + handleBeamLatticeExtension(pXMLNode.get()); + + // Create Default Properties + createDefaultProperties(); + } + // Read a component object + else if (strcmp(pChildName, XML_3MF_ELEMENT_COMPONENTS) == 0) { + // If we already have parsed an object, the node is duplicate + if (m_pObject.get()) + throw CNMRException(NMR_ERROR_AMBIGUOUSOBJECTDEFINITON); + + // Create Component List Object + PModelComponentsObject pComponentsObject = std::make_shared(m_nID, m_pModel); + m_pObject = pComponentsObject; + // Set Object Type (might fail, if string is invalid) + if (m_bHasType) { + if (!m_pObject->setObjectTypeString(m_sType, false)) + m_pWarnings->addWarning(NMR_ERROR_INVALIDMODELOBJECTTYPE, mrwInvalidOptionalValue); + } + + // Read Components + PModelReaderNode pXMLNode = std::make_shared(pComponentsObject.get(), m_pWarnings); + pXMLNode->parseXML(pXMLReader); + + // Add Object to Parent + m_pModel->addResource(m_pObject); + + if (m_nObjectLevelPropertyIndex != 0) + m_pWarnings->addException(CNMRException(NMR_ERROR_OBJECTLEVELPID_ON_COMPONENTSOBJECT), mrwInvalidOptionalValue); + } + else if (strcmp(pChildName, XML_3MF_ELEMENT_METADATAGROUP) == 0) { + PModelReaderNode pXMLNode = std::make_shared(m_pWarnings); + pXMLNode->parseXML(pXMLReader); + + if (m_MetaDataGroup.get()) { + m_pWarnings->addException(CNMRException(NMR_ERROR_DUPLICATEMETADATAGROUP), mrwInvalidOptionalValue); + } + m_MetaDataGroup = dynamic_cast(pXMLNode.get())->getMetaDataGroup(); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT), mrwInvalidOptionalValue); + + // In any case (component object or mesh object) + if ( (m_pObject) && (m_nSliceStackId > 0) ) { + PPackageResourceID pID = m_pModel->findPackageResourceID(m_pModel->currentPath(), m_nSliceStackId); + if (!pID.get()) + throw CNMRException(NMR_ERROR_SLICESTACKRESOURCE_NOT_FOUND); + PModelSliceStack pSliceStackResource = std::dynamic_pointer_cast(m_pModel->findResource(pID) ); + if (pSliceStackResource) { + if ((m_pObject->getObjectType() == MODELOBJECTTYPE_MODEL) || (m_pObject->getObjectType() == MODELOBJECTTYPE_SOLIDSUPPORT)) { + if (!pSliceStackResource->areAllPolygonsClosed()) { + m_pWarnings->addException(CNMRException(NMR_ERROR_SLICEPOLYGONNOTCLOSED), mrwInvalidMandatoryValue); + } + } + } + else + throw CNMRException(NMR_ERROR_SLICESTACKRESOURCE_NOT_FOUND); + + m_pObject->assignSliceStack(pSliceStackResource); + m_pObject->setSlicesMeshResolution(m_eSlicesMeshResolution); + } + + } + + } + + // Create the object-level property from m_nObjectLevelPropertyID, if defined + void CModelReaderNode100_Object::createDefaultProperties() + { + if (m_pObject.get() == nullptr) + return; + + if (m_bHasDefaultPropertyIndex && m_bHasDefaultPropertyID) { + CModelMeshObject* pMeshObject = dynamic_cast(m_pObject.get()); + if (pMeshObject) { + CMesh * pMesh = pMeshObject->getMesh(); + if (pMesh) { + + // Assign Default Resource Property + PModelResource pResource = m_pModel->findResource(m_pModel->currentPath(), m_nObjectLevelPropertyModelID); + if (pResource.get() == nullptr) { + throw CNMRException(NMR_ERROR_RESOURCENOTFOUND); + } + if(!pResource->hasResourceIndexMap()) + pResource->buildResourceIndexMap(); + + auto pInformationHandler = pMesh->createMeshInformationHandler(); + CMeshInformation_Properties * pInformation = dynamic_cast (pInformationHandler->getInformationByType(0, NMR::emiProperties)); + if (pInformation == nullptr) { + NMR::PMeshInformation_Properties pNewInformation = std::make_shared(pMesh->getFaceCount()); + pInformationHandler->addInformation(pNewInformation); + + pInformation = pNewInformation.get(); + } + + ModelResourceID pPropertyID; + if (pResource->mapResourceIndexToPropertyID(m_nObjectLevelPropertyIndex, pPropertyID)) { + NMR::MESHINFORMATION_PROPERTIES * pDefaultData = new NMR::MESHINFORMATION_PROPERTIES; + pDefaultData->m_nUniqueResourceID = pResource->getPackageResourceID()->getUniqueID(); + pDefaultData->m_nPropertyIDs[0] = pPropertyID; + pDefaultData->m_nPropertyIDs[1] = pPropertyID; + pDefaultData->m_nPropertyIDs[2] = pPropertyID; + pInformation->setDefaultData((NMR::MESHINFORMATIONFACEDATA*)pDefaultData); + } + else { + throw CNMRException(NMR_ERROR_INVALID_RESOURCE_INDEX); + } + + } + } + } + } + + void CModelReaderNode100_Object::handleBeamLatticeExtension(CModelReaderNode100_Mesh* pXMLNode) + { + CModelMeshObject* pMeshObject = dynamic_cast(m_pObject.get()); + if (pMeshObject == nullptr || pXMLNode == nullptr) + return; + + if (pMeshObject->getMesh()->getBeamCount() > 0) { + if ( (pMeshObject->getObjectType() != MODELOBJECTTYPE_MODEL) && (pMeshObject->getObjectType() != MODELOBJECTTYPE_SOLIDSUPPORT)) { + m_pWarnings->addException(CNMRException(NMR_ERROR_BEAMLATTICE_INVALID_OBJECTTYPE), mrwInvalidOptionalValue); + } + } + + eModelBeamLatticeClipMode eClipMode; + nfBool bHasClippingMeshID; + ModelResourceID nClippingMeshID; + + pXMLNode->retrieveClippingInfo(eClipMode, bHasClippingMeshID, nClippingMeshID); + if (bHasClippingMeshID) { + PPackageResourceID pID = m_pModel->findPackageResourceID(m_pModel->currentPath(), nClippingMeshID); + if (!pID.get()) { + m_pWarnings->addWarning(NMR_ERROR_BEAMLATTICECLIPPINGRESOURCENOTDEFINED, mrwInvalidMandatoryValue); + } + else { + CModelObject * pModelObject = m_pModel->findObject(pID->getUniqueID()); + if (pModelObject) { + pMeshObject->getBeamLatticeAttributes()->m_bHasClippingMeshID = bHasClippingMeshID; + pMeshObject->getBeamLatticeAttributes()->m_pClippingMeshUniqueID = pID; + pMeshObject->getBeamLatticeAttributes()->m_eClipMode = eClipMode; + } + else { + pMeshObject->getBeamLatticeAttributes()->m_bHasClippingMeshID = false; + m_pWarnings->addWarning(NMR_ERROR_BEAMLATTICECLIPPINGRESOURCENOTDEFINED, mrwInvalidMandatoryValue); + } + } + } + + nfBool bHasRepresentationMeshID; + ModelResourceID nRepresentationMeshID; + pXMLNode->retrieveRepresentationInfo(bHasRepresentationMeshID, nRepresentationMeshID); + if (nRepresentationMeshID) { + PPackageResourceID pID = m_pModel->findPackageResourceID(m_pModel->currentPath(), nRepresentationMeshID); + if (!pID.get()) { + m_pWarnings->addWarning(NMR_ERROR_BEAMLATTICE_INVALID_REPRESENTATIONRESOURCE, mrwInvalidMandatoryValue); + } + else { + CModelObject * pModelObject = m_pModel->findObject(pID->getUniqueID()); + if (pModelObject) { + pMeshObject->getBeamLatticeAttributes()->m_bHasRepresentationMeshID = bHasRepresentationMeshID; + pMeshObject->getBeamLatticeAttributes()->m_pRepresentationUniqueID = pID; + } + else { + pMeshObject->getBeamLatticeAttributes()->m_bHasRepresentationMeshID = false; + m_pWarnings->addWarning(NMR_ERROR_BEAMLATTICE_INVALID_REPRESENTATIONRESOURCE, mrwInvalidMandatoryValue); + } + } + } + } + +} diff --git a/Source/Model/Reader/v100/NMR_ModelReaderNode100_Resources.cpp b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Resources.cpp new file mode 100644 index 0000000..fa23352 --- /dev/null +++ b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Resources.cpp @@ -0,0 +1,148 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: +NMR_ModelReaderNode100_Resources.cpp implements the Model Reader Resources Node +Class. A resources reader model node is a parser for the resources node of an +XML Model Stream. + +--*/ + +#include "Model/Reader/v100/NMR_ModelReaderNode100_Resources.h" +#include "Model/Reader/v100/NMR_ModelReaderNode100_Object.h" +#include "Model/Reader/v100/NMR_ModelReaderNode100_BaseMaterials.h" +#include "Model/Reader/v100/NMR_ModelReaderNode100_Colors.h" +#include "Model/Reader/v100/NMR_ModelReaderNode100_Tex2DGroup.h" +#include "Model/Reader/v100/NMR_ModelReaderNode100_Texture2D.h" +#include "Model/Reader/v100/NMR_ModelReaderNode100_CompositeMaterials.h" +#include "Model/Reader/v100/NMR_ModelReaderNode100_MultiProperties.h" +#include "Model/Reader/Slice1507/NMR_ModelReader_Slice1507_SliceStack.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Model/Classes/NMR_ModelConstants_Slices.h" + +namespace NMR { + + CModelReaderNode100_Resources::CModelReaderNode100_Resources(_In_ CModel * pModel, _In_ PModelWarnings pWarnings, _In_z_ const std::string sPath, + _In_ PProgressMonitor pProgressMonitor) + : CModelReaderNode(pWarnings, pProgressMonitor) + { + __NMRASSERT(pModel); + __NMRASSERT(sPath); + m_pModel = pModel; + m_sPath = sPath; + m_nProgressCount = 0; + } + + void CModelReaderNode100_Resources::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + } + + void CModelReaderNode100_Resources::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + } + + void CModelReaderNode100_Resources::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + + __NMRASSERT(pChildName); + __NMRASSERT(pXMLReader); + + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_CORESPEC100) == 0) { + if (strcmp(pChildName, XML_3MF_ELEMENT_OBJECT) == 0) { + m_pProgressMonitor->SetProgressIdentifier(ProgressIdentifier::PROGRESS_READRESOURCES); + m_pProgressMonitor->ReportProgressAndQueryCancelled(true); + + PModelReaderNode pXMLNode = std::make_shared(m_pModel, m_pWarnings, m_pProgressMonitor); + pXMLNode->parseXML(pXMLReader); + + } + else if (strcmp(pChildName, XML_3MF_ELEMENT_BASEMATERIALS) == 0) { + PModelReaderNode pXMLNode = std::make_shared(m_pModel, m_pWarnings); + pXMLNode->parseXML(pXMLReader); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT), mrwInvalidOptionalValue); + } + + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_MATERIALSPEC) == 0) { + if (strcmp(pChildName, XML_3MF_ELEMENT_COLORGROUP) == 0) { + PModelReaderNode pXMLNode = std::make_shared(m_pModel, m_pWarnings); + pXMLNode->parseXML(pXMLReader); + } + else if (strcmp(pChildName, XML_3MF_ELEMENT_TEX2DGROUP) == 0) { + PModelReaderNode pXMLNode = std::make_shared(m_pModel, m_pWarnings); + pXMLNode->parseXML(pXMLReader); + } + else if (strcmp(pChildName, XML_3MF_ELEMENT_TEXTURE2D) == 0) { + PModelReaderNode pXMLNode = std::make_shared(m_pModel, m_pWarnings); + pXMLNode->parseXML(pXMLReader); + } + else if (strcmp(pChildName, XML_3MF_ELEMENT_COMPOSITEMATERIALS) == 0) { + PModelReaderNode pXMLNode = std::make_shared(m_pModel, m_pWarnings); + pXMLNode->parseXML(pXMLReader); + } + else if (strcmp(pChildName, XML_3MF_ELEMENT_MULTIPROPERTIES) == 0) { + PModelReaderNode pXMLNode = std::make_shared(m_pModel, m_pWarnings); + pXMLNode->parseXML(pXMLReader); + } + // there might be other things, that are not yet properly implemented in lib3MF + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT), mrwInvalidOptionalValue); + } + + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_SLICESPEC) == 0) { + if (strcmp(pChildName, XML_3MF_ELEMENT_SLICESTACKRESOURCE) == 0) { + + m_pProgressMonitor->SetProgressIdentifier(ProgressIdentifier::PROGRESS_READRESOURCES); + m_pProgressMonitor->ReportProgressAndQueryCancelled(true); + + PModelReaderNode pXMLNode = std::make_shared( + m_pModel, m_pWarnings, m_pProgressMonitor, m_sPath.c_str()); + pXMLNode->parseXML(pXMLReader); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT), mrwInvalidOptionalValue); + } + + + } + + +} diff --git a/Source/Model/Reader/v100/NMR_ModelReaderNode100_Tex2Coord.cpp b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Tex2Coord.cpp new file mode 100644 index 0000000..caf12c0 --- /dev/null +++ b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Tex2Coord.cpp @@ -0,0 +1,107 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_Tex2Coord.cpp implements the Model Reader Tex2Coord Node Class. + +--*/ + +#include "Model/Reader/v100/NMR_ModelReaderNode100_Tex2Coord.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_ModelMeshObject.h" + +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CModelReaderNode100_Tex2Coord::CModelReaderNode100_Tex2Coord(_In_ CModel * pModel, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + + m_pModel = pModel; + m_bHasU = false; + m_bHasV = false; + m_sUVCoordinate.m_dU = 0.0; + m_sUVCoordinate.m_dV = 0.0; + } + + void CModelReaderNode100_Tex2Coord::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + + } + + void CModelReaderNode100_Tex2Coord::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TEXTUREVERTEX_U) == 0) { + try { + m_sUVCoordinate.m_dU = fnStringToDouble(pAttributeValue); + } + catch (...) + { + } + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TEXTUREVERTEX_V) == 0) { + try { + m_sUVCoordinate.m_dV = fnStringToDouble(pAttributeValue); + } + catch (...) + { + } + } + } + + nfBool CModelReaderNode100_Tex2Coord::hasU() + { + return m_bHasU; + } + + nfBool CModelReaderNode100_Tex2Coord::hasV() + { + return m_bHasV; + } + + MODELTEXTURE2DCOORDINATE CModelReaderNode100_Tex2Coord::getUV() + { + return m_sUVCoordinate; + } +} diff --git a/Source/Model/Reader/v100/NMR_ModelReaderNode100_Tex2DGroup.cpp b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Tex2DGroup.cpp new file mode 100644 index 0000000..c61f0da --- /dev/null +++ b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Tex2DGroup.cpp @@ -0,0 +1,132 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_Colors.cpp implements the Model Reader Color Group Class. + +--*/ + +#include "Model/Reader/v100/NMR_ModelReaderNode100_Tex2DGroup.h" +#include "Model/Reader/v100/NMR_ModelReaderNode100_Tex2Coord.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_ModelMeshObject.h" +#include "Model/Classes/NMR_ModelResource.h" +#include "Model/Classes/NMR_Model.h" + +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CModelReaderNode100_Tex2DGroup::CModelReaderNode100_Tex2DGroup(_In_ CModel * pModel, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + // Initialize variables + m_nID = 0; + m_nTextureID = 0; + + m_pModel = pModel; + } + + void CModelReaderNode100_Tex2DGroup::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Use parameter and assign to model Object + if (m_nID == 0) + throw CNMRException(NMR_ERROR_MISSINGMODELRESOURCEID); + + if (m_nTextureID == 0) + throw CNMRException(NMR_ERROR_MISSINGMODELRESOURCEID); + + PPackageResourceID pID = m_pModel->findPackageResourceID(m_pModel->currentPath(), m_nTextureID); + if (!pID) + throw CNMRException(NMR_ERROR_INVALIDMODELRESOURCE); + + PModelTexture2DResource pTexture2D = m_pModel->findTexture2D(pID->getUniqueID()); + + // Create Resource + m_pTexture2DGroup = std::make_shared(m_nID, m_pModel, pTexture2D); + + m_pModel->addResource(m_pTexture2DGroup); + + // Parse Content + parseContent(pXMLReader); + + } + + void CModelReaderNode100_Tex2DGroup::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TEX2DGROUP_ID) == 0) { + if (m_nID != 0) + throw CNMRException(NMR_ERROR_DUPLICATERESOURCEID); + + // Convert to integer and make a input and range check! + m_nID = fnStringToUint32(pAttributeValue); + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TEX2DGROUP_TEXTUREID) == 0) { + if (m_nTextureID != 0) + throw CNMRException(NMR_ERROR_DUPLICATERESOURCEID); + + // Convert to integer and make a input and range check! + ModelResourceID nID = fnStringToUint32(pAttributeValue); + if (nID == 0) + m_pWarnings->addException(CNMRException(NMR_ERROR_INVALIDMODELRESOURCE), mrwInvalidMandatoryValue); + + m_nTextureID = nID; + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ATTRIBUTE), mrwInvalidOptionalValue); + } + + + void CModelReaderNode100_Tex2DGroup::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_MATERIALSPEC) == 0) { + if (strcmp(pChildName, XML_3MF_ELEMENT_TEX2COORD) == 0) { + PModelReaderNode100_Tex2Coord pXMLNode = std::make_shared(m_pModel, m_pWarnings); + pXMLNode->parseXML(pXMLReader); + + ModelResourceIndex nTexCoordIndex = m_pTexture2DGroup->addUVCoordinate(pXMLNode->getUV()); + if (nTexCoordIndex > XML_3MF_MAXRESOURCEINDEX) + throw CNMRException(NMR_ERROR_INVALIDINDEX); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT), mrwInvalidOptionalValue); + } + } + +} diff --git a/Source/Model/Reader/v100/NMR_ModelReaderNode100_Texture2D.cpp b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Texture2D.cpp new file mode 100644 index 0000000..672785e --- /dev/null +++ b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Texture2D.cpp @@ -0,0 +1,165 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_Texture2D.cpp implements the Model Reader Texture2D Class. + +--*/ + +#include "Model/Reader/v100/NMR_ModelReaderNode100_Texture2D.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_ModelMeshObject.h" +#include "Model/Classes/NMR_ModelResource.h" +#include "Model/Classes/NMR_ModelTexture2D.h" +#include "Model/Classes/NMR_Model.h" + +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CModelReaderNode100_Texture2D::CModelReaderNode100_Texture2D(_In_ CModel * pModel, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + // Initialize variables + m_nID = 0; + m_hasBox = false; + m_pModel = pModel; + } + + void CModelReaderNode100_Texture2D::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Use parameter and assign to model Object + if (m_nID == 0) + throw CNMRException(NMR_ERROR_MISSINGMODELRESOURCEID); + + PModelAttachment pAttachment = m_pModel->findModelAttachment(m_sPath); + + // Create Resource + m_pTexture2DResource = CModelTexture2DResource::make(m_nID, m_pModel, pAttachment); + m_pModel->addResource(m_pTexture2DResource); + + // Set Properties + m_pTexture2DResource->setContentTypeString(m_sContentType, true); + + if (!m_sTileStyleU.empty()) { + try { + m_pTexture2DResource->setTileStyleUString(m_sTileStyleU); + } + catch (CNMRException & e) { + if (e.getErrorCode() == NMR_ERROR_INVALIDTILESTYLE) + m_pWarnings->addException(e, mrwInvalidOptionalValue); + else + throw e; + } + } + if (!m_sTileStyleV.empty()) { + try { + m_pTexture2DResource->setTileStyleVString(m_sTileStyleV); + } + catch (CNMRException & e) { + if (e.getErrorCode() == NMR_ERROR_INVALIDTILESTYLE) + m_pWarnings->addException(e, mrwInvalidOptionalValue); + else + throw e; + } + } + if (!m_sFilter.empty()) { + try { + m_pTexture2DResource->setFilterFromString(m_sFilter); + } + catch (CNMRException & e) { + if (e.getErrorCode() == NMR_ERROR_INVALIDFILTER) + m_pWarnings->addException(e, mrwInvalidOptionalValue); + else + throw e; + } + } + + if (m_hasBox) + m_pTexture2DResource->setBox2D(m_fU, m_fV, m_fWidth, m_fHeight); + else + m_pTexture2DResource->clearBox2D(); + + // Parse Content + parseContent(pXMLReader); + } + + void CModelReaderNode100_Texture2D::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TEXTURE2D_ID) == 0) { + if (m_nID != 0) + throw CNMRException(NMR_ERROR_DUPLICATERESOURCEID); + + // Convert to integer and make a input and range check! + m_nID = fnStringToUint32(pAttributeValue); + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TEXTURE2D_PATH) == 0) { + m_sPath = std::string(pAttributeValue); + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TEXTURE2D_CONTENTTYPE) == 0) { + m_sContentType = std::string(pAttributeValue); + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TEXTURE2D_TILESTYLEU) == 0) { + m_sTileStyleU = std::string(pAttributeValue); + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TEXTURE2D_TILESTYLEV) == 0) { + m_sTileStyleV = std::string(pAttributeValue); + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TEXTURE2D_FILTER) == 0) { + m_sFilter = std::string(pAttributeValue); + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TEXTURE2D_BOX) == 0) { + if (m_hasBox) + throw CNMRException(NMR_ERROR_DUPLICATE_BOX_ATTRIBUTE); + // parse box + std::vector box = fnVctType_fromString(pAttributeValue); + if (box.size() != 4) + throw CNMRException(NMR_ERROR_NAMESPACE_INVALID_ATTRIBUTE); + m_fU = nfFloat(box[0]); + m_fV = nfFloat(box[1]); + m_fWidth = nfFloat(box[2]); + m_fHeight = nfFloat(box[3]); + m_hasBox = true; + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ATTRIBUTE), mrwInvalidOptionalValue); + } + + +} diff --git a/Source/Model/Reader/v100/NMR_ModelReaderNode100_Triangle.cpp b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Triangle.cpp new file mode 100644 index 0000000..eeb5c61 --- /dev/null +++ b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Triangle.cpp @@ -0,0 +1,159 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_Triangle.cpp implements the Model Reader Triangle Node +Class. A triangle reader model node is a parser for the triangle node of an +XML Model Stream. + +--*/ + +#include "Model/Reader/v100/NMR_ModelReaderNode100_Triangle.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_StringUtils.h" +#include +#include + +namespace NMR { + + CModelReaderNode100_Triangle::CModelReaderNode100_Triangle(_In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + // Initialise default values + m_nPropertyID = 0; + m_nPropertyIndex1 = -1; + m_nPropertyIndex2 = -1; + m_nPropertyIndex3 = -1; + m_nIndex1 = -1; + m_nIndex2 = -1; + m_nIndex3 = -1; + } + + void CModelReaderNode100_Triangle::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + } + + void CModelReaderNode100_Triangle::retrieveIndices(_Out_ nfInt32 & nIndex1, _Out_ nfInt32 & nIndex2, _Out_ nfInt32 & nIndex3, nfInt32 nNodeCount) + { + if ((m_nIndex1 < 0) || (m_nIndex2 < 0) || (m_nIndex3 < 0)) + throw CNMRException(NMR_ERROR_INVALIDMODELNODEINDEX); + + if ((m_nIndex1 >= nNodeCount) || (m_nIndex2 >= nNodeCount) || (m_nIndex3 >= nNodeCount)) + throw CNMRException(NMR_ERROR_INVALIDMODELNODEINDEX); + + nIndex1 = m_nIndex1; + nIndex2 = m_nIndex2; + nIndex3 = m_nIndex3; + } + + nfBool CModelReaderNode100_Triangle::retrieveProperties(_Inout_ ModelResourceID & nPropertyID, _Inout_ ModelResourceIndex & nPropertyIndex1, _Inout_ ModelResourceIndex & nPropertyIndex2, _Inout_ ModelResourceIndex & nPropertyIndex3) + { + + if (m_nPropertyID == 0) + return false; + if (m_nPropertyIndex1 < 0) + return false; + + // See Core Spec 4.1.3.1 (Triangle) + nPropertyID = m_nPropertyID; + nPropertyIndex1 = m_nPropertyIndex1; + + if (m_nPropertyIndex2 >= 0) { + nPropertyIndex2 = m_nPropertyIndex2; + } + else { + nPropertyIndex2 = m_nPropertyIndex1; + } + + if (m_nPropertyIndex3 >= 0) { + nPropertyIndex3 = m_nPropertyIndex3; + } + else { + nPropertyIndex3 = m_nPropertyIndex1; + } + + return true; + + } + + void CModelReaderNode100_Triangle::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + nfInt32 nValue; + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TRIANGLE_V1) == 0) { + nValue = fnStringToInt32(pAttributeValue); + if ((nValue >= 0) && (nValue < XML_3MF_MAXRESOURCEINDEX)) + m_nIndex1 = nValue; + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TRIANGLE_V2) == 0) { + nValue = fnStringToInt32(pAttributeValue); + if ((nValue >= 0) && (nValue < XML_3MF_MAXRESOURCEINDEX)) + m_nIndex2 = nValue; + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TRIANGLE_V3) == 0) { + nValue = fnStringToInt32(pAttributeValue); + if ((nValue >= 0) && (nValue < XML_3MF_MAXRESOURCEINDEX)) + m_nIndex3 = nValue; + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TRIANGLE_PID) == 0) { + nValue = fnStringToInt32(pAttributeValue); + if ((nValue >= 0) && (nValue < XML_3MF_MAXRESOURCEID)) + m_nPropertyID = nValue; + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TRIANGLE_P1) == 0) { + nValue = fnStringToInt32(pAttributeValue); + if ((nValue >= 0) && (nValue < XML_3MF_MAXRESOURCEINDEX)) + m_nPropertyIndex1 = nValue; + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TRIANGLE_P2) == 0) { + nValue = fnStringToInt32(pAttributeValue); + if ((nValue >= 0) && (nValue < XML_3MF_MAXRESOURCEINDEX)) + m_nPropertyIndex2 = nValue; + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_TRIANGLE_P3) == 0) { + nValue = fnStringToInt32(pAttributeValue); + if ((nValue >= 0) && (nValue < XML_3MF_MAXRESOURCEINDEX)) + m_nPropertyIndex3 = nValue; + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ATTRIBUTE), mrwInvalidOptionalValue); + } + +} diff --git a/Source/Model/Reader/v100/NMR_ModelReaderNode100_Triangles.cpp b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Triangles.cpp new file mode 100644 index 0000000..85cea0e --- /dev/null +++ b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Triangles.cpp @@ -0,0 +1,184 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_Triangles.cpp implements the Model Reader Triangles Node +Class. A triangles reader model node is a parser for the triangles node of an +XML Model Stream. + +--*/ + +#include "Model/Reader/v100/NMR_ModelReaderNode100_Triangles.h" +#include "Model/Reader/v100/NMR_ModelReaderNode100_Triangle.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Model/Reader/NMR_ModelReader_ColorMapping.h" + +namespace NMR { + + CModelReaderNode100_Triangles::CModelReaderNode100_Triangles(_In_ CModel * pModel, _In_ CMesh * pMesh, + _In_ PModelWarnings pWarnings, _In_ PPackageResourceID pObjectLevelPropertyID, _In_ ModelResourceIndex nDefaultPropertyIndex) + : CModelReaderNode(pWarnings) + { + __NMRASSERT(pMesh); + __NMRASSERT(pModel); + + m_pObjectLevelPropertyID = pObjectLevelPropertyID; + m_nDefaultResourceIndex = nDefaultPropertyIndex; + + m_nUsedResourceID = 0; + + m_pModel = pModel; + m_pMesh = pMesh; + } + + void CModelReaderNode100_Triangles::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse Name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + } + + void CModelReaderNode100_Triangles::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + } + + + _Ret_notnull_ CMeshInformation_Properties * CModelReaderNode100_Triangles::createPropertiesInformation() + { + CMeshInformationHandler * pMeshInformationHandler = m_pMesh->createMeshInformationHandler(); + + CMeshInformation * pInformation = pMeshInformationHandler->getInformationByType(0, emiProperties); + CMeshInformation_Properties * pProperties = nullptr; + + if (pInformation) + pProperties = dynamic_cast (pInformation); + + if (!pProperties) { + PMeshInformation_Properties pNewMeshInformation = std::make_shared(m_pMesh->getFaceCount()); + pMeshInformationHandler->addInformation(pNewMeshInformation); + + pProperties = pNewMeshInformation.get(); + } + + return pProperties; + } + + + void CModelReaderNode100_Triangles::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pChildName); + __NMRASSERT(pXMLReader); + __NMRASSERT(pNameSpace); + + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_CORESPEC100) == 0) { + if (strcmp(pChildName, XML_3MF_ELEMENT_TRIANGLE) == 0) { + // Parse XML + PModelReaderNode100_Triangle pXMLNode = std::make_shared(m_pWarnings); + pXMLNode->parseXML(pXMLReader); + + // Retrieve node indices + nfInt32 nIndex1, nIndex2, nIndex3; + pXMLNode->retrieveIndices(nIndex1, nIndex2, nIndex3, m_pMesh->getNodeCount()); + + // Create face if valid + if ((nIndex1 != nIndex2) && (nIndex1 != nIndex3) && (nIndex2 != nIndex3)) { + MESHNODE * pNode1 = m_pMesh->getNode(nIndex1); + MESHNODE * pNode2 = m_pMesh->getNode(nIndex2); + MESHNODE * pNode3 = m_pMesh->getNode(nIndex3); + MESHFACE * pFace = m_pMesh->addFace(pNode1, pNode2, pNode3); + + ModelResourceID nModelResourceID = 0; + if (m_pObjectLevelPropertyID) + nModelResourceID = m_pObjectLevelPropertyID->getModelResourceID(); + ModelResourceIndex nResourceIndex1 = m_nDefaultResourceIndex; + ModelResourceIndex nResourceIndex2 = m_nDefaultResourceIndex; + ModelResourceIndex nResourceIndex3 = m_nDefaultResourceIndex; + + if (pXMLNode->retrieveProperties(nModelResourceID, nResourceIndex1, nResourceIndex2, nResourceIndex3) || (nModelResourceID != 0)) { + // set potential default properties (i.e. used pid) + m_nUsedResourceID = nModelResourceID; + + PPackageResourceID pID = m_pModel->findPackageResourceID(m_pModel->currentPath(), nModelResourceID); + if (pID.get()) { + // Find and Assign Resource of this Property + PModelResource pResource = m_pModel->findResource(pID->getUniqueID()); + if (pResource.get () != nullptr) { + if (!pResource->hasResourceIndexMap()) + pResource->buildResourceIndexMap(); + + ModelPropertyID pPropertyID1; + ModelPropertyID pPropertyID2; + ModelPropertyID pPropertyID3; + if (pResource->mapResourceIndexToPropertyID(nResourceIndex1, pPropertyID1) + && pResource->mapResourceIndexToPropertyID(nResourceIndex2, pPropertyID2) + && pResource->mapResourceIndexToPropertyID(nResourceIndex3, pPropertyID3)) { + + CMeshInformation_Properties * pProperties = createPropertiesInformation(); + MESHINFORMATION_PROPERTIES* pFaceData = (MESHINFORMATION_PROPERTIES*)pProperties->getFaceData(pFace->m_index); + if (pFaceData) { + pFaceData->m_nUniqueResourceID = pID->getUniqueID(); + pFaceData->m_nPropertyIDs[0] = pPropertyID1; + pFaceData->m_nPropertyIDs[1] = pPropertyID2; + pFaceData->m_nPropertyIDs[2] = pPropertyID3; + } + } else { + m_pWarnings->addException(CNMRException(NMR_ERROR_INVALIDMESHINFORMATIONINDEX), mrwInvalidOptionalValue); + } + } + } + else { + m_pWarnings->addException(CNMRException(NMR_ERROR_INVALIDMODELRESOURCE), mrwInvalidOptionalValue); + } + + } + } + else + throw CNMRException(NMR_ERROR_INVALIDMODELCOORDINATEINDICES); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT), mrwInvalidOptionalValue); + + } + } + + ModelResourceID CModelReaderNode100_Triangles::getUsedPropertyID() const + { + return m_nUsedResourceID; + } + +} diff --git a/Source/Model/Reader/v100/NMR_ModelReaderNode100_Vertex.cpp b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Vertex.cpp new file mode 100644 index 0000000..797e782 --- /dev/null +++ b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Vertex.cpp @@ -0,0 +1,113 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: +NMR_ModelReaderNode100_Vertex.cpp implements the Model Reader Vertex Node Class. +A vertex reader model node is a parser for the vertex node of an XML Model Stream. + +--*/ + +#include "Model/Reader/v100/NMR_ModelReaderNode100_Vertex.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include +#include +#include + +namespace NMR { + + CModelReaderNode100_Vertex::CModelReaderNode100_Vertex(_In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + m_fX = 0.0f; + m_fY = 0.0f; + m_fZ = 0.0f; + m_bHasX = false; + m_bHasY = false; + m_bHasZ = false; + } + + void CModelReaderNode100_Vertex::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + } + + void CModelReaderNode100_Vertex::retrievePosition(_Out_ nfFloat & fX, _Out_ nfFloat & fY, _Out_ nfFloat & fZ) + { + // Model Coordinate is missing + if ((!m_bHasX) || (!m_bHasY) || (!m_bHasZ)) + throw CNMRException(NMR_ERROR_MODELCOORDINATEMISSING); + + fX = m_fX; + fY = m_fY; + fZ = m_fZ; + } + + void CModelReaderNode100_Vertex::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_VERTEX_X) == 0) { + m_fX = strtof(pAttributeValue, nullptr); + if (std::isnan (m_fX)) + throw CNMRException(NMR_ERROR_INVALIDMODELCOORDINATES); + if (fabs (m_fX) > XML_3MF_MAXIMUMCOORDINATEVALUE) + throw CNMRException(NMR_ERROR_INVALIDMODELCOORDINATES); + m_bHasX = true; + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_VERTEX_Y) == 0) { + m_fY = strtof(pAttributeValue, nullptr); + if (std::isnan (m_fY)) + throw CNMRException(NMR_ERROR_INVALIDMODELCOORDINATES); + if (fabs(m_fY) > XML_3MF_MAXIMUMCOORDINATEVALUE) + throw CNMRException(NMR_ERROR_INVALIDMODELCOORDINATES); + m_bHasY = true; + } + else if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_VERTEX_Z) == 0) { + m_fZ = strtof(pAttributeValue, nullptr); + if (std::isnan (m_fZ)) + throw CNMRException(NMR_ERROR_INVALIDMODELCOORDINATES); + if (fabs(m_fZ) > XML_3MF_MAXIMUMCOORDINATEVALUE) + throw CNMRException(NMR_ERROR_INVALIDMODELCOORDINATES); + m_bHasZ = true; + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ATTRIBUTE), mrwInvalidOptionalValue); + } + + +} diff --git a/Source/Model/Reader/v100/NMR_ModelReaderNode100_Vertices.cpp b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Vertices.cpp new file mode 100644 index 0000000..b3a0201 --- /dev/null +++ b/Source/Model/Reader/v100/NMR_ModelReaderNode100_Vertices.cpp @@ -0,0 +1,92 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelReaderNode100_Vertices.cpp defines the Model Reader Vertices Node Class. +A vertices reader model node is a parser for the vertices node of an +XML Model Stream. + +--*/ + +#include "Model/Reader/v100/NMR_ModelReaderNode100_Vertices.h" +#include "Model/Reader/v100/NMR_ModelReaderNode100_Vertex.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" + +namespace NMR { + + CModelReaderNode100_Vertices::CModelReaderNode100_Vertices(_In_ CMesh * pMesh, _In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + __NMRASSERT(pMesh); + m_pMesh = pMesh; + } + + void CModelReaderNode100_Vertices::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse Name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + } + + void CModelReaderNode100_Vertices::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + } + + void CModelReaderNode100_Vertices::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) + { + __NMRASSERT(pChildName); + __NMRASSERT(pXMLReader); + __NMRASSERT(pNameSpace); + + if (strcmp(pNameSpace, XML_3MF_NAMESPACE_CORESPEC100) == 0) { + if (strcmp(pChildName, XML_3MF_ELEMENT_VERTEX) == 0) + { + PModelReaderNode100_Vertex pXMLNode = std::make_shared(m_pWarnings); + pXMLNode->parseXML(pXMLReader); + + // Create Mesh Node + nfFloat fX, fY, fZ; + pXMLNode->retrievePosition(fX, fY, fZ); + m_pMesh->addNode(fnVEC3_make(fX, fY, fZ)); + } + else + m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT), mrwInvalidOptionalValue); + } + } + +} diff --git a/Source/Model/Writer/NMR_KeyStoreOpcPackageWriter.cpp b/Source/Model/Writer/NMR_KeyStoreOpcPackageWriter.cpp new file mode 100644 index 0000000..a61a9d7 --- /dev/null +++ b/Source/Model/Writer/NMR_KeyStoreOpcPackageWriter.cpp @@ -0,0 +1,234 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_OpcPackageWriter.cpp defines an OPC Package writer in a portable way. + +--*/ + +#include "Common/NMR_Exception.h" +#include "Common/NMR_StringUtils.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_ErrorConst.h" +#include "Model/Writer/NMR_KeyStoreOpcPackageWriter.h" +#include "Model/Writer/SecureContent101/NMR_ModelWriterNode_KeyStore.h" +#include "Common/Platform/NMR_ExportStream_Compressed.h" +#include "Common/Platform/NMR_XmlWriter_Native.h" +#include "Common/OPC/NMR_OpcPackageWriter.h" +#include "Model/Classes/NMR_Model.h" +#include "Model/Classes/NMR_ModelContext.h" +#include "Model/Classes/NMR_KeyStoreResourceData.h" +#include "Model/Classes/NMR_KeyStoreAccessRight.h" +#include "Model/Classes/NMR_KeyStoreResourceDataGroup.h" +#include "Common/NMR_SecureContext.h" +#include "Common/NMR_SecureContentTypes.h" +#include "Common/Platform/NMR_ExportStream_Encrypted.h" +#include "Common/Platform/NMR_ImportStream_Encrypted.h" +#include "Common/Platform/NMR_ExportStream.h" +#include "Common/NMR_ModelWarnings.h" +#include "Model/Classes/NMR_KeyStoreFactory.h" + +namespace NMR { + + + CKeyStoreOpcPackageWriter::CKeyStoreOpcPackageWriter(_In_ PExportStream pImportStream, _In_ CModelContext const & context) + :m_pContext(context) + { + if (!context.isComplete()) + throw CNMRException(NMR_ERROR_INVALIDPOINTER); + + m_pPackageWriter = std::make_shared(pImportStream); + refreshAllResourceDataGroups(); + } + + void CKeyStoreOpcPackageWriter::refreshAllResourceDataGroups() { + PKeyStore const & keyStore = m_pContext.keyStore(); + for (nfUint64 i = 0; i < keyStore->getResourceDataGroupCount(); ++i) { + PKeyStoreResourceDataGroup rdg = keyStore->getResourceDataGroup(i); + if (rdg->isOpen()) { + for (nfUint64 j = 0; j < rdg->getAccessRightCount(); ++j) { + PKeyStoreAccessRight ar = rdg->getAccessRight(j); + refreshAccessRight(ar, rdg->getKey()); + } + } + } + + PModel const & model = m_pContext.model(); + if (!model->hasCryptoRandCallbak()) + m_pContext.warnings()->addWarning(NMR_ERROR_RNGCALLBACKNOTCRYPTOSTRONG, eModelWarningLevel::mrwInvalidOptionalValue); + for (nfUint64 i = 0; i < keyStore->getResourceDataCount(); ++i) { + PKeyStoreResourceData rd = keyStore->getResourceData(i); + if (rd->getGroup()->isOpen()) { + std::vector newIv(fnGetAlgorithmInitVectorSize(rd->getEncryptionAlgorithm()), 0); + model->generateRandomBytes(newIv.data(), newIv.size()); + rd->setInitVector(newIv); + } + } + } + + bool CKeyStoreOpcPackageWriter::pathIsEncrypted(_In_ std::string sPath) + { + PSecureContext const& secureContext = m_pContext.secureContext(); + PKeyStore const& keyStore = m_pContext.keyStore(); + + NMR::PKeyStoreResourceData rd = keyStore->findResourceData(sPath); + if (nullptr != rd) { + if (secureContext->hasDekCtx()) { + return true; + } + else { + m_pContext.warnings()->addWarning(NMR_ERROR_DEKDESCRIPTORNOTFOUND, eModelWarningLevel::mrwMissingMandatoryValue); + } + } + return false; + } + + POpcPackagePart CKeyStoreOpcPackageWriter::wrapPartStream(PKeyStoreResourceData rd, POpcPackagePart part) { + PSecureContext const & secureContext = m_pContext.secureContext(); + ContentEncryptionDescriptor p = secureContext->getDekCtx(); + PKeyStoreResourceDataGroup rdg = m_pContext.keyStore()->findResourceDataGroupByResourceDataPath(rd->packagePath()); + p.m_sDekDecryptData.m_sParams = CKeyStoreFactory::makeContentEncryptionParams(rd, rdg); + + PExportStream stream; + PExportStream encryptStream = std::make_shared(part->getExportStream(), p); + if (rd->isCompressed()) { + PExportStream compressStream = std::make_shared(encryptStream); + stream = compressStream; + } else { + stream = encryptStream; + } + return std::make_shared(*part, stream); + } + + void CKeyStoreOpcPackageWriter::refreshResourceDataTag(PKeyStoreResourceData rd) { + ContentEncryptionDescriptor dekCtx = m_pContext.secureContext()->getDekCtx(); + PKeyStoreResourceDataGroup rdg = m_pContext.keyStore()->findResourceDataGroupByResourceDataPath(rd->packagePath()); + dekCtx.m_sDekDecryptData.m_sParams = CKeyStoreFactory::makeContentEncryptionParams(rd, rdg); + dekCtx.m_fnCrypt(0, nullptr, nullptr, dekCtx.m_sDekDecryptData); + rd->setAuthTag(dekCtx.m_sDekDecryptData.m_sParams->getAuthTag()); + } + + void CKeyStoreOpcPackageWriter::refreshAccessRight(PKeyStoreAccessRight ar, std::vector const & key) { + try { + KeyWrappingDescriptor ctx = m_pContext.secureContext()->getKekCtx(ar->getConsumer()->getConsumerID()); + ctx.m_sKekDecryptData.m_pAccessRight = ar; + std::vector closedKey; + //give consumer a chance to (re)encrypt this key + nfUint64 wrapped = ctx.m_fnWrap(key, closedKey, ctx.m_sKekDecryptData); + ar->setCipherValue(closedKey); + } catch (CNMRException const & e) { + if (ar->isNew()) { + m_pContext.warnings()->addException(e, eModelWarningLevel::mrwFatal); + } + //here, either there is no registered consumer client or client decided not to refresh the value + } + } + + POpcPackagePart CKeyStoreOpcPackageWriter::addPart(_In_ std::string sPath) + { + PSecureContext const & secureContext = m_pContext.secureContext(); + PKeyStore const & keyStore = m_pContext.keyStore(); + + auto pPart = m_pPackageWriter->addPart(sPath); + NMR::PKeyStoreResourceData rd = keyStore->findResourceData(sPath); + if (nullptr != rd) { + if (secureContext->hasDekCtx()) { + return wrapPartStream(rd, pPart); + } else { + m_pContext.warnings()->addWarning(NMR_ERROR_DEKDESCRIPTORNOTFOUND, eModelWarningLevel::mrwFatal); + } + } + return pPart; + } + + void CKeyStoreOpcPackageWriter::close() { + PSecureContext const & secureContext = m_pContext.secureContext(); + PKeyStore const & keyStore = m_pContext.keyStore(); + + for (nfUint32 i = 0; i < keyStore->getResourceDataCount(); i++) { + PKeyStoreResourceData rd = keyStore->getResourceData(i); + if(secureContext->hasDekCtx()){ + refreshResourceDataTag(rd); + } + } + + if (!keyStore->empty()) { + POpcPackagePart pKeyStorePart = m_pPackageWriter->addPart(PACKAGE_3D_KEYSTORE_URI); + m_pPackageWriter->addContentType(pKeyStorePart, PACKAGE_KEYSTORE_CONTENT_TYPE); + m_pPackageWriter->addRootRelationship(PACKAGE_KEYSTORE_RELATIONSHIP_TYPE, pKeyStorePart.get()); + m_pPackageWriter->addRootRelationship(PACKAGE_MUST_PRESERVE_RELATIONSHIP_TYPE, pKeyStorePart.get()); + PXmlWriter_Native pXMLWriter4KeyStore = std::make_shared(pKeyStorePart->getExportStream()); + writeKeyStoreStream(pXMLWriter4KeyStore.get()); + } + } + + void CKeyStoreOpcPackageWriter::addContentType(std::string sExtension, std::string sContentType) + { + m_pPackageWriter->addContentType(sExtension, sContentType); + } + + void CKeyStoreOpcPackageWriter::addContentType(POpcPackagePart pOpcPackagePart, std::string sContentType) + { + m_pPackageWriter->addContentType(pOpcPackagePart, sContentType); + } + + POpcPackageRelationship CKeyStoreOpcPackageWriter::addRootRelationship(std::string sType, COpcPackagePart * pTargetPart) + { + return m_pPackageWriter->addRootRelationship(sType, pTargetPart); + } + + POpcPackageRelationship CKeyStoreOpcPackageWriter::addPartRelationship(POpcPackagePart pOpcPackagePart, std::string sType, COpcPackagePart * pTargetPart) + { + return m_pPackageWriter->addPartRelationship(pOpcPackagePart, sType, pTargetPart); + } + + std::list CKeyStoreOpcPackageWriter::addWriterSpecificRelationships(_In_ POpcPackagePart pOpcPackagePart, _In_ COpcPackagePart* pTargetPart) + { + std::list list; + std::string sPath = fnIncludeLeadingPathDelimiter(pTargetPart->getURI()); + if (pathIsEncrypted(sPath)) + { + list.push_back(addPartRelationship(pOpcPackagePart, PACKAGE_ENCRYPTED_FILE_RELATIONSHIP, pTargetPart)); + } + + list.merge(m_pPackageWriter->addWriterSpecificRelationships(pOpcPackagePart, pTargetPart)); + return list; + } + + void CKeyStoreOpcPackageWriter::writeKeyStoreStream(_In_ CXmlWriter * pXMLWriter) { + pXMLWriter->WriteStartDocument(); + + CModelWriterNode_KeyStore XMLNode4KeyStore(pXMLWriter, m_pContext.monitor(), m_pContext.keyStore()); + XMLNode4KeyStore.writeToXML(); + + pXMLWriter->WriteEndDocument(); + + pXMLWriter->Flush(); + } + +} diff --git a/Source/Model/Writer/NMR_ModelWriter.cpp b/Source/Model/Writer/NMR_ModelWriter.cpp new file mode 100644 index 0000000..1a55eac --- /dev/null +++ b/Source/Model/Writer/NMR_ModelWriter.cpp @@ -0,0 +1,68 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelWriter.cpp implements the Model Writer Class. +A model writer exports the in memory represenation into a model file. + +--*/ + +#include "Model/Writer/NMR_ModelWriter.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/Platform/NMR_XmlWriter.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_SecureContext.h" + + +#include + +namespace NMR { + + const int MIN_DECIMAL_PRECISION = 1; + const int MAX_DECIMAL_PRECISION = 16; + + CModelWriter::CModelWriter(_In_ PModel pModel): + CModelContext(pModel), + m_nDecimalPrecision(6) + { + } + + void CModelWriter::SetDecimalPrecision(nfUint32 nDecimalPrecision) + { + if ((nDecimalPrecision < MIN_DECIMAL_PRECISION) || (nDecimalPrecision > MAX_DECIMAL_PRECISION)) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + m_nDecimalPrecision = nDecimalPrecision; + } + + nfUint32 CModelWriter::GetDecimalPrecision() + { + return m_nDecimalPrecision; + } + +} diff --git a/Source/Model/Writer/NMR_ModelWriterNode.cpp b/Source/Model/Writer/NMR_ModelWriterNode.cpp new file mode 100644 index 0000000..03ec812 --- /dev/null +++ b/Source/Model/Writer/NMR_ModelWriterNode.cpp @@ -0,0 +1,129 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelWriterNode.cpp implements Model Writer Node Class. +This is the abstract base class for all 3MF model stream exporters. + +--*/ + +#include "Model/Writer/NMR_ModelWriterNode.h" + +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include + +namespace NMR { + + CModelWriterNode::CModelWriterNode(_In_ CXmlWriter * pXMLWriter, _In_ PProgressMonitor pProgressMonitor) + { + __NMRASSERT(pXMLWriter); + __NMRASSERT(pProgressMonitor); + m_pXMLWriter = pXMLWriter; + m_pProgressMonitor = pProgressMonitor; + } + + void CModelWriterNode::writeStringAttribute(_In_z_ const nfChar * pAttributeName, _In_ std::string sAttributeValue) + { + writeConstStringAttribute(pAttributeName, sAttributeValue.c_str ()); + } + + void CModelWriterNode::writePrefixedStringAttribute(_In_z_ const nfChar * pPrefix, _In_ const nfChar * pAttributeName, std::string sAttributeValue) + { + writeConstPrefixedStringAttribute(pPrefix, pAttributeName, sAttributeValue.c_str()); + } + + void CModelWriterNode::writeConstStringAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + __NMRASSERT(m_pXMLWriter); + + m_pXMLWriter->WriteAttributeString(nullptr, pAttributeName, nullptr, pAttributeValue); + } + + void CModelWriterNode::writeConstPrefixedStringAttribute(_In_z_ const nfChar * pPrefix, _In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + __NMRASSERT(pPrefix); + __NMRASSERT(m_pXMLWriter); + + m_pXMLWriter->WriteAttributeString(pPrefix, pAttributeName, nullptr, pAttributeValue); + } + + void CModelWriterNode::writeIntAttribute(_In_z_ const nfChar * pAttributeName, _In_ nfInt32 nAttributeValue) + { + std::stringstream sStream; + sStream << nAttributeValue; + writeConstStringAttribute(pAttributeName, sStream.str().c_str()); + } + + void CModelWriterNode::writeUintAttribute(_In_z_ const nfChar * pAttributeName, _In_ nfUint32 nAttributeValue) + { + std::stringstream sStream; + sStream << nAttributeValue; + writeConstStringAttribute(pAttributeName, sStream.str().c_str()); + } + + void CModelWriterNode::writeFloatAttribute(_In_z_ const nfChar * pAttributeName, _In_ nfFloat fAttributeValue) + { + std::stringstream sStream; + sStream << fAttributeValue; + writeConstStringAttribute(pAttributeName, sStream.str().c_str()); + } + + void CModelWriterNode::writeStartElement(_In_z_ const nfChar * pElementName) + { + m_pXMLWriter->WriteStartElement(nullptr, pElementName, nullptr); + } + + void CModelWriterNode::writeStartElementWithNamespace(_In_z_ const nfChar * pElementName, _In_z_ const nfChar * pNameSpace) + { + m_pXMLWriter->WriteStartElement(nullptr, pElementName, pNameSpace); + } + + void CModelWriterNode::writeStartElementWithPrefix(_In_z_ const nfChar * pElementName, _In_z_ const nfChar * pPrefix) + { + m_pXMLWriter->WriteStartElement(pPrefix, pElementName, nullptr); + } + + void CModelWriterNode::writeEndElement() + { + m_pXMLWriter->WriteEndElement(); + } + + void CModelWriterNode::writeFullEndElement() + { + m_pXMLWriter->WriteFullEndElement(); + } + + void CModelWriterNode::writeText(_In_z_ const nfChar * pwszText, _In_ nfUint32 cbLength) + { + m_pXMLWriter->WriteText(pwszText, cbLength); + } +} diff --git a/Source/Model/Writer/NMR_ModelWriterNode_KeyStoreBase.cpp b/Source/Model/Writer/NMR_ModelWriterNode_KeyStoreBase.cpp new file mode 100644 index 0000000..083fe85 --- /dev/null +++ b/Source/Model/Writer/NMR_ModelWriterNode_KeyStoreBase.cpp @@ -0,0 +1,41 @@ +#include "Model/Writer/NMR_ModelWriterNode_KeyStoreBase.h" +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelWriterNode_KeyStoreBase.cpp implements the base class for all Model Writer Node classes that are related to . + +--*/ +#include "Common/NMR_Exception.h" + + +NMR::CModelWriterNode_KeyStoreBase::CModelWriterNode_KeyStoreBase(CXmlWriter * pXMLWriter, PProgressMonitor pProgressMonitor, PKeyStore pKeyStore) +: CModelWriterNode(pXMLWriter, pProgressMonitor), m_pKeyStore(pKeyStore) +{ + if (!pKeyStore) + throw CNMRException(NMR_ERROR_INVALIDPOINTER); +} diff --git a/Source/Model/Writer/NMR_ModelWriterNode_ModelBase.cpp b/Source/Model/Writer/NMR_ModelWriterNode_ModelBase.cpp new file mode 100644 index 0000000..1ebc711 --- /dev/null +++ b/Source/Model/Writer/NMR_ModelWriterNode_ModelBase.cpp @@ -0,0 +1,50 @@ +#include "Model/Writer/NMR_ModelWriterNode_ModelBase.h" +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelWriterNode_ModelBase.h defines the Base class for all Model Writer Node classes that are related to . +This is the abstract base class for all 3MF model stream exporters. + +--*/ + +#include "Model/Writer/NMR_ModelWriterNode_ModelBase.h" + +namespace NMR { + + CModelWriterNode_ModelBase::CModelWriterNode_ModelBase(CModel * pModel, CXmlWriter * pXMLWriter, PProgressMonitor pProgressMonitor) + :CModelWriterNode(pXMLWriter, pProgressMonitor) { + __NMRASSERT(pModel); + m_pModel = pModel; + } + + void CModelWriterNode_ModelBase::assertResourceIsInCurrentPath(PPackageResourceID pID) { + if (pID->getPath() != m_pModel->currentPath()) + throw CNMRException(NMR_ERROR_MODELRESOURCE_IN_DIFFERENT_MODEL); + } +} + diff --git a/Source/Model/Writer/NMR_ModelWriter_3MF.cpp b/Source/Model/Writer/NMR_ModelWriter_3MF.cpp new file mode 100644 index 0000000..89572ee --- /dev/null +++ b/Source/Model/Writer/NMR_ModelWriter_3MF.cpp @@ -0,0 +1,112 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelWriter_3MF.cpp implements the 3MF Model Writer Class. +A model writer exports the in memory represenation into a 3MF file. + +--*/ + +#include "Model/Writer/SecureContent101/NMR_ModelWriterNode_KeyStore.h" +#include "Model/Writer/NMR_ModelWriter_3MF.h" +#include "Model/Writer/v100/NMR_ModelWriterNode100_Model.h" +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include + +#include "Common/Platform/NMR_XmlWriter.h" +#include "Common/Platform/NMR_Platform.h" +#include "Common/3MF_ProgressMonitor.h" + +namespace NMR { + + CModelWriter_3MF::CModelWriter_3MF(_In_ PModel pModel) : CModelWriter(pModel) + { + // empty on purpose + } + + void CModelWriter_3MF::exportToStream(_In_ PExportStream pStream) + { + if (pStream == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + monitor()->SetProgressIdentifier(ProgressIdentifier::PROGRESS_CREATEOPCPACKAGE); + monitor()->ReportProgressAndQueryCancelled(true); + + // Create new OPC Package + createPackage(model().get()); + + monitor()->SetProgressIdentifier(ProgressIdentifier::PROGRESS_WRITEMODELSTOSTREAM); + monitor()->ReportProgressAndQueryCancelled(true); + + // Write Package to Stream + writePackageToStream(pStream); + + monitor()->SetProgressIdentifier(ProgressIdentifier::PROGRESS_CLEANUP); + monitor()->ReportProgressAndQueryCancelled(true); + + // Release Memory + releasePackage(); + + monitor()->IncrementProgress(1); + + monitor()->SetProgressIdentifier(ProgressIdentifier::PROGRESS_DONE); + monitor()->ReportProgressAndQueryCancelled(true); + } + + void CModelWriter_3MF::writeNonRootModelStream(_In_ CXmlWriter *pXMLWriter) + { + if (pXMLWriter == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + pXMLWriter->WriteStartDocument(); + CModelWriterNode100_Model ModelNode(model().get(), pXMLWriter, monitor(), GetDecimalPrecision(), false); + ModelNode.writeToXML(); + + pXMLWriter->WriteEndDocument(); + pXMLWriter->Flush(); + } + + void CModelWriter_3MF::writeModelStream(_In_ CXmlWriter * pXMLWriter, _In_ CModel * pModel) + { + __NMRASSERT(pModel != nullptr); + if (pXMLWriter == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + model()->setCurrentPath(model()->rootPath()); + + pXMLWriter->WriteStartDocument(); + + CModelWriterNode100_Model ModelNode(pModel, pXMLWriter, monitor(), GetDecimalPrecision(), true); + ModelNode.writeToXML(); + + pXMLWriter->WriteEndDocument(); + + pXMLWriter->Flush(); + } +} diff --git a/Source/Model/Writer/NMR_ModelWriter_3MF_Native.cpp b/Source/Model/Writer/NMR_ModelWriter_3MF_Native.cpp new file mode 100644 index 0000000..7aea896 --- /dev/null +++ b/Source/Model/Writer/NMR_ModelWriter_3MF_Native.cpp @@ -0,0 +1,220 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelWriter_3MF_Native.cpp implements the platform independent 3MF Model Writer Class. +This model writer exports the in memory represenation into a 3MF file, +using LibZ and a native XML writer implementation. + + +--*/ + +#include "Model/Classes/NMR_KeyStoreResourceData.h" +#include "Model/Writer/NMR_ModelWriter_3MF_Native.h" +#include "Model/Classes/NMR_ModelConstants.h" +#include "Model/Classes/NMR_ModelAttachment.h" +#include "Model/Classes/NMR_ModelTextureAttachment.h" +#include "Common/Platform/NMR_ImportStream.h" +#include "Common/NMR_Exception.h" +#include "Common/Platform/NMR_XmlWriter.h" +#include "Common/Platform/NMR_XmlWriter_Native.h" +#include "Common/Platform/NMR_ImportStream_Unique_Memory.h" +#include "Common/Platform/NMR_ExportStream_Memory.h" +#include "Common/NMR_StringUtils.h" +#include "Common/3MF_ProgressMonitor.h" +#include "Common/NMR_ModelWarnings.h" +#include +#include + +namespace NMR { + + CModelWriter_3MF_Native::CModelWriter_3MF_Native(_In_ PModel pModel) : CModelWriter_3MF(pModel) + { + m_pOtherModel = nullptr; + } + + // These are OPC dependent functions + void CModelWriter_3MF_Native::createPackage(_In_ CModel * pModel) + { + __NMRASSERT(pModel != nullptr); + m_pOtherModel = pModel; + } + + void CModelWriter_3MF_Native::releasePackage() + { + m_pPackageWriter->close(); + m_pPackageWriter = nullptr; + m_pOtherModel = nullptr; + } + + void CModelWriter_3MF_Native::writePackageToStream(_In_ PExportStream pStream) + { + if (pStream.get() == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + if (m_pOtherModel == nullptr) + throw CNMRException(NMR_ERROR_NOMODELTOWRITE); + + // Maximal progress = NrResources + NrAttachments + Build + Cleanup + monitor()->SetMaxProgress(m_pOtherModel->getResourceCount() + m_pOtherModel->getAttachmentCount() + 1 + 1); + + // Write Model Stream + m_pPackageWriter = std::make_shared(pStream, *this); + POpcPackagePart pModelPart = m_pPackageWriter->addPart(m_pOtherModel->rootPath()); + PXmlWriter_Native pXMLWriter = std::make_shared(pModelPart->getExportStream()); + + monitor()->SetProgressIdentifier(ProgressIdentifier::PROGRESS_WRITEROOTMODEL); + monitor()->ReportProgressAndQueryCancelled(true); + + writeModelStream(pXMLWriter.get(), m_pOtherModel); + + // add Root relationships + m_pPackageWriter->addRootRelationship(PACKAGE_START_PART_RELATIONSHIP_TYPE, pModelPart.get()); + + PModelAttachment pPackageThumbnail = m_pOtherModel->getPackageThumbnail(); + if (pPackageThumbnail.get() != nullptr) + { + // create Package Thumbnail Part + POpcPackagePart pThumbnailPart = m_pPackageWriter->addPart(pPackageThumbnail->getPathURI()); + PExportStream pExportStream = pThumbnailPart->getExportStream(); + // Copy data + PImportStream pPackageThumbnailStream = pPackageThumbnail->getStream(); + pPackageThumbnailStream->seekPosition(0, true); + pExportStream->copyFrom(pPackageThumbnailStream.get(), pPackageThumbnailStream->retrieveSize(), MODELWRITER_NATIVE_BUFFERSIZE); + // add root relationship + m_pPackageWriter->addRootRelationship(pPackageThumbnail->getRelationShipType(), pThumbnailPart.get()); + } + + monitor()->SetProgressIdentifier(ProgressIdentifier::PROGRESS_WRITENONROOTMODELS); + monitor()->ReportProgressAndQueryCancelled(true); + + addNonRootModels(); + + // add Attachments + monitor()->SetProgressIdentifier(ProgressIdentifier::PROGRESS_WRITEATTACHMENTS); + monitor()->ReportProgressAndQueryCancelled(true); + + addAttachments(m_pOtherModel, pModelPart); + + monitor()->SetProgressIdentifier(ProgressIdentifier::PROGRESS_WRITECONTENTTYPES); + monitor()->ReportProgressAndQueryCancelled(true); + + // add Content Types + m_pPackageWriter->addContentType(PACKAGE_3D_RELS_EXTENSION, PACKAGE_3D_RELS_CONTENT_TYPE); + m_pPackageWriter->addContentType(PACKAGE_3D_MODEL_EXTENSION, PACKAGE_3D_MODEL_CONTENT_TYPE); + m_pPackageWriter->addContentType(PACKAGE_3D_TEXTURE_EXTENSION, PACKAGE_TEXTURE_CONTENT_TYPE); + m_pPackageWriter->addContentType(PACKAGE_3D_PNG_EXTENSION, PACKAGE_PNG_CONTENT_TYPE); + m_pPackageWriter->addContentType(PACKAGE_3D_JPEG_EXTENSION, PACKAGE_JPG_CONTENT_TYPE); + m_pPackageWriter->addContentType(PACKAGE_3D_JPG_EXTENSION, PACKAGE_JPG_CONTENT_TYPE); + + std::map CustomContentTypes = m_pOtherModel->getCustomContentTypes(); + std::map::iterator iContentTypeIterator; + + for (iContentTypeIterator = CustomContentTypes.begin(); iContentTypeIterator != CustomContentTypes.end(); iContentTypeIterator++) { + if (!m_pOtherModel->contentTypeIsDefault(iContentTypeIterator->first)) { + m_pPackageWriter->addContentType(iContentTypeIterator->first, iContentTypeIterator->second); + } + } + } + + void CModelWriter_3MF_Native::addNonRootModels() { + + // do this based on resource-paths + std::vector vctPPaths = m_pOtherModel->retrieveAllModelPaths(); + nfUint64 nCount = vctPPaths.size(); + + for (nfUint32 nIndex = 0; nIndex < nCount; nIndex++) { + monitor()->SetProgressIdentifier(ProgressIdentifier::PROGRESS_WRITENONROOTMODELS); + monitor()->ReportProgressAndQueryCancelled(true); + + std::string sNonRootModelPath = vctPPaths[nIndex]->getPath(); + if (sNonRootModelPath == m_pOtherModel->rootPath()) + continue; + + m_pOtherModel->setCurrentPath(sNonRootModelPath); + PImportStream pStream; + { + PExportStreamMemory pExportStream = std::make_shared(); + PXmlWriter_Native pXMLWriter = std::make_shared(pExportStream); + writeNonRootModelStream(pXMLWriter.get()); + + pStream = std::make_shared(pExportStream->getData(), pExportStream->getDataSize()); + } + + // check, whether this non-root model is already in here + PModelAttachment pNonRootModelAttachment = m_pOtherModel->findModelAttachment(sNonRootModelPath); + if (pNonRootModelAttachment.get() != nullptr) { + if (pNonRootModelAttachment->getRelationShipType() != PACKAGE_START_PART_RELATIONSHIP_TYPE) + warnings()->addWarning(NMR_ERROR_DUPLICATEATTACHMENTPATH, eModelWarningLevel::mrwFatal); + pNonRootModelAttachment->setStream(pStream); + } + else + pNonRootModelAttachment = m_pOtherModel->addAttachment(sNonRootModelPath, PACKAGE_START_PART_RELATIONSHIP_TYPE, pStream); + } + } + + void CModelWriter_3MF_Native::addAttachments(_In_ CModel * pModel, _In_ POpcPackagePart pModelPart) + { + __NMRASSERT(pModel != nullptr); + __NMRASSERT(pModelPart.get() != nullptr); + __NMRASSERT(pPackageWriter.get() != nullptr); + + nfUint32 nCount = pModel->getAttachmentCount(); + nfUint32 nIndex; + + if (nCount > 0) { + for (nIndex = 0; nIndex < nCount; nIndex++) { + + monitor()->SetProgressIdentifier(ProgressIdentifier::PROGRESS_WRITEATTACHMENTS); + monitor()->ReportProgressAndQueryCancelled(true); + + PModelAttachment pAttachment = pModel->getModelAttachment(nIndex); + PImportStream pStream = pAttachment->getStream(); + + std::string sPath = fnIncludeLeadingPathDelimiter(pAttachment->getPathURI()); + std::string sRelationShipType = pAttachment->getRelationShipType(); + + if (pStream.get() == nullptr) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + // create Attachment Part + POpcPackagePart pAttachmentPart = m_pPackageWriter->addPart(sPath); + PExportStream pExportStream = pAttachmentPart->getExportStream(); + + // Copy data + pStream->seekPosition(0, true); + pExportStream->copyFrom(pStream.get(), pStream->retrieveSize(), MODELWRITER_NATIVE_BUFFERSIZE); + + // add relationships + m_pPackageWriter->addPartRelationship(pModelPart, sRelationShipType.c_str(), pAttachmentPart.get()); + + m_pPackageWriter->addWriterSpecificRelationships(pModelPart, pAttachmentPart.get()); + + monitor()->IncrementProgress(1); + } + } + } +} diff --git a/Source/Model/Writer/NMR_ModelWriter_ColorMapping.cpp b/Source/Model/Writer/NMR_ModelWriter_ColorMapping.cpp new file mode 100644 index 0000000..f5b0e92 --- /dev/null +++ b/Source/Model/Writer/NMR_ModelWriter_ColorMapping.cpp @@ -0,0 +1,86 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelWriter_ColorMapping.cpp implements the Model Writer Color Mapping Class. + +--*/ + +#include "Model/Writer/NMR_ModelWriter_ColorMapping.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_Types.h" + +namespace NMR { + + CModelWriter_ColorMapping::CModelWriter_ColorMapping(_In_ ModelResourceID ResourceID) + { + m_nCurrentIndex = 0; + m_ResourceID = ResourceID; + } + + void CModelWriter_ColorMapping::registerColor(_In_ nfColor cColor) + { + auto iIterator = m_IndexMap.find(cColor); + if (iIterator == m_IndexMap.end()) { + m_IndexMap.insert(std::make_pair(cColor, m_nCurrentIndex)); + m_nCurrentIndex++; + m_ColorVector.push_back(cColor); + } + + } + + nfBool CModelWriter_ColorMapping::findColor(_In_ nfColor cColor, _Out_ ModelResourceIndex & nResourceIndex) + { + auto iIterator = m_IndexMap.find(cColor); + if (iIterator != m_IndexMap.end()) { + nResourceIndex = iIterator->second; + return true; + } + else { + nResourceIndex = 0; + return false; + } + + } + + nfUint32 CModelWriter_ColorMapping::getCount() + { + return (nfUint32)m_ColorVector.size(); + + } + nfColor CModelWriter_ColorMapping::getColor(_In_ nfUint32 nIndex) + { + return m_ColorVector[nIndex]; + } + + ModelResourceID CModelWriter_ColorMapping::getResourceID() + { + return m_ResourceID; + } + +} diff --git a/Source/Model/Writer/NMR_ModelWriter_STL.cpp b/Source/Model/Writer/NMR_ModelWriter_STL.cpp new file mode 100644 index 0000000..ddabdb8 --- /dev/null +++ b/Source/Model/Writer/NMR_ModelWriter_STL.cpp @@ -0,0 +1,62 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelWriter_STL.cpp implements the STL Model Writer Class. +A model writer exports the in memory representation into a binary STL file. + +--*/ + +#include "Model/Writer/NMR_ModelWriter_STL.h" +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/MeshExport/NMR_MeshExporter_STL.h" +#include + +namespace NMR { + + CModelWriter_STL::CModelWriter_STL(_In_ PModel pModel) : CModelWriter(pModel) + { + // empty on purpose + } + + void CModelWriter_STL::exportToStream(_In_ PExportStream pStream) + { + if (!pStream.get()) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + // Create Merged Mesh + PMesh pMesh = std::make_shared(); + model()->mergeToMesh(pMesh.get()); + + // Export Merged Mesh to STL + PMeshExporter pExporter = std::make_shared(pStream); + pExporter->exportMesh(pMesh.get(), nullptr); + } + +} diff --git a/Source/Model/Writer/NMR_ModelWriter_TexCoordMapping.cpp b/Source/Model/Writer/NMR_ModelWriter_TexCoordMapping.cpp new file mode 100644 index 0000000..2d8c7ad --- /dev/null +++ b/Source/Model/Writer/NMR_ModelWriter_TexCoordMapping.cpp @@ -0,0 +1,116 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelWriter_ColorMapping.cpp implements the Model Writer Color Mapping Class. + +--*/ + +#include "Model/Writer/NMR_ModelWriter_TexCoordMapping.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_Types.h" + +namespace NMR { + + bool operator< (_In_ const WRITERTEXCOORDMAPPINGTREEENTRY & entry1, _In_ const WRITERTEXCOORDMAPPINGTREEENTRY & entry2) + { + if (entry1.m_fU < entry2.m_fU) + return true; + if (entry1.m_fU > entry2.m_fU) + return false; + if (entry1.m_fV < entry2.m_fV) + return true; + return false; + } + + CModelWriter_TexCoordMapping::CModelWriter_TexCoordMapping(_In_ ModelResourceID ResourceID, _In_ ModelResourceID TextureID) + { + m_nCurrentIndex = 0; + m_ResourceID = ResourceID; + m_TextureID = TextureID; + } + + void CModelWriter_TexCoordMapping::registerTexCoords(_In_ nfFloat fU, _In_ nfFloat fV) + { + WRITERTEXCOORDMAPPINGTREEENTRY Entry; + Entry.m_fU = fU; + Entry.m_fV = fV; + + auto iIterator = m_IndexMap.find(Entry); + if (iIterator == m_IndexMap.end()) { + m_IndexMap.insert(std::make_pair(Entry, m_nCurrentIndex)); + m_TexCoordVector.push_back(Entry); + m_nCurrentIndex++; + } + + } + + nfBool CModelWriter_TexCoordMapping::findTexCoords(_In_ nfFloat fU, _In_ nfFloat fV, _Out_ ModelResourceIndex & nResourceIndex) + { + WRITERTEXCOORDMAPPINGTREEENTRY Entry; + Entry.m_fU = fU; + Entry.m_fV = fV; + + auto iIterator = m_IndexMap.find(Entry); + if (iIterator != m_IndexMap.end()) { + nResourceIndex = iIterator->second; + return true; + } + else { + nResourceIndex = 0; + return false; + } + + } + + ModelResourceID CModelWriter_TexCoordMapping::getResourceID() + { + return m_ResourceID; + } + + ModelResourceID CModelWriter_TexCoordMapping::getTextureID() + { + return m_TextureID; + } + + nfUint32 CModelWriter_TexCoordMapping::getCount() + { + return (nfUint32) m_TexCoordVector.size(); + + } + + void CModelWriter_TexCoordMapping::getTexCoords(_In_ nfUint32 nIndex, _Out_ nfFloat & fU, _Out_ nfFloat & fV) + { + WRITERTEXCOORDMAPPINGTREEENTRY Entry = m_TexCoordVector[nIndex]; + fU = Entry.m_fU; + fV = Entry.m_fV; + } + + + +} diff --git a/Source/Model/Writer/NMR_ModelWriter_TexCoordMappingContainer.cpp b/Source/Model/Writer/NMR_ModelWriter_TexCoordMappingContainer.cpp new file mode 100644 index 0000000..2e14dd3 --- /dev/null +++ b/Source/Model/Writer/NMR_ModelWriter_TexCoordMappingContainer.cpp @@ -0,0 +1,91 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelWriter_ColorMappingContainer.cpp implements the Model Writer Color Mapping Container Class. + +--*/ + +#include "Model/Writer/NMR_ModelWriter_TexCoordMappingContainer.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_Types.h" + +namespace NMR { + + + CModelWriter_TexCoordMappingContainer::CModelWriter_TexCoordMappingContainer() + { + + } + + CModelWriter_TexCoordMappingContainer::~CModelWriter_TexCoordMappingContainer() + { + + } + + nfBool CModelWriter_TexCoordMappingContainer::hasTexture(_In_ ModelResourceID nTextureID) + { + auto iIterator = m_TextureMappings.find(nTextureID); + return (iIterator != m_TextureMappings.end()); + } + + PModelWriter_TexCoordMapping CModelWriter_TexCoordMappingContainer::findTexture(_In_ ModelResourceID nTextureID) + { + auto iIterator = m_TextureMappings.find(nTextureID); + if (iIterator != m_TextureMappings.end()) { + return iIterator->second; + } + else { + return nullptr; + } + } + + PModelWriter_TexCoordMapping CModelWriter_TexCoordMappingContainer::addTexture(_In_ ModelResourceID nTextureID, _In_ ModelResourceID nResourceID) + { + if (hasTexture(nTextureID)) + throw CNMRException(NMR_ERROR_DUPLICATETEXTURE); + + PModelWriter_TexCoordMapping pTexture = std::make_shared(nResourceID, nTextureID); + m_TextureMappings.insert(std::make_pair(nTextureID, pTexture)); + m_TextureMappingVector.push_back(pTexture); + + return pTexture; + } + + nfUint32 CModelWriter_TexCoordMappingContainer::getCount() + { + return (nfUint32)m_TextureMappingVector.size(); + } + + PModelWriter_TexCoordMapping CModelWriter_TexCoordMappingContainer::getMapping(_In_ nfUint32 nIndex) + { + return m_TextureMappingVector[nIndex]; + } + +} + diff --git a/Source/Model/Writer/SecureContent101/NMR_ModelWriterNode_KeyStore.cpp b/Source/Model/Writer/SecureContent101/NMR_ModelWriterNode_KeyStore.cpp new file mode 100644 index 0000000..7bf7565 --- /dev/null +++ b/Source/Model/Writer/SecureContent101/NMR_ModelWriterNode_KeyStore.cpp @@ -0,0 +1,246 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelWriterNode_KeyStore.cpp implements the Model Writer KeyStore Node Class. +This is the class for exporting the 3mf keystore stream root node. + +--*/ + +#include "Model/Writer/SecureContent101/NMR_ModelWriterNode_KeyStore.h" +#include "Model/Classes/NMR_KeyStoreConsumer.h" +#include "Model/Classes/NMR_KeyStoreResourceData.h" +#include "Model/Classes/NMR_KeyStoreResourceDataGroup.h" +#include "Model/Classes/NMR_KeyStoreCEKParams.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_StringUtils.h" +#include "Common/NMR_UUID.h" +#include "Libraries/cpp-base64/base64.h" +#include +#include + + +void NMR::CModelWriterNode_KeyStore::writeConsumers() { + nfUint64 count = m_pKeyStore->getConsumerCount(); + for (nfUint64 nIndex = 0; nIndex < count; ++nIndex) { + PKeyStoreConsumer consumer = m_pKeyStore->getConsumer(nIndex); + m_consumerIndexes[consumer] = nIndex; + // + writeStartElement(XML_3MF_ELEMENT_CONSUMER); + //@consumerid + std::string consumerId = consumer->getConsumerID(); + if (consumerId.empty()) { + throw CNMRException(NMR_ERROR_KEYSTOREMISSINGCONSUMERID); + } + writeConstStringAttribute(XML_3MF_SECURE_CONTENT_CONSUMER_ID, consumerId.c_str()); + //@keyid + std::string keyId = consumer->getKeyID(); + if (!keyId.empty()) { + writeConstStringAttribute(XML_3MF_SECURE_CONTENT_KEY_ID, keyId.c_str()); + } + + std::string kvStr = consumer->getKeyValue(); + if (!kvStr.empty()) { + // + writeStartElement(XML_3MF_ELEMENT_KEYVALUE); + writeText(kvStr.c_str(), (nfUint32)kvStr.length()); + // + writeFullEndElement(); + } + + // + writeFullEndElement(); + } +} + +void NMR::CModelWriterNode_KeyStore::writeEncryptionAlgorithmAttribute(eKeyStoreEncryptAlgorithm ea) { + if (ea == eKeyStoreEncryptAlgorithm::AES256_GCM) { + writeConstStringAttribute(XML_3MF_SECURE_CONTENT_ENCRYPTION_ALGORITHM, XML_3MF_SECURE_CONTENT_ENCRYPTION_AES256); + } +} + +void NMR::CModelWriterNode_KeyStore::writeWrapAlgorithmAttribute(eKeyStoreWrapAlgorithm ea) { + if (ea == eKeyStoreWrapAlgorithm::RSA_OAEP) { + writeConstStringAttribute(XML_3MF_SECURE_CONTENT_WRAPPINGALGORITHM, XML_3MF_SECURE_CONTENT_KEYWRAPPING_RSASHORT); + } +} + +void NMR::CModelWriterNode_KeyStore::writeMgf(eKeyStoreMaskGenerationFunction mgf) { + std::string value; + switch (mgf) { + default: + case MGF1_SHA1: + value = XML_3MF_SECURE_CONTENT_MGF1_SHA1; + break; + case MGF1_SHA224: + value = XML_3MF_SECURE_CONTENT_MGF1_SHA224; + break; + case MGF1_SHA256: + value = XML_3MF_SECURE_CONTENT_MGF1_SHA256; + break; + case MGF1_SHA384: + value = XML_3MF_SECURE_CONTENT_MGF1_SHA384; + break; + case MGF1_SHA512: + value = XML_3MF_SECURE_CONTENT_MGF1_SHA512; + break; + } + writeConstStringAttribute(XML_3MF_SECURE_CONTENT_MGFALGORITHM, value.c_str()); +} + +void NMR::CModelWriterNode_KeyStore::writeDigest(eKeyStoreMessageDigest md) { + std::string value; + switch (md) { + default: + case SHA1: + value = XML_3MF_SECURE_CONTENT_MD_SHA1; + break; + case SHA256: + value = XML_3MF_SECURE_CONTENT_MD_SHA256; + break; + case SHA384: + value = XML_3MF_SECURE_CONTENT_MD_SHA384; + break; + case SHA512: + value = XML_3MF_SECURE_CONTENT_MD_SHA512; + break; + } + writeConstStringAttribute(XML_3MF_SECURE_CONTENT_DIGESTMETHOD, value.c_str()); +} + +void NMR::CModelWriterNode_KeyStore::writeResourceDatagroup() { + nfUint64 const count = m_pKeyStore->getResourceDataGroupCount(); + for (nfUint32 resourceIndex = 0; resourceIndex < count; ++resourceIndex) { + PKeyStoreResourceDataGroup resourcedatagroup = m_pKeyStore->getResourceDataGroup(resourceIndex); + // + writeStartElement(XML_3MF_ELEMENT_RESOURCEDATAGROUP); + // keyuuid - attribute + writeConstStringAttribute(XML_3MF_SECURE_CONTENT_KEY_UUID, resourcedatagroup->getKeyUUID()->toString().c_str()); + + nfUint64 const accessCount = resourcedatagroup->getAccessRightCount(); + for (nfUint64 accessIndex = 0; accessIndex < accessCount; ++accessIndex) { + PKeyStoreAccessRight ar = resourcedatagroup->getAccessRight(accessIndex); + writeAccessRight(ar); + } + + nfUint64 const resourceDataCount = m_pKeyStore->getResourceDataCount(); + for (nfUint32 rdIndex = 0; rdIndex < resourceDataCount; ++rdIndex) + { + PKeyStoreResourceData rd = m_pKeyStore->getResourceData(rdIndex); + if (rd->getGroup() == resourcedatagroup) { + writeResourceData(rd); + } + } + // + writeFullEndElement(); + } +} + +void NMR::CModelWriterNode_KeyStore::writeAccessRight(PKeyStoreAccessRight const & ar) { + // + writeStartElement(XML_3MF_ELEMENT_ACCESSRIGHT); + nfUint64 nIndex = m_consumerIndexes[ar->getConsumer()]; + // consumerindex - attribute + writeConstStringAttribute(XML_3MF_SECURE_CONTENT_CONSUMER_INDEX, fnUint32ToString((NMR::nfUint32)nIndex).c_str()); + + // + writeStartElement(XML_3MF_ELEMENT_KEKPARAMS); + // wrappingalgorithm - attribute + writeWrapAlgorithmAttribute(ar->getAlgorithm()); + // mgfalgorithm - attribute + writeMgf(ar->getMgf()); + // digestmethod - attribute + writeDigest(ar->getDigest()); + // + writeEndElement(); + + // + writeStartElement(XML_3MF_ELEMENT_CIPHERDATA); + // + writeStartElementWithPrefix(XML_3MF_ELEMENT_CIPHERVALUE, XML_3MF_NAMESPACEPREFIX_XENC); + std::string encodedCv = base64_encode(ar->getCipherValue()); + writeText(encodedCv.c_str(), (nfUint32)encodedCv.length()); + // + writeFullEndElement(); + // + writeFullEndElement(); + // + writeFullEndElement(); +} + +void NMR::CModelWriterNode_KeyStore::writeResourceData(PKeyStoreResourceData const & rd) { + // + writeStartElement(XML_3MF_ELEMENT_RESOURCEDATA); + // path - attribute + writeConstStringAttribute(XML_3MF_SECURE_CONTENT_PATH, rd->packagePath()->getPath().c_str()); + writeStartElement(XML_3MF_ELEMENT_CEKPARAMS); + // encryptionalgorithm - attribute + writeEncryptionAlgorithmAttribute(rd->getEncryptionAlgorithm()); + // compression - attribute + if (rd->isCompressed()) + writeConstStringAttribute(XML_3MF_SECURE_CONTENT_COMPRESSION, XML_3MF_SECURE_CONTENT_COMPRESSION_DEFLATE); + else + writeConstStringAttribute(XML_3MF_SECURE_CONTENT_COMPRESSION, XML_3MF_SECURE_CONTENT_COMPRESSION_NONE); + + std::vector const & iv = rd->getInitVector(); + if (!iv.empty()) { + writeStartElement(XML_3MF_SECURE_CONTENT_IV); + std::string encodedIv = base64_encode(iv); + writeText(encodedIv.c_str(), (nfUint32)encodedIv.length()); + writeFullEndElement(); + } + + std::vector const & tag = rd->getAuthTag(); + if (!tag.empty()) { + writeStartElement(XML_3MF_SECURE_CONTENT_TAG); + std::string encodedTag = base64_encode(tag); + writeText(encodedTag.c_str(), (nfUint32)encodedTag.length()); + writeFullEndElement(); + } + + std::vector const & aad = rd->getAddAuthData(); + if (!aad.empty()) { + writeStartElement(XML_3MF_SECURE_CONTENT_AAD); + std::string encodedAad = base64_encode(aad); + writeText(encodedAad.c_str(), (nfUint32)encodedAad.length()); + writeFullEndElement(); + } + // + writeFullEndElement(); + // + writeFullEndElement(); +} + +void NMR::CModelWriterNode_KeyStore::writeToXML() { + writeStartElementWithNamespace(XML_3MF_ELEMENT_KEYSTORE, XML_3MF_NAMESPACE_SECURECONTENTSPEC); + writeConstPrefixedStringAttribute(XML_3MF_ATTRIBUTE_XMLNS, XML_3MF_NAMESPACEPREFIX_XENC, XML_3MF_NAMESPACE_CIPHERVALUESPEC); + writeConstPrefixedStringAttribute(XML_3MF_ATTRIBUTE_XMLNS, XML_3MF_NAMESPACEPREFIX_DS, XML_3MF_NAMESPACE_DIGITALSIGNATURESPEC); + writeConstStringAttribute(XML_3MF_SECURE_CONTENT_UUID, m_pKeyStore->getUUID()->toString().c_str()); + writeConsumers(); + writeResourceDatagroup(); + writeFullEndElement(); +} \ No newline at end of file diff --git a/Source/Model/Writer/v100/NMR_ModelWriterNode100_Mesh.cpp b/Source/Model/Writer/v100/NMR_ModelWriterNode100_Mesh.cpp new file mode 100644 index 0000000..d25fb17 --- /dev/null +++ b/Source/Model/Writer/v100/NMR_ModelWriterNode100_Mesh.cpp @@ -0,0 +1,781 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelWriterNode100_Mesh.cpp implements the Model Writer Mesh Node Class. +This is the class for exporting the 3mf mesh node. + +--*/ + +#include "Model/Writer/v100/NMR_ModelWriterNode100_Mesh.h" +#include "Common/MeshInformation/NMR_MeshInformation_Properties.h" + +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_StringUtils.h" + +#include "Common/3MF_ProgressMonitor.h" + +#include + +#ifdef __GNUC__ +#include +#endif // __GNUC__ + +#define MAX(a,b) (((a)>(b))?(a):(b)) + +namespace NMR { + + CModelWriterNode100_Mesh::CModelWriterNode100_Mesh(_In_ CModelMeshObject * pModelMeshObject, _In_ CXmlWriter * pXMLWriter, _In_ PProgressMonitor pProgressMonitor, + _In_ PMeshInformation_PropertyIndexMapping pPropertyIndexMapping, _In_ int nPosAfterDecPoint, _In_ nfBool bWriteMaterialExtension, _In_ nfBool bWriteBeamLatticeExtension) + :CModelWriterNode_ModelBase(pModelMeshObject->getModel(), pXMLWriter, pProgressMonitor), m_nPosAfterDecPoint(nPosAfterDecPoint), m_nPutDoubleFactor((int)(pow(10, CModelWriterNode100_Mesh::m_nPosAfterDecPoint))) + { + __NMRASSERT(pModelMeshObject != nullptr); + if (!pPropertyIndexMapping.get()) + throw CNMRException(NMR_ERROR_INVALIDPARAM); + + m_bWriteMaterialExtension = bWriteMaterialExtension; + m_bWriteBeamLatticeExtension = bWriteBeamLatticeExtension; + + m_pModelMeshObject = pModelMeshObject; + m_pPropertyIndexMapping = pPropertyIndexMapping; + + // Initialize buffer arrays + m_nTriangleBufferPos = 0; + m_nVertexBufferPos = 0; + m_nBeamBufferPos = 0; + m_nBallBufferPos = 0; + m_nBeamRefBufferPos = 0; + m_nBallRefBufferPos = 0; + putVertexString(MODELWRITERMESH100_VERTEXLINESTART); + putTriangleString(MODELWRITERMESH100_TRIANGLELINESTART); + putBeamString(MODELWRITERMESH100_BEAMLATTICE_BEAMLINESTART); + putBallString(MODELWRITERMESH100_BEAMLATTICE_BALLLINESTART); + putBeamRefString(MODELWRITERMESH100_BEAMLATTICE_REFLINESTART); + putBallRefString(MODELWRITERMESH100_BEAMLATTICE_BALLREFLINESTART); + } + + bool stringRepresentationsDiffer(double a, double b, double putFactor) { + return fabs(a - b) * putFactor > 0.1; + } + + std::string capModeToString(eModelBeamLatticeCapMode eCapMode) { + switch (eCapMode) { + case eModelBeamLatticeCapMode::MODELBEAMLATTICECAPMODE_SPHERE: return XML_3MF_BEAMLATTICE_CAPMODE_SPHERE; break; + case eModelBeamLatticeCapMode::MODELBEAMLATTICECAPMODE_HEMISPHERE: return XML_3MF_BEAMLATTICE_CAPMODE_HEMISPHERE; break; + case eModelBeamLatticeCapMode::MODELBEAMLATTICECAPMODE_BUTT: return XML_3MF_BEAMLATTICE_CAPMODE_BUTT; break; + default: + return XML_3MF_BEAMLATTICE_CAPMODE_SPHERE; + } + } + + std::string clipModeToString(eModelBeamLatticeClipMode eClipMode) { + switch (eClipMode) { + case eModelBeamLatticeClipMode::MODELBEAMLATTICECLIPMODE_INSIDE: return XML_3MF_BEAMLATTICE_CLIPMODE_INSIDE; break; + case eModelBeamLatticeClipMode::MODELBEAMLATTICECLIPMODE_OUTSIDE: return XML_3MF_BEAMLATTICE_CLIPMODE_OUTSIDE; break; + case eModelBeamLatticeClipMode::MODELBEAMLATTICECLIPMODE_NONE: return XML_3MF_BEAMLATTICE_CLIPMODE_NONE; break; + default: + return XML_3MF_BEAMLATTICE_CLIPMODE_NONE; + } + } + + std::string ballModeToString(eModelBeamLatticeBallMode eBallMode) { + switch (eBallMode) { + case eModelBeamLatticeBallMode::MODELBEAMLATTICEBALLMODE_NONE: return XML_3MF_BEAMLATTICE_BALLMODE_NONE; break; + case eModelBeamLatticeBallMode::MODELBEAMLATTICEBALLMODE_MIXED: return XML_3MF_BEAMLATTICE_BALLMODE_MIXED; break; + case eModelBeamLatticeBallMode::MODELBEAMLATTICEBALLMODE_ALL: return XML_3MF_BEAMLATTICE_BALLMODE_ALL; break; + default: + return XML_3MF_BEAMLATTICE_BALLMODE_NONE; + } + } + + void CModelWriterNode100_Mesh::writeToXML() + { + __NMRASSERT(m_pXMLWriter); + __NMRASSERT(m_pModel); + + CMesh * pMesh = m_pModelMeshObject->getMesh(); + + const nfUint32 nNodeCount = pMesh->getNodeCount (); + const nfUint32 nFaceCount = pMesh->getFaceCount(); + const nfUint32 nBeamCount = pMesh->getBeamCount(); + const nfUint32 nBallCount = pMesh->getBallCount(); + nfUint32 nNodeIndex, nFaceIndex, nBeamIndex, nBallIndex; + + // Write Mesh Element + writeStartElement(XML_3MF_ELEMENT_MESH); + + m_pProgressMonitor->SetProgressIdentifier(ProgressIdentifier::PROGRESS_WRITENODES); + // Write Vertices + writeStartElement(XML_3MF_ELEMENT_VERTICES); + for (nNodeIndex = 0; nNodeIndex < nNodeCount; nNodeIndex++) { + // Get Mesh Node + MESHNODE * pMeshNode = pMesh->getNode(nNodeIndex); + writeVertexData(pMeshNode); + + /* The following works, but would be a major output speed bottleneck! + + // Write Vertex + writeStartElement(XML_3MF_ELEMENT_VERTEX); + writeFloatAttribute(XML_3MF_ATTRIBUTE_VERTEX_X, pMeshNode->m_position.m_values.x); + writeFloatAttribute(XML_3MF_ATTRIBUTE_VERTEX_Y, pMeshNode->m_position.m_values.y); + writeFloatAttribute(XML_3MF_ATTRIBUTE_VERTEX_Z, pMeshNode->m_position.m_values.z); + writeEndElement(); */ + + if (nNodeIndex % PROGRESS_NODEUPDATE == PROGRESS_NODEUPDATE-1) { + m_pProgressMonitor->ReportProgressAndQueryCancelled(true); + } + } + writeFullEndElement(); + + // Retrieve Mesh Informations + CMeshInformation_Properties * pProperties = NULL; + + UniqueResourceID nObjectLevelPropertyID = 0; + ModelResourceIndex nObjectLevelPropertyIndex = 0; + + CMeshInformationHandler * pMeshInformationHandler = pMesh->getMeshInformationHandler(); + if (pMeshInformationHandler) { + // Get generic property handler + CMeshInformation *pInformation = pMeshInformationHandler->getInformationByType(0, emiProperties); + if (pInformation) { + pProperties = dynamic_cast (pInformation); + NMR::MESHINFORMATION_PROPERTIES * pDefaultData = (NMR::MESHINFORMATION_PROPERTIES*)pProperties->getDefaultData(); + + if (pDefaultData && pDefaultData->m_nUniqueResourceID != 0) { + nObjectLevelPropertyID = pDefaultData->m_nUniqueResourceID; + nObjectLevelPropertyIndex = m_pPropertyIndexMapping->mapPropertyIDToIndex(nObjectLevelPropertyID, pDefaultData->m_nPropertyIDs[0]); + } + } + } + + bool bMeshHasAProperty = false; + + m_pProgressMonitor->SetProgressIdentifier(ProgressIdentifier::PROGRESS_WRITETRIANGLES); + // Write Triangles + writeStartElement(XML_3MF_ELEMENT_TRIANGLES); + for (nFaceIndex = 0; nFaceIndex < nFaceCount; nFaceIndex++) { + if (nFaceIndex % PROGRESS_TRIANGLEUPDATE == PROGRESS_TRIANGLEUPDATE - 1) { + m_pProgressMonitor->ReportProgressAndQueryCancelled(true); + } + + // Get Mesh Face + MESHFACE * pMeshFace = pMesh->getFace(nFaceIndex); + + UniqueResourceID nPropertyID = 0; + ModelResourceIndex nPropertyIndex1 = 0; + ModelResourceIndex nPropertyIndex2 = 0; + ModelResourceIndex nPropertyIndex3 = 0; + + nfChar * pAdditionalString = nullptr; + // Retrieve Property Indices + if (pProperties != nullptr) { + MESHINFORMATION_PROPERTIES* pFaceData = (MESHINFORMATION_PROPERTIES*)pProperties->getFaceData(nFaceIndex); + if (pFaceData != nullptr) { + if (pFaceData->m_nUniqueResourceID) { + nPropertyID = pFaceData->m_nUniqueResourceID; + nPropertyIndex1 = m_pPropertyIndexMapping->mapPropertyIDToIndex(nPropertyID, pFaceData->m_nPropertyIDs[0]); + nPropertyIndex2 = m_pPropertyIndexMapping->mapPropertyIDToIndex(nPropertyID, pFaceData->m_nPropertyIDs[1]); + nPropertyIndex3 = m_pPropertyIndexMapping->mapPropertyIDToIndex(nPropertyID, pFaceData->m_nPropertyIDs[2]); + } + } + } + + + if (nPropertyID != 0) { + bMeshHasAProperty = true; + // TODO: this is slow + ModelResourceID nPropertyModelResourceID = m_pModel->findPackageResourceID(nPropertyID)->getModelResourceID(); + if ((nPropertyIndex1 != nPropertyIndex2) || (nPropertyIndex1 != nPropertyIndex3)) { + writeFaceData_ThreeProperties(pMeshFace, nPropertyModelResourceID, nPropertyIndex1, nPropertyIndex2, nPropertyIndex3, pAdditionalString); + } + else { + if ((nPropertyID == nObjectLevelPropertyID) && (nPropertyIndex1 == nObjectLevelPropertyIndex)){ + writeFaceData_Plain(pMeshFace, pAdditionalString); + } else { + writeFaceData_OneProperty(pMeshFace, nPropertyModelResourceID, nPropertyIndex1, pAdditionalString); + } + } + } + else + { + writeFaceData_Plain(pMeshFace, pAdditionalString); + } + + /* The following works, but would be a major output speed bottleneck! + + // Write Triangle + writeStartElement(XML_3MF_ELEMENT_TRIANGLE); + writeIntAttribute(XML_3MF_ATTRIBUTE_TRIANGLE_V1, pMeshFace->m_nodeindices[0]); + writeIntAttribute(XML_3MF_ATTRIBUTE_TRIANGLE_V2, pMeshFace->m_nodeindices[1]); + writeIntAttribute(XML_3MF_ATTRIBUTE_TRIANGLE_V3, pMeshFace->m_nodeindices[2]); + + // Write Property Indices + if (nPropertyID != 0) { + writeIntAttribute(XML_3MF_ATTRIBUTE_TRIANGLE_PID, nPropertyID); + writeIntAttribute(XML_3MF_ATTRIBUTE_TRIANGLE_P1, nPropertyIndex1); + if ((nPropertyIndex1 != nPropertyIndex2) || (nPropertyIndex1 != nPropertyIndex3)) { + writeIntAttribute(XML_3MF_ATTRIBUTE_TRIANGLE_P2, nPropertyIndex2); + writeIntAttribute(XML_3MF_ATTRIBUTE_TRIANGLE_P3, nPropertyIndex3); + } + } + + writeEndElement(); */ + } + writeFullEndElement(); + + if (bMeshHasAProperty && !(nObjectLevelPropertyID != 0)) { + throw CNMRException(NMR_ERROR_MISSINGOBJECTLEVELPID); + } + + if (m_bWriteBeamLatticeExtension) { + if (nBeamCount > 0) { + // write beamlattice + writeStartElementWithPrefix(XML_3MF_ELEMENT_BEAMLATTICE, XML_3MF_NAMESPACEPREFIX_BEAMLATTICE); + nfDouble dDefaultRadius = pMesh->getDefaultBeamRadius(); + nfDouble dDefaultBallRadius = pMesh->getDefaultBallRadius(); + nfBool bWriteBallsElement = nBallCount > 0; + writeFloatAttribute(XML_3MF_ATTRIBUTE_BEAMLATTICE_RADIUS, float(dDefaultRadius)); + writeFloatAttribute(XML_3MF_ATTRIBUTE_BEAMLATTICE_MINLENGTH, float(pMesh->getBeamLatticeMinLength())); + eModelBeamLatticeBallMode eBallMode = pMesh->getBeamLatticeBallMode(); + + if (eBallMode == eModelBeamLatticeBallMode::MODELBEAMLATTICEBALLMODE_ALL) { + if (dDefaultBallRadius > 0) { + writeStringAttribute(XML_3MF_ATTRIBUTE_BEAMLATTICE_BALLMODE, ballModeToString(eBallMode)); + writeFloatAttribute(XML_3MF_ATTRIBUTE_BEAMLATTICE_BALLRADIUS, float(dDefaultBallRadius)); + + // Check if any balls do not use dDefaultBallRadius + bWriteBallsElement = false; + for (nfUint32 iBall = 0; iBall < nBallCount; iBall++) { + if (stringRepresentationsDiffer(pMesh->getBall(iBall)->m_radius, dDefaultBallRadius, m_nPutDoubleFactor)) { + bWriteBallsElement = true; + break; + } + } + } + else { + throw CNMRException(NMR_ERROR_BEAMLATTICEINVALIDATTRIBUTE); + } + } + else if (nBallCount > 0) { + if (eBallMode == eModelBeamLatticeBallMode::MODELBEAMLATTICEBALLMODE_MIXED) { + if (dDefaultBallRadius > 0) { + writeStringAttribute(XML_3MF_ATTRIBUTE_BEAMLATTICE_BALLMODE, ballModeToString(eBallMode)); + writeFloatAttribute(XML_3MF_ATTRIBUTE_BEAMLATTICE_BALLRADIUS, float(dDefaultBallRadius)); + } + else { + throw CNMRException(NMR_ERROR_BEAMLATTICEINVALIDATTRIBUTE); + } + } + } + + if (m_pModelMeshObject->getBeamLatticeAttributes()->m_bHasClippingMeshID) { + writeStringAttribute(XML_3MF_ATTRIBUTE_BEAMLATTICE_CLIPPINGMODE, clipModeToString(m_pModelMeshObject->getBeamLatticeAttributes()->m_eClipMode)); + PPackageResourceID pID = m_pModelMeshObject->getBeamLatticeAttributes()->m_pClippingMeshUniqueID; + if (pID->getPath() != m_pModel->currentPath()) + throw CNMRException(NMR_ERROR_MODELRESOURCE_IN_DIFFERENT_MODEL); + writeIntAttribute(XML_3MF_ATTRIBUTE_BEAMLATTICE_CLIPPINGMESH, pID->getModelResourceID()); + } + + if (m_pModelMeshObject->getBeamLatticeAttributes()->m_bHasRepresentationMeshID) { + PPackageResourceID pID = m_pModelMeshObject->getBeamLatticeAttributes()->m_pRepresentationUniqueID; + if (pID->getPath() != m_pModel->currentPath()) + throw CNMRException(NMR_ERROR_MODELRESOURCE_IN_DIFFERENT_MODEL); + writeIntAttribute(XML_3MF_ATTRIBUTE_BEAMLATTICE_REPRESENTATIONMESH, pID->getModelResourceID()); + } + + eModelBeamLatticeCapMode eDefaultCapMode = pMesh->getBeamLatticeCapMode(); + writeConstStringAttribute(XML_3MF_ATTRIBUTE_BEAMLATTICE_CAPMODE, capModeToString(eDefaultCapMode).c_str()); + { + // write beamlattice: beams + writeStartElementWithPrefix(XML_3MF_ELEMENT_BEAMS, XML_3MF_NAMESPACEPREFIX_BEAMLATTICE); + for (nBeamIndex = 0; nBeamIndex < nBeamCount; nBeamIndex++) { + // write beamlattice: beam + MESHBEAM * pMeshBeam = pMesh->getBeam(nBeamIndex); + writeBeamData(pMeshBeam, dDefaultRadius, eDefaultCapMode); + } + writeFullEndElement(); + + // write beamlattice: balls + // Only if there is at least 1 ball + if (bWriteBallsElement) { + writeStartElementWithPrefix(XML_3MF_ELEMENT_BALLS, XML_3MF_NAMESPACEPREFIX_BEAMLATTICE); + for (nBallIndex = 0; nBallIndex < nBallCount; nBallIndex++) { + // write beamlattice: ball + MESHBALL * pMeshBall = pMesh->getBall(nBallIndex); + writeBallData(pMeshBall, eBallMode, dDefaultBallRadius); + } + writeFullEndElement(); + } + + const nfUint32 nBeamSetCount = pMesh->getBeamSetCount(); + if (nBeamSetCount > 0) { + // write beamlattice: beamsets + writeStartElementWithPrefix(XML_3MF_ELEMENT_BEAMSETS, XML_3MF_NAMESPACEPREFIX_BEAMLATTICE); + for (nfUint32 nBeamSetIndex = 0; nBeamSetIndex < nBeamSetCount; nBeamSetIndex++) { + const PBEAMSET pBeamSet = pMesh->getBeamSet(nBeamSetIndex); + { + // write beamlattice: beamset + writeStartElementWithPrefix(XML_3MF_ELEMENT_BEAMSET, XML_3MF_NAMESPACEPREFIX_BEAMLATTICE); + if (pBeamSet->m_sName.length()>0) + writeConstStringAttribute(XML_3MF_ATTRIBUTE_BEAMLATTICE_NAME, pBeamSet->m_sName.c_str()); + if (pBeamSet->m_sIdentifier.length()>0) + writeConstStringAttribute(XML_3MF_ATTRIBUTE_BEAMLATTICE_IDENTIFIER, pBeamSet->m_sIdentifier.c_str()); + const nfUint32 nRefCount = (nfUint32)pBeamSet->m_Refs.size(); + for (nfUint32 nRefIndex = 0; nRefIndex < nRefCount; nRefIndex++) { + // write beamlattice: ref + writeRefData(pBeamSet->m_Refs[nRefIndex]); + } + const nfUint32 nBallRefCount = (nfUint32)pBeamSet->m_BallRefs.size(); + for (nfUint32 nBallRefIndex = 0; nBallRefIndex < nBallRefCount; nBallRefIndex++) { + // write beamlattice: ballref + writeBallRefData(pBeamSet->m_BallRefs[nBallRefIndex]); + } + writeFullEndElement(); + } + } + writeFullEndElement(); + } + } + writeFullEndElement(); + } + } + + // Finish Mesh Element + writeFullEndElement(); + } + + + void CModelWriterNode100_Mesh::putVertexString(_In_ const nfChar * pszString) + { + __NMRASSERT(pszString); + const nfChar * pChar = pszString; + nfChar * pTarget = &m_VertexLine[m_nVertexBufferPos]; + + while (*pChar != 0) { + *pTarget = *pChar; + pTarget++; + pChar++; + m_nVertexBufferPos++; + } + } + + void CModelWriterNode100_Mesh::putFloat(_In_ const nfFloat fValue, _In_ std::array & line, _In_ nfUint32 & nBufferPos) { + // Format float with "%.$ACCf" syntax where $ACC = m_snPosAfterDecPoint + nfInt64 nAbsValue = (nfInt64)(fValue * m_nPutDoubleFactor); + nAbsValue = MAX(nAbsValue, -nAbsValue); + nfBool bIsNegative = fValue < 0; + + int nStart = nBufferPos; + int nCount = 0; + + if (!nAbsValue) { + line[nBufferPos++] = '0'; + } + else { + // Write the string in reverse order + while (nAbsValue || nCount < m_nPosAfterDecPoint) { + line[nBufferPos++] = '0' + (nAbsValue % 10); + nAbsValue /= 10; + nCount++; + if (nCount == m_nPosAfterDecPoint) { + line[nBufferPos++] = '.'; + if (!nAbsValue) { + line[nBufferPos++] = '0'; + } + nCount++; + } + } + if (bIsNegative) { + line[nBufferPos++] = '-'; + nCount++; + } + } + + // Reverse the float string + int nEnd = nBufferPos - 1; + while (nStart < nEnd) { + char temp = line[nStart]; + line[nStart] = line[nEnd]; + line[nEnd] = temp; + nStart++; + nEnd--; + } + } + + void CModelWriterNode100_Mesh::putDouble(_In_ const nfDouble dValue, _In_ std::array & line, _In_ nfUint32 & nBufferPos) { + // Format float with "%.$ACCf" syntax where $ACC = m_snPosAfterDecPoint + nfInt64 nAbsValue = (nfInt64)(dValue * m_nPutDoubleFactor); + nAbsValue = MAX(nAbsValue, -nAbsValue); + nfBool bIsNegative = dValue < 0; + + int nStart = nBufferPos; + int nCount = 0; + + if (!nAbsValue) { + line[nBufferPos++] = '0'; + } + else { + // Write the string in reverse order + while (nAbsValue || nCount < m_nPosAfterDecPoint) { + line[nBufferPos++] = '0' + (nAbsValue % 10); + nAbsValue /= 10; + nCount++; + if (nCount == m_nPosAfterDecPoint) { + line[nBufferPos++] = '.'; + if (!nAbsValue) { + line[nBufferPos++] = '0'; + } + nCount++; + } + } + if (bIsNegative) { + line[nBufferPos++] = '-'; + nCount++; + } + } + + // Reverse the float string + int nEnd = nBufferPos - 1; + while (nStart < nEnd) { + char temp = line[nStart]; + line[nStart] = line[nEnd]; + line[nEnd] = temp; + nStart++; + nEnd--; + } + } + + void CModelWriterNode100_Mesh::putVertexFloat(_In_ const nfFloat fValue) + { + putFloat(fValue, m_VertexLine, m_nVertexBufferPos); + } + + + void CModelWriterNode100_Mesh::putTriangleString(_In_ const nfChar * pszString) + { + __NMRASSERT(pszString); + const nfChar * pChar = pszString; + nfChar * pTarget = &m_TriangleLine[m_nTriangleBufferPos]; + + while (*pChar != 0) { + *pTarget = *pChar; + pTarget++; + pChar++; + m_nTriangleBufferPos++; + } + } + + void CModelWriterNode100_Mesh::putTriangleUInt32(_In_ const nfUint32 nValue) + { + +#ifdef __GNUC__ + int nCount = sprintf(&m_TriangleLine[m_nTriangleBufferPos], "%d", nValue); +#else + int nCount = sprintf_s(&m_TriangleLine[m_nTriangleBufferPos], MODELWRITERMESH100_LINEBUFFERSIZE - m_nTriangleBufferPos, "%d", nValue); +#endif // __GNUC__ + + if (nCount < 1) + throw CNMRException(NMR_ERROR_COULDNOTCONVERTNUMBER); + m_nTriangleBufferPos += nCount; + } + + + void CModelWriterNode100_Mesh::putBeamString(_In_ const nfChar * pszString) + { + __NMRASSERT(pszString); + const nfChar * pChar = pszString; + nfChar * pTarget = &m_BeamLine[m_nBeamBufferPos]; + + while (*pChar != 0) { + *pTarget = *pChar; + pTarget++; + pChar++; + m_nBeamBufferPos++; + } + } + + void CModelWriterNode100_Mesh::putBeamUInt32(_In_ const nfUint32 nValue) + { +#ifdef __GNUC__ + int nCount = sprintf(&m_BeamLine[m_nBeamBufferPos], "%d", nValue); +#else + int nCount = sprintf_s(&m_BeamLine[m_nBeamBufferPos], MODELWRITERMESH100_LINEBUFFERSIZE - m_nBeamBufferPos, "%d", nValue); +#endif // __GNUC__ + + if (nCount < 1) + throw CNMRException(NMR_ERROR_COULDNOTCONVERTNUMBER); + m_nBeamBufferPos += nCount; + } + + void CModelWriterNode100_Mesh::putBeamDouble(_In_ const nfDouble dValue) + { + putDouble(dValue, m_BeamLine, m_nBeamBufferPos); + } + + void CModelWriterNode100_Mesh::putBallString(_In_ const nfChar * pszString) + { + __NMRASSERT(pszString); + const nfChar * pChar = pszString; + nfChar * pTarget = &m_BallLine[m_nBallBufferPos]; + + while (*pChar != 0) { + *pTarget = *pChar; + pTarget++; + pChar++; + m_nBallBufferPos++; + } + } + + void CModelWriterNode100_Mesh::putBallUInt32(_In_ const nfUint32 nValue) + { +#ifdef __GNUC__ + int nCount = sprintf(&m_BallLine[m_nBallBufferPos], "%d", nValue); +#else + int nCount = sprintf_s(&m_BallLine[m_nBallBufferPos], MODELWRITERMESH100_LINEBUFFERSIZE - m_nBallBufferPos, "%d", nValue); +#endif // __GNUC__ + + if (nCount < 1) + throw CNMRException(NMR_ERROR_COULDNOTCONVERTNUMBER); + m_nBallBufferPos += nCount; + } + + void CModelWriterNode100_Mesh::putBallDouble(_In_ const nfDouble dValue) + { + putDouble(dValue, m_BallLine, m_nBallBufferPos); + } + + void CModelWriterNode100_Mesh::putBeamRefString(_In_ const nfChar * pszString) + { + __NMRASSERT(pszString); + const nfChar * pChar = pszString; + nfChar * pTarget = &m_BeamRefLine[m_nBeamRefBufferPos]; + + while (*pChar != 0) { + *pTarget = *pChar; + pTarget++; + pChar++; + m_nBeamRefBufferPos++; + } + } + + void CModelWriterNode100_Mesh::putBeamRefUInt32(_In_ const nfUint32 nValue) + { +#ifdef __GNUC__ + int nCount = sprintf(&m_BeamRefLine[m_nBeamRefBufferPos], "%d", nValue); +#else + int nCount = sprintf_s(&m_BeamRefLine[m_nBeamRefBufferPos], MODELWRITERMESH100_LINEBUFFERSIZE - m_nBeamRefBufferPos, "%d", nValue); +#endif // __GNUC__ + + if (nCount < 1) + throw CNMRException(NMR_ERROR_COULDNOTCONVERTNUMBER); + m_nBeamRefBufferPos += nCount; + } + + void CModelWriterNode100_Mesh::putBallRefString(_In_ const nfChar* pszString) + { + __NMRASSERT(pszString); + const nfChar * pChar = pszString; + nfChar * pTarget = &m_BallRefLine[m_nBallRefBufferPos]; + + while (*pChar != 0) { + *pTarget = *pChar; + pTarget++; + pChar++; + m_nBallRefBufferPos++; + } + } + + void CModelWriterNode100_Mesh::putBallRefUInt32(_In_ const nfUint32 nValue) + { +#ifdef __GNUC__ + int nCount = sprintf(&m_BallRefLine[m_nBallRefBufferPos], "%d", nValue); +#else + int nCount = sprintf_s(&m_BallRefLine[m_nBallRefBufferPos], MODELWRITERMESH100_LINEBUFFERSIZE - m_nBallRefBufferPos, "%d", nValue); +#endif // __GNUC__ + + if (nCount < 1) + throw CNMRException(NMR_ERROR_COULDNOTCONVERTNUMBER); + m_nBallRefBufferPos += nCount; + } + + void CModelWriterNode100_Mesh::writeVertexData(_In_ MESHNODE * pNode) + { + __NMRASSERT(pNode); + m_nVertexBufferPos = MODELWRITERMESH100_VERTEXLINESTARTLENGTH; + putVertexFloat(pNode->m_position.m_values.x); + putVertexString("\" y=\""); + putVertexFloat(pNode->m_position.m_values.y); + putVertexString("\" z=\""); + putVertexFloat(pNode->m_position.m_values.z); + putVertexString("\" />"); + + m_pXMLWriter->WriteRawLine(&m_VertexLine[0], m_nVertexBufferPos); + } + + void CModelWriterNode100_Mesh::writeFaceData_Plain(_In_ MESHFACE * pFace, _In_opt_ const nfChar * pszAdditionalString) + { + __NMRASSERT(pFace); + m_nTriangleBufferPos = MODELWRITERMESH100_TRIANGLELINESTARTLENGTH; + putTriangleUInt32(pFace->m_nodeindices[0]); + putTriangleString("\" v2=\""); + putTriangleUInt32(pFace->m_nodeindices[1]); + putTriangleString("\" v3=\""); + putTriangleUInt32(pFace->m_nodeindices[2]); + putTriangleString("\""); + if (pszAdditionalString) { + putTriangleString(pszAdditionalString); + } + putTriangleString(" />"); + m_pXMLWriter->WriteRawLine(&m_TriangleLine[0], m_nTriangleBufferPos); + } + + void CModelWriterNode100_Mesh::writeFaceData_OneProperty(_In_ MESHFACE * pFace, _In_ const ModelResourceID nPropertyID, _In_ const ModelResourceIndex nPropertyIndex, _In_opt_ const nfChar * pszAdditionalString) + { + __NMRASSERT(pFace); + m_nTriangleBufferPos = MODELWRITERMESH100_TRIANGLELINESTARTLENGTH; + putTriangleUInt32(pFace->m_nodeindices[0]); + putTriangleString("\" v2=\""); + putTriangleUInt32(pFace->m_nodeindices[1]); + putTriangleString("\" v3=\""); + putTriangleUInt32(pFace->m_nodeindices[2]); + if (nPropertyID != 0) { + putTriangleString("\" pid=\""); + putTriangleUInt32(nPropertyID); + } + putTriangleString("\" p1=\""); + putTriangleUInt32(nPropertyIndex); + putTriangleString("\""); + if (pszAdditionalString) { + putTriangleString(pszAdditionalString); + } + putTriangleString(" />"); + m_pXMLWriter->WriteRawLine(&m_TriangleLine[0], m_nTriangleBufferPos); + } + + void CModelWriterNode100_Mesh::writeFaceData_ThreeProperties(_In_ MESHFACE * pFace, _In_ const ModelResourceID nPropertyID, _In_ const ModelResourceIndex nPropertyIndex1, _In_ const ModelResourceIndex nPropertyIndex2, _In_ const ModelResourceIndex nPropertyIndex3, _In_opt_ const nfChar * pszAdditionalString) + { + __NMRASSERT(pFace); + m_nTriangleBufferPos = MODELWRITERMESH100_TRIANGLELINESTARTLENGTH; + putTriangleUInt32(pFace->m_nodeindices[0]); + putTriangleString("\" v2=\""); + putTriangleUInt32(pFace->m_nodeindices[1]); + putTriangleString("\" v3=\""); + putTriangleUInt32(pFace->m_nodeindices[2]); + if (nPropertyID != 0) { + putTriangleString("\" pid=\""); + putTriangleUInt32(nPropertyID); + } + putTriangleString("\" p1=\""); + putTriangleUInt32(nPropertyIndex1); + putTriangleString("\" p2=\""); + putTriangleUInt32(nPropertyIndex2); + putTriangleString("\" p3=\""); + putTriangleUInt32(nPropertyIndex3); + putTriangleString("\""); + if (pszAdditionalString) { + putTriangleString(pszAdditionalString); + } + putTriangleString(" />"); + m_pXMLWriter->WriteRawLine(&m_TriangleLine[0], m_nTriangleBufferPos); + } + + __NMR_INLINE void CModelWriterNode100_Mesh::writeBeamData(_In_ MESHBEAM * pBeam, _In_ nfDouble dRadius, _In_ eModelBeamLatticeCapMode eDefaultCapMode) + { + __NMRASSERT(pBeam); + m_nBeamBufferPos = MODELWRITERMESH100_BEAMLATTICE_BEAMSTARTLENGTH; + putBeamUInt32(pBeam->m_nodeindices[0]); + const std::string sV2 = "\" " + std::string(XML_3MF_ATTRIBUTE_BEAMLATTICE_V2) + "=\""; + putBeamString(sV2.c_str()); + putBeamUInt32(pBeam->m_nodeindices[1]); + + nfBool bWriteR2 = stringRepresentationsDiffer(pBeam->m_radius[0], pBeam->m_radius[1], m_nPutDoubleFactor); + nfBool bWriteR1 = bWriteR2 || stringRepresentationsDiffer(pBeam->m_radius[0], dRadius, m_nPutDoubleFactor); + if (bWriteR1) { + const std::string sR1 = "\" " + std::string(XML_3MF_ATTRIBUTE_BEAMLATTICE_R1) + "=\""; + putBeamString(sR1.c_str()); + putBeamDouble(pBeam->m_radius[0]); + } + if (bWriteR2) { + const std::string sR2 = "\" " + std::string(XML_3MF_ATTRIBUTE_BEAMLATTICE_R2) + "=\""; + putBeamString(sR2.c_str()); + putBeamDouble(pBeam->m_radius[1]); + } + + if ( eDefaultCapMode != pBeam->m_capMode[0] ) { + const std::string sCap1 = "\" " + std::string(XML_3MF_ATTRIBUTE_BEAMLATTICE_CAP1) + "=\"" + + capModeToString(eModelBeamLatticeCapMode(pBeam->m_capMode[0])); + putBeamString(sCap1.c_str()); + } + if (eDefaultCapMode != pBeam->m_capMode[1]) { + const std::string sCap2 = "\" " + std::string(XML_3MF_ATTRIBUTE_BEAMLATTICE_CAP2) + "=\"" + + capModeToString(eModelBeamLatticeCapMode(pBeam->m_capMode[1])); + putBeamString(sCap2.c_str()); + } + + putBeamString("\"/>"); + m_pXMLWriter->WriteRawLine(&m_BeamLine[0], m_nBeamBufferPos); + } + + __NMR_INLINE void CModelWriterNode100_Mesh::writeBallData(_In_ MESHBALL* pBall, _In_ eModelBeamLatticeBallMode eBallMode, _In_ nfDouble dRadius) + { + __NMRASSERT(pBall); + + nfBool bWriteR = stringRepresentationsDiffer(pBall->m_radius, dRadius, m_nPutDoubleFactor); + if (!bWriteR && eBallMode == eModelBeamLatticeBallMode::MODELBEAMLATTICEBALLMODE_ALL) { + return; + } + + m_nBallBufferPos = MODELWRITERMESH100_BEAMLATTICE_BALLSTARTLENGTH; + putBallUInt32(pBall->m_nodeindex); + if (bWriteR) { + const std::string sR = "\" " + std::string(XML_3MF_ATTRIBUTE_BEAMLATTICE_BALL_R) + "=\""; + putBallString(sR.c_str()); + putBallDouble(pBall->m_radius); + } + + putBallString("\"/>"); + m_pXMLWriter->WriteRawLine(&m_BallLine[0], m_nBallBufferPos); + } + + __NMR_INLINE void CModelWriterNode100_Mesh::writeRefData(_In_ INT nRefID) + { + m_nBeamRefBufferPos = MODELWRITERMESH100_BEAMLATTICE_REFSTARTLENGTH; + putBeamRefUInt32(nRefID); + putBeamRefString("\"/>"); + m_pXMLWriter->WriteRawLine(&m_BeamRefLine[0], m_nBeamRefBufferPos); + } + + __NMR_INLINE void CModelWriterNode100_Mesh::writeBallRefData(_In_ INT nBallRefID) + { + m_nBallRefBufferPos = MODELWRITERMESH100_BEAMLATTICE_BALLREFSTARTLENGTH; + putBallRefUInt32(nBallRefID); + putBallRefString("\"/>"); + m_pXMLWriter->WriteRawLine(&m_BallRefLine[0], m_nBallRefBufferPos); + } + +} diff --git a/Source/Model/Writer/v100/NMR_ModelWriterNode100_Model.cpp b/Source/Model/Writer/v100/NMR_ModelWriterNode100_Model.cpp new file mode 100644 index 0000000..fdf97fa --- /dev/null +++ b/Source/Model/Writer/v100/NMR_ModelWriterNode100_Model.cpp @@ -0,0 +1,887 @@ +/*++ + +Copyright (C) 2019 3MF Consortium + +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. + +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 HOLDER 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. + +Abstract: + +NMR_ModelWriterNode100_Model.cpp implements the Model Writer Model Node Class. +This is the class for exporting the 3mf model stream root node. + +--*/ + +#include "Model/Writer/v100/NMR_ModelWriterNode100_Mesh.h" +#include "Model/Writer/v100/NMR_ModelWriterNode100_Model.h" + +#include "Model/Classes/NMR_ModelAttachment.h" +#include "Model/Classes/NMR_ModelBuildItem.h" +#include "Model/Classes/NMR_ModelObject.h" +#include "Model/Classes/NMR_ModelBaseMaterials.h" +#include "Model/Classes/NMR_ModelColorGroup.h" +#include "Model/Classes/NMR_ModelTexture2D.h" +#include "Model/Classes/NMR_ModelTexture2DGroup.h" +#include "Model/Classes/NMR_ModelCompositeMaterials.h" +#include "Model/Classes/NMR_ModelMultiPropertyGroup.h" +#include "Model/Classes/NMR_ModelMeshObject.h" +#include "Model/Classes/NMR_ModelComponentsObject.h" +#include "Model/Classes/NMR_Model.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_StringUtils.h" +#include "Common/MeshInformation/NMR_MeshInformation_Properties.h" +#include "Model/Classes/NMR_ModelConstants_Slices.h" + +#include "Common/3MF_ProgressMonitor.h" + + +namespace NMR { + + CModelWriterNode100_Model::CModelWriterNode100_Model(_In_ CModel * pModel, _In_ CXmlWriter * pXMLWriter, _In_ PProgressMonitor pProgressMonitor, + _In_ nfUint32 nDecimalPrecision, nfBool bWritesRootModel) : CModelWriterNode_ModelBase(pModel, pXMLWriter, pProgressMonitor), m_nDecimalPrecision(nDecimalPrecision) + { + m_pPropertyIndexMapping = std::make_shared(); + m_bIsRootModel = bWritesRootModel; + + m_bWriteMaterialExtension = true; + m_bWriteProductionExtension = true; + m_bWriteBeamLatticeExtension = true; + m_bWriteSliceExtension = true; + m_bWriteSecureContentExtension = true; + m_bWriteBaseMaterials = true; + m_bWriteObjects = true; + + m_bWriteCustomNamespaces = true; + + // register custom NameSpaces from metadata in objects, build items and the model itself + RegisterMetaDataNameSpaces(); + } + + void CModelWriterNode100_Model::RegisterMetaDataGroupNameSpaces(PModelMetaDataGroup mdg) + { + for (nfUint32 i = 0; i < mdg->getMetaDataCount(); i++) + { + PModelMetaData md = mdg->getMetaData(i); + if (!md->getNameSpace().empty()) { + std::string prefix = "customXMLNS" + std::to_string(m_pXMLWriter->GetNamespaceCount()); + std::string sDummy; + if (!m_pXMLWriter->GetNamespacePrefix(md->getNameSpace(), sDummy)) { + m_pXMLWriter->RegisterCustomNameSpace(md->getNameSpace(), prefix); + } + } + } + } + + void CModelWriterNode100_Model::RegisterMetaDataNameSpaces() + { + RegisterMetaDataGroupNameSpaces(m_pModel->getMetaDataGroup()); + + nfInt32 nObjectCount = m_pModel->getObjectCount(); + for (nfInt32 nObjectIndex = 0; nObjectIndex < nObjectCount; nObjectIndex++) { + PModelResource pResource = m_pModel->getObjectResource(nObjectIndex); + CModelObject * pObject = dynamic_cast (pResource.get()); + if (pObject) { + RegisterMetaDataGroupNameSpaces(pObject->metaDataGroup()); + } + } + + nfInt32 nOBuildItemCount = m_pModel->getBuildItemCount(); + for (nfInt32 nBuildItemIndex = 0; nBuildItemIndex < nOBuildItemCount; nBuildItemIndex++) { + PModelBuildItem pBuildItem = m_pModel->getBuildItem(nBuildItemIndex); + RegisterMetaDataGroupNameSpaces(pBuildItem->metaDataGroup()); + } + } + + void CModelWriterNode100_Model::writeToXML() + { + std::string sLanguage = m_pModel->getLanguage(); + + writeStartElementWithNamespace(XML_3MF_ELEMENT_MODEL, PACKAGE_XMLNS_100); + + writeStringAttribute(XML_3MF_ATTRIBUTE_MODEL_UNIT, m_pModel->getUnitString()); + writeConstPrefixedStringAttribute(XML_3MF_ATTRIBUTE_PREFIX_XML, XML_3MF_ATTRIBUTE_MODEL_LANG, sLanguage.c_str()); + + std::string sRequiredExtensions = ""; + if (m_bWriteMaterialExtension) { + writeConstPrefixedStringAttribute(XML_3MF_ATTRIBUTE_XMLNS, XML_3MF_NAMESPACEPREFIX_MATERIAL, XML_3MF_NAMESPACE_MATERIALSPEC); + } + if (m_bWriteProductionExtension) { + writeConstPrefixedStringAttribute(XML_3MF_ATTRIBUTE_XMLNS, XML_3MF_NAMESPACEPREFIX_PRODUCTION, XML_3MF_NAMESPACE_PRODUCTIONSPEC); + if (m_pModel->RequireExtension(XML_3MF_NAMESPACEPREFIX_PRODUCTION)) { + if (sRequiredExtensions.size() > 0) + sRequiredExtensions = sRequiredExtensions + " "; + sRequiredExtensions = sRequiredExtensions + XML_3MF_NAMESPACE_PRODUCTIONSPEC; + } + } + if (m_bWriteBeamLatticeExtension) { + writeConstPrefixedStringAttribute(XML_3MF_ATTRIBUTE_XMLNS, XML_3MF_NAMESPACEPREFIX_BEAMLATTICE, XML_3MF_NAMESPACE_BEAMLATTICESPEC); + + if (m_pModel->RequireExtension(XML_3MF_NAMESPACE_BEAMLATTICESPEC)) { + if (sRequiredExtensions.size() > 0) + sRequiredExtensions = sRequiredExtensions + " "; + sRequiredExtensions = sRequiredExtensions + XML_3MF_NAMESPACEPREFIX_BEAMLATTICE; + } + } + + if (m_bWriteSliceExtension) { + writeConstPrefixedStringAttribute(XML_3MF_ATTRIBUTE_XMLNS, XML_3MF_NAMESPACEPREFIX_SLICE, XML_3MF_NAMESPACE_SLICESPEC); + if (m_pModel->RequireExtension(XML_3MF_NAMESPACE_SLICESPEC)) { + if (sRequiredExtensions.size() > 0) + sRequiredExtensions = sRequiredExtensions + " "; + sRequiredExtensions = sRequiredExtensions + XML_3MF_NAMESPACEPREFIX_SLICE; + } + } + + if (m_bWriteSecureContentExtension) { + writeConstPrefixedStringAttribute(XML_3MF_ATTRIBUTE_XMLNS, XML_3MF_NAMESPACEPREFIX_SECURECONTENT, XML_3MF_NAMESPACE_SECURECONTENTSPEC); + if (m_pModel->RequireExtension(XML_3MF_NAMESPACE_SECURECONTENTSPEC)) { + if (sRequiredExtensions.size() > 0) + sRequiredExtensions = sRequiredExtensions + " "; + sRequiredExtensions = sRequiredExtensions + XML_3MF_NAMESPACEPREFIX_SECURECONTENT; + } + } + + if (m_bWriteCustomNamespaces) { + nfUint32 nNSCount = m_pXMLWriter->GetNamespaceCount(); + for (nfUint32 iNSCount = 0; iNSCount < nNSCount; iNSCount++) { + writeConstPrefixedStringAttribute(XML_3MF_ATTRIBUTE_XMLNS, m_pXMLWriter->GetNamespacePrefix(iNSCount).c_str(), m_pXMLWriter->GetNamespace(iNSCount).c_str()); + } + } + + if (sRequiredExtensions.size() > 0) + writeConstStringAttribute(XML_3MF_ATTRIBUTE_REQUIREDEXTENSIONS, sRequiredExtensions.c_str()); + + if (m_bIsRootModel) + writeModelMetaData(); + + writeResources(); + writeBuild(); + + writeFullEndElement(); + } + + void CModelWriterNode100_Model::writeTextures2D() + { + nfUint32 nTextureCount = m_pModel->getTexture2DCount(); + nfUint32 nTextureIndex; + + for (nTextureIndex = 0; nTextureIndex < nTextureCount; nTextureIndex++) { + m_pProgressMonitor->IncrementProgress(1); + + CModelTexture2DResource * pTexture2D = m_pModel->getTexture2D(nTextureIndex); + + writeStartElementWithPrefix(XML_3MF_ELEMENT_TEXTURE2D, XML_3MF_NAMESPACEPREFIX_MATERIAL); + + assertResourceIsInCurrentPath(pTexture2D->getPackageResourceID()); + writeIntAttribute(XML_3MF_ATTRIBUTE_TEXTURE2D_ID, pTexture2D->getPackageResourceID()->getModelResourceID()); + writeStringAttribute(XML_3MF_ATTRIBUTE_TEXTURE2D_PATH, pTexture2D->getAttachment()->getPathURI()); + writeStringAttribute(XML_3MF_ATTRIBUTE_TEXTURE2D_CONTENTTYPE, pTexture2D->getContentTypeString()); + + if (pTexture2D->getTileStyleU() != MODELTEXTURETILESTYLE_WRAP) + writeStringAttribute(XML_3MF_ATTRIBUTE_TEXTURE2D_TILESTYLEU, CModelTexture2DResource::tileStyleToString(pTexture2D->getTileStyleU())); + if (pTexture2D->getTileStyleV() != MODELTEXTURETILESTYLE_WRAP) + writeStringAttribute(XML_3MF_ATTRIBUTE_TEXTURE2D_TILESTYLEV, CModelTexture2DResource::tileStyleToString(pTexture2D->getTileStyleV())); + if (pTexture2D->getFilter() != MODELTEXTUREFILTER_AUTO) + writeStringAttribute(XML_3MF_ATTRIBUTE_TEXTURE2D_FILTER, CModelTexture2DResource::filterToString(pTexture2D->getFilter())); + + if (pTexture2D->hasBox2D()) { + nfFloat fU, fV, fWidth, fHeight; + pTexture2D->getBox2D(fU, fV, fWidth, fHeight); + writeStringAttribute(XML_3MF_ATTRIBUTE_TEXTURE2D_BOX, + std::to_string(fU) + " " + std::to_string(fV) + " " + std::to_string(fWidth) + " " + std::to_string(fHeight)); + } + + writeEndElement(); + + } + + } + + void CModelWriterNode100_Model::writeModelMetaData() + { + if (m_bIsRootModel) + { + nfUint32 nMetaDataCount = m_pModel->getMetaDataCount(); + nfUint32 nMetaDataIndex; + + for (nMetaDataIndex = 0; nMetaDataIndex < nMetaDataCount; nMetaDataIndex++) { + PModelMetaData pMetaData = m_pModel->getMetaData(nMetaDataIndex); + writeMetaData(pMetaData); + } + } + } + + + void CModelWriterNode100_Model::writeBaseMaterials() + { + nfUint32 nMaterialCount = m_pModel->getBaseMaterialCount(); + + for (nfUint32 nMaterialIndex = 0; nMaterialIndex < nMaterialCount; nMaterialIndex++) { + m_pProgressMonitor->IncrementProgress(1); + + CModelBaseMaterialResource * pBaseMaterial = m_pModel->getBaseMaterial(nMaterialIndex); + + pBaseMaterial->buildResourceIndexMap(); + + assertResourceIsInCurrentPath(pBaseMaterial->getPackageResourceID()); + ModelResourceID nResourceID = pBaseMaterial->getPackageResourceID()->getModelResourceID(); + + writeStartElement(XML_3MF_ELEMENT_BASEMATERIALS); + // Write Object ID (mandatory) + writeIntAttribute(XML_3MF_ATTRIBUTE_BASEMATERIALS_ID, nResourceID); + + nfUint32 nElementCount = pBaseMaterial->getCount(); + + UniqueResourceID nUniqueResourceID = pBaseMaterial->getPackageResourceID()->getUniqueID(); + + for (nfUint32 j = 0; j < nElementCount; j++) { + ModelPropertyID nPropertyID; + if (!pBaseMaterial->mapResourceIndexToPropertyID(j, nPropertyID)) { + throw CNMRException(NMR_ERROR_INVALIDPROPERTYRESOURCEID); + } + PModelBaseMaterial pElement = pBaseMaterial->getBaseMaterial(nPropertyID); + + m_pPropertyIndexMapping->registerPropertyID(nUniqueResourceID, pElement->getPropertyID(), j); + + writeStartElement(XML_3MF_ELEMENT_BASE); + writeStringAttribute(XML_3MF_ATTRIBUTE_BASEMATERIAL_NAME, pElement->getName()); + writeStringAttribute(XML_3MF_ATTRIBUTE_BASEMATERIAL_DISPLAYCOLOR, pElement->getDisplayColorString()); + writeEndElement(); + } + + writeFullEndElement(); + } + + } + + + void CModelWriterNode100_Model::writeSliceStacks() { + nfUint32 nSliceStackCount = m_pModel->getSliceStackCount(); + + for (nfUint32 nSliceStackIndex = 0; nSliceStackIndex < nSliceStackCount; nSliceStackIndex++) { + m_pProgressMonitor->IncrementProgress(1); + + CModelSliceStack *pSliceStackResource = dynamic_cast(m_pModel->getSliceStackResource(nSliceStackIndex).get()); + if (pSliceStackResource != nullptr) { + writeSliceStack(pSliceStackResource); + } + } + + } + + + void CModelWriterNode100_Model::writeSliceStack(_In_ CModelSliceStack *pSliceStackResource) { + __NMRASSERT(pSliceStackResource); + + std::string sNameSpacePrefix = XML_3MF_NAMESPACEPREFIX_SLICE; + + if (pSliceStackResource->OwnPath() == m_pModel->currentPath()) + { + writeStartElementWithPrefix(XML_3MF_ELEMENT_SLICESTACKRESOURCE, XML_3MF_NAMESPACEPREFIX_SLICE); + + assertResourceIsInCurrentPath(pSliceStackResource->getPackageResourceID()); + writeIntAttribute(XML_3MF_ATTRIBUTE_SLICESTACKID, pSliceStackResource->getPackageResourceID()->getModelResourceID()); + writeFloatAttribute(XML_3MF_ATTRIBUTE_SLICESTACKZBOTTOM, (float)pSliceStackResource->getZBottom()); + + + if (pSliceStackResource->getSliceRefCount() > 0) { + for (nfUint32 sliceRefIndex = 0; sliceRefIndex < pSliceStackResource->getSliceRefCount(); sliceRefIndex++) { + auto sliceRef = pSliceStackResource->getSliceRef(sliceRefIndex); + + writeStartElementWithPrefix(XML_3MF_ELEMENT_SLICEREFRESOURCE, XML_3MF_NAMESPACEPREFIX_SLICE); + writeIntAttribute(XML_3MF_ATTRIBUTE_SLICEREF_ID, sliceRef->getPackageResourceID()->getModelResourceID()); + if (sliceRef->OwnPath() != m_pModel->currentPath()) { + writeStringAttribute(XML_3MF_ATTRIBUTE_SLICEREF_PATH, sliceRef->OwnPath()); + } + writeEndElement(); + } + } + + if (pSliceStackResource->getSliceCount() > 0) { + for (nfUint32 nSliceIndex = 0; nSliceIndex < pSliceStackResource->getSliceCount(); nSliceIndex++) { + if (nSliceIndex % PROGRESS_SLICEUPDATE == PROGRESS_SLICEUPDATE - 1) { + + m_pProgressMonitor->SetProgressIdentifier(ProgressIdentifier::PROGRESS_WRITESLICES); + m_pProgressMonitor->ReportProgressAndQueryCancelled(true); + } + PSlice pSlice = pSliceStackResource->getSlice(nSliceIndex); + writeStartElementWithPrefix(XML_3MF_ELEMENT_SLICE, XML_3MF_NAMESPACEPREFIX_SLICE); + + writeFloatAttribute(XML_3MF_ATTRIBUTE_SLICEZTOP, nfFloat(pSlice->getTopZ())); + if (pSlice->getVertexCount() >= 2) { + writeStartElementWithPrefix(XML_3MF_ELEMENT_SLICEVERTICES, XML_3MF_NAMESPACEPREFIX_SLICE); + + for (nfUint32 nVertexIndex = 0; nVertexIndex < pSlice->getVertexCount(); nVertexIndex++) { + writeStartElementWithPrefix(XML_3MF_ELEMENT_VERTEX, XML_3MF_NAMESPACEPREFIX_SLICE); + nfFloat x, y; + pSlice->getVertex(nVertexIndex, &x, &y); + writeFloatAttribute(XML_3MF_ATTRIBUTE_SLICEVERTEX_X, x); + writeFloatAttribute(XML_3MF_ATTRIBUTE_SLICEVERTEX_Y, y); + writeEndElement(); + } + writeFullEndElement(); + } + else { + if (pSlice->getVertexCount() == 1) + throw CNMRException(NMR_ERROR_SLICE_ONEVERTEX); + } + + for (nfUint32 nPolygonIndex = 0; nPolygonIndex < pSlice->getPolygonCount(); nPolygonIndex++) { + if (pSlice->getPolygonIndexCount(nPolygonIndex) >= 2) { + writeStartElementWithPrefix(XML_3MF_ELEMENT_SLICEPOLYGON, XML_3MF_NAMESPACEPREFIX_SLICE); + writeIntAttribute(XML_3MF_ATTRIBUTE_SLICEPOLYGON_STARTV, pSlice->getPolygonIndex(nPolygonIndex, 0)); + + for (nfUint32 nIndexIndex = 1; nIndexIndex < pSlice->getPolygonIndexCount(nPolygonIndex); nIndexIndex++) { + writeStartElementWithPrefix(XML_3MF_ELEMENT_SLICESEGMENT, XML_3MF_NAMESPACEPREFIX_SLICE); + writeIntAttribute(XML_3MF_ATTRIBUTE_SLICESEGMENT_V2, pSlice->getPolygonIndex(nPolygonIndex, nIndexIndex)); + writeEndElement(); + } + + writeFullEndElement(); + } + else { + if (pSlice->getPolygonIndexCount(nPolygonIndex) == 1) + throw CNMRException(NMR_ERROR_SLICE_ONEPOINT); + } + } + + writeFullEndElement(); + } + } + writeFullEndElement(); + } + } + + void CModelWriterNode100_Model::writeObjects() + { + std::list objectList = m_pModel->getSortedObjectList(); + + for (auto iIterator = objectList.begin(); iIterator != objectList.end(); iIterator++) { + CModelObject * pObject = *iIterator; + + PPackageModelPath pPath = pObject->getPackageResourceID()->getPackageModelPath(); + if (m_pModel->currentModelPath()->getPath() != pPath->getPath()) + { + continue; + } + + m_pProgressMonitor->SetProgressIdentifier(ProgressIdentifier::PROGRESS_WRITEOBJECTS); + m_pProgressMonitor->IncrementProgress(1); + m_pProgressMonitor->ReportProgressAndQueryCancelled(true); + + writeStartElement(XML_3MF_ELEMENT_OBJECT); + // Write Object ID (mandatory) + writeIntAttribute(XML_3MF_ATTRIBUTE_OBJECT_ID, pObject->getPackageResourceID()->getModelResourceID()); + + // Write Object Name (optional) + std::string sObjectName = pObject->getName(); + if (sObjectName.length() > 0) + writeStringAttribute(XML_3MF_ATTRIBUTE_OBJECT_NAME, sObjectName); + + // Write Object Partnumber (optional) + std::string sObjectPartNumber = pObject->getPartNumber(); + if (sObjectPartNumber.length() > 0) + writeStringAttribute(XML_3MF_ATTRIBUTE_OBJECT_PARTNUMBER, sObjectPartNumber); + + // Write Object Type (optional) + writeStringAttribute(XML_3MF_ATTRIBUTE_OBJECT_TYPE, pObject->getObjectTypeString()); + + // Write Object Thumbnail (optional) + PModelAttachment pThumbnail = pObject->getThumbnailAttachment(); + if (pThumbnail) { + PModelAttachment pModelAttachment = m_pModel->findModelAttachment(pThumbnail->getPathURI()); + if (!pModelAttachment) + throw CNMRException(NMR_ERROR_NOTEXTURESTREAM); + if (!((pModelAttachment->getRelationShipType() == PACKAGE_TEXTURE_RELATIONSHIP_TYPE) || (pModelAttachment->getRelationShipType() == PACKAGE_THUMBNAIL_RELATIONSHIP_TYPE))) + throw CNMRException(NMR_ERROR_NOTEXTURESTREAM); + + writeStringAttribute(XML_3MF_ATTRIBUTE_OBJECT_THUMBNAIL, pThumbnail->getPathURI()); + } + + if (m_bWriteProductionExtension) { + if (!pObject->uuid().get()) + throw CNMRException(NMR_ERROR_MISSINGUUID); + writePrefixedStringAttribute(XML_3MF_NAMESPACEPREFIX_PRODUCTION, XML_3MF_PRODUCTION_UUID, pObject->uuid()->toString()); + } + + // Slice extension content + if (m_bWriteSliceExtension) { + if (pObject->getSliceStack().get()) { + assertResourceIsInCurrentPath(pObject->getSliceStack()->getPackageResourceID()); + writePrefixedStringAttribute(XML_3MF_NAMESPACEPREFIX_SLICE, XML_3MF_ATTRIBUTE_OBJECT_SLICESTACKID, + fnUint32ToString(pObject->getSliceStack()->getPackageResourceID()->getModelResourceID())); + } + if (pObject->slicesMeshResolution() != MODELSLICESMESHRESOLUTION_FULL) { + writePrefixedStringAttribute(XML_3MF_NAMESPACEPREFIX_SLICE, XML_3MF_ATTRIBUTE_OBJECT_MESHRESOLUTION, + XML_3MF_VALUE_OBJECT_MESHRESOLUTION_LOW); + } + } + + // Check if object is a mesh Object + CModelMeshObject * pMeshObject = dynamic_cast (pObject); + if (pMeshObject) { + // Prepare Object Level Property ID and Index + UniqueResourceID nObjectLevelPropertyID = 0; + ModelResourceIndex nObjectLevelPropertyIndex = 0; + CMesh* pMesh = pMeshObject->getMesh(); + + if (pMesh) { + CMeshInformationHandler * pMeshInformationHandler = pMesh->getMeshInformationHandler(); + if (pMeshInformationHandler) { + // Get generic property handler + CMeshInformation *pInformation = pMeshInformationHandler->getInformationByType(0, emiProperties); + if (pInformation) { + auto pProperties = dynamic_cast (pInformation); + NMR::MESHINFORMATION_PROPERTIES * pDefaultData = (NMR::MESHINFORMATION_PROPERTIES*)pProperties->getDefaultData(); + if (pDefaultData && pDefaultData->m_nUniqueResourceID != 0) { + nObjectLevelPropertyID = pDefaultData->m_nUniqueResourceID; + nObjectLevelPropertyIndex = m_pPropertyIndexMapping->mapPropertyIDToIndex(nObjectLevelPropertyID, pDefaultData->m_nPropertyIDs[0]); + } + } + } + } + // Write Object Level Attributes (only for meshes) + if (nObjectLevelPropertyID != 0) { + ModelResourceID nPropertyModelResourceID = m_pModel->findPackageResourceID(nObjectLevelPropertyID)->getModelResourceID(); + writeIntAttribute(XML_3MF_ATTRIBUTE_OBJECT_PID, nPropertyModelResourceID); + writeIntAttribute(XML_3MF_ATTRIBUTE_OBJECT_PINDEX, nObjectLevelPropertyIndex); + } + } + + writeMetaDataGroup(pObject->metaDataGroup()); + + if (pMeshObject) { + CModelWriterNode100_Mesh ModelWriter_Mesh(pMeshObject, m_pXMLWriter, m_pProgressMonitor, + m_pPropertyIndexMapping, m_nDecimalPrecision, m_bWriteMaterialExtension, m_bWriteBeamLatticeExtension); + + ModelWriter_Mesh.writeToXML(); + } + + // Check if object is a component Object + CModelComponentsObject * pComponentObject = dynamic_cast (pObject); + if (pComponentObject) { + writeComponentsObject(pComponentObject); + } + + writeFullEndElement(); + } + + } + + void CModelWriterNode100_Model::writeMetaData(_In_ PModelMetaData pMetaData) + { + writeStartElement(XML_3MF_ELEMENT_METADATA); + + std::string sNameSpace = pMetaData->getNameSpace(); + std::string sName = pMetaData->getName(); + std::string sValue = pMetaData->getValue(); + std::string sType = pMetaData->getType(); + nfBool bPreserve = pMetaData->getPreserve(); + + if (sNameSpace.empty()) { + writeStringAttribute(XML_3MF_ATTRIBUTE_METADATA_NAME, sName); + } + else { + std::string sNameSpacePrefix; + if (!m_pXMLWriter->GetNamespacePrefix(sNameSpace, sNameSpacePrefix)) { + throw CNMRException(NMR_ERROR_INVALIDBUFFERSIZE); + } + writeStringAttribute(XML_3MF_ATTRIBUTE_METADATA_NAME, composeNamespaceAndNameIntoKey(sNameSpacePrefix, sName)); + } + + if (sType != "xs:string") { + writeStringAttribute(XML_3MF_ATTRIBUTE_METADATA_TYPE, sType); + } + if (bPreserve) { + writeStringAttribute(XML_3MF_ATTRIBUTE_METADATA_PRESERVE, "1"); + } + writeText(sValue.c_str(), (nfUint32)sValue.length()); + + writeEndElement(); + } + + void CModelWriterNode100_Model::writeMetaDataGroup(_In_ PModelMetaDataGroup pMetaDataGroup) + { + if (pMetaDataGroup->getMetaDataCount() > 0) + { + writeStartElement(XML_3MF_ELEMENT_METADATAGROUP); + for (nfUint32 index = 0; indexgetMetaDataCount(); index++) { + PModelMetaData pMetaData = pMetaDataGroup->getMetaData(index); + writeMetaData(pMetaData); + } + writeFullEndElement(); + } + } + + void CModelWriterNode100_Model::writeColors() + { + nfUint32 nCount = m_pModel->getColorGroupCount(); + + for (nfUint32 nIndex = 0; nIndex < nCount; nIndex++) { + m_pProgressMonitor->IncrementProgress(1); + + CModelColorGroupResource * pColorGroup = m_pModel->getColorGroup(nIndex); + + pColorGroup->buildResourceIndexMap(); + + assertResourceIsInCurrentPath(pColorGroup->getPackageResourceID()); + ModelResourceID nResourceID = pColorGroup->getPackageResourceID()->getModelResourceID(); + + writeStartElementWithPrefix(XML_3MF_ELEMENT_COLORGROUP, XML_3MF_NAMESPACEPREFIX_MATERIAL); + // Write Object ID (mandatory) + writeIntAttribute(XML_3MF_ATTRIBUTE_COLORS_ID, nResourceID); + + nfUint32 nElementCount = pColorGroup->getCount(); + + UniqueResourceID nUniqueResourceID = pColorGroup->getPackageResourceID()->getUniqueID(); + for (nfUint32 j = 0; j < nElementCount; j++) { + ModelPropertyID nPropertyID; + if (!pColorGroup->mapResourceIndexToPropertyID(j, nPropertyID)) { + throw CNMRException(NMR_ERROR_INVALIDPROPERTYRESOURCEID); + } + nfColor pElement = pColorGroup->getColor(nPropertyID); + + m_pPropertyIndexMapping->registerPropertyID(nUniqueResourceID, nPropertyID, j); + + writeStartElementWithPrefix(XML_3MF_ELEMENT_COLOR, XML_3MF_NAMESPACEPREFIX_MATERIAL); + writeStringAttribute(XML_3MF_ATTRIBUTE_COLORS_COLOR, fnColorToString(pElement)); + writeEndElement(); + } + + writeFullEndElement(); + } + } + + void CModelWriterNode100_Model::writeTex2Coords() + { + nfUint32 nGroupCount = m_pModel->getTexture2DGroupCount(); + + for (nfUint32 nGroupIndex = 0; nGroupIndex < nGroupCount; nGroupIndex++) { + m_pProgressMonitor->IncrementProgress(1); + + CModelTexture2DGroupResource * pTexture2DGroup = m_pModel->getTexture2DGroup(nGroupIndex); + + pTexture2DGroup->buildResourceIndexMap(); + + assertResourceIsInCurrentPath(pTexture2DGroup->getPackageResourceID()); + ModelResourceID nResourceID = pTexture2DGroup->getPackageResourceID()->getModelResourceID(); + + writeStartElementWithPrefix(XML_3MF_ELEMENT_TEX2DGROUP, XML_3MF_NAMESPACEPREFIX_MATERIAL); + // Write Object ID (mandatory) + writeIntAttribute(XML_3MF_ATTRIBUTE_TEX2DGROUP_ID, nResourceID); + assertResourceIsInCurrentPath(pTexture2DGroup->getTexture2D()->getPackageResourceID()); + writeIntAttribute(XML_3MF_ATTRIBUTE_TEX2DGROUP_TEXTUREID, pTexture2DGroup->getTexture2D()->getPackageResourceID()->getModelResourceID()); + + nfUint32 nElementCount = pTexture2DGroup->getCount(); + UniqueResourceID nUniqueResourceID = pTexture2DGroup->getPackageResourceID()->getUniqueID(); + for (nfUint32 j = 0; j < nElementCount; j++) { + ModelPropertyID nPropertyID; + if (!pTexture2DGroup->mapResourceIndexToPropertyID(j, nPropertyID)) { + throw CNMRException(NMR_ERROR_INVALIDPROPERTYRESOURCEID); + } + MODELTEXTURE2DCOORDINATE uvCoordinate = pTexture2DGroup->getUVCoordinate(nPropertyID); + + m_pPropertyIndexMapping->registerPropertyID(nUniqueResourceID, nPropertyID, j); + + writeStartElementWithPrefix(XML_3MF_ELEMENT_TEX2COORD, XML_3MF_NAMESPACEPREFIX_MATERIAL); + writeFloatAttribute(XML_3MF_ATTRIBUTE_TEXTURE_U, (float)uvCoordinate.m_dU); + writeFloatAttribute(XML_3MF_ATTRIBUTE_TEXTURE_V, (float)uvCoordinate.m_dV); + writeEndElement(); + } + + writeFullEndElement(); + } + + } + + void CModelWriterNode100_Model::writeCompositeMaterials() + { + nfUint32 nCount = m_pModel->getCompositeMaterialsCount(); + + for (nfUint32 nIndex = 0; nIndex < nCount; nIndex++) { + m_pProgressMonitor->IncrementProgress(1); + + CModelCompositeMaterialsResource * pCompositeMaterials = m_pModel->getCompositeMaterials(nIndex); + + pCompositeMaterials->buildResourceIndexMap(); + + assertResourceIsInCurrentPath(pCompositeMaterials->getPackageResourceID()); + ModelResourceID nResourceID = pCompositeMaterials->getPackageResourceID()->getModelResourceID(); + UniqueResourceID nUniqueResourceID = pCompositeMaterials->getPackageResourceID()->getUniqueID(); + + writeStartElementWithPrefix(XML_3MF_ELEMENT_COMPOSITEMATERIALS, XML_3MF_NAMESPACEPREFIX_MATERIAL); + // Write Object ID (mandatory) + writeIntAttribute(XML_3MF_ATTRIBUTE_COMPOSITEMATERIALS_ID, nResourceID); + PModelBaseMaterialResource pBaseMaterialResource = pCompositeMaterials->getBaseMaterialResource(); + assertResourceIsInCurrentPath(pBaseMaterialResource->getPackageResourceID()); + ModelResourceID nBaseMaterialResourceID = pBaseMaterialResource->getPackageResourceID()->getModelResourceID(); + writeIntAttribute(XML_3MF_ATTRIBUTE_COMPOSITEMATERIALS_MATID, nBaseMaterialResourceID); + + std::vector matIndices; + std::set mapUsedBMPropertyIDs; + + nfUint32 nCompositeCount = pCompositeMaterials->getCount(); + for (nfUint32 j = 0; j < nCompositeCount; j++) { + ModelPropertyID nPropertyID; + if (!pCompositeMaterials->mapResourceIndexToPropertyID(j, nPropertyID)) { + throw CNMRException(NMR_ERROR_INVALIDPROPERTYRESOURCEID); + } + m_pPropertyIndexMapping->registerPropertyID(nUniqueResourceID, nPropertyID, j); + PModelComposite pModelComposite = pCompositeMaterials->getComposite(nPropertyID); + + for (auto constituents : (*pModelComposite)) { + nfUint32 nBaseMaterialIndex = m_pPropertyIndexMapping->mapPropertyIDToIndex(nBaseMaterialResourceID, constituents.m_nPropertyID); + if (mapUsedBMPropertyIDs.find(constituents.m_nPropertyID) == mapUsedBMPropertyIDs.end()) { + mapUsedBMPropertyIDs.insert(constituents.m_nPropertyID); + matIndices.push_back(nBaseMaterialIndex); + } + } + } + writeStringAttribute(XML_3MF_ATTRIBUTE_COMPOSITEMATERIALS_MATINDICES, fnVectorToSpaceDelimitedString(matIndices)); + + for (nfUint32 j = 0; j < nCompositeCount; j++) { + ModelPropertyID nPropertyID; + if (!pCompositeMaterials->mapResourceIndexToPropertyID(j, nPropertyID)) { + throw CNMRException(NMR_ERROR_INVALIDPROPERTYRESOURCEID); + } + PModelComposite pModelComposite = pCompositeMaterials->getComposite(nPropertyID); + + std::vector ratios; + writeStartElementWithPrefix(XML_3MF_ELEMENT_COMPOSITE, XML_3MF_NAMESPACEPREFIX_MATERIAL); + for (ModelPropertyID nBMPropertyID: mapUsedBMPropertyIDs) { + ratios.push_back(pModelComposite->GetMixingRatio(nBMPropertyID)); + } + writeStringAttribute(XML_3MF_ATTRIBUTE_COMPOSITE_VALUES, fnVectorToSpaceDelimitedString(ratios)); + writeEndElement(); + } + writeFullEndElement(); + } + } + + + void CModelWriterNode100_Model::writeMultiPropertyAttributes(_In_ CModelMultiPropertyGroupResource* pMultiPropertyGroup) + { + // assemble and write pids and blendmethods + std::vector vctUniqueIDs; + std::vector vctBlendMethodString; + + nfUint32 nLayerCount = pMultiPropertyGroup->getLayerCount(); + for (nfUint32 iLayer = 0; iLayer < nLayerCount; iLayer++) { + MODELMULTIPROPERTYLAYER layer = pMultiPropertyGroup->getLayer(iLayer); + vctUniqueIDs.push_back(layer.m_nUniqueResourceID); + if (iLayer > 0) { + vctBlendMethodString.push_back(CModelMultiPropertyGroupResource::blendMethodToString(layer.m_nMethod)); + } + } + assertResourceIsInCurrentPath(pMultiPropertyGroup->getPackageResourceID()); + ModelResourceID nModelResourceID = pMultiPropertyGroup->getPackageResourceID()->getModelResourceID(); + writeIntAttribute(XML_3MF_ATTRIBUTE_MULTIPROPERTIES_ID, nModelResourceID); + writeStringAttribute(XML_3MF_ATTRIBUTE_MULTIPROPERTIES_PIDS, fnVectorToSpaceDelimitedString(vctUniqueIDs)); + writeStringAttribute(XML_3MF_ATTRIBUTE_MULTIPROPERTIES_BLENDMETHODS, fnVectorToSpaceDelimitedString(vctBlendMethodString)); + } + + void CModelWriterNode100_Model::writeMultiPropertyMultiElements(_In_ CModelMultiPropertyGroupResource* pMultiPropertyGroup) + { + // assemble and write MultiPropertyElements + assertResourceIsInCurrentPath(pMultiPropertyGroup->getPackageResourceID()); + UniqueResourceID nUniqueResourceID = pMultiPropertyGroup->getPackageResourceID()->getUniqueID(); + + nfUint32 nMultiCount = pMultiPropertyGroup->getCount(); + nfUint32 nLayerCount = pMultiPropertyGroup->getLayerCount(); + for (nfUint32 iMulti = 0; iMulti < nMultiCount; iMulti++) { + ModelPropertyID nPropertyID; + if (!pMultiPropertyGroup->mapResourceIndexToPropertyID(iMulti, nPropertyID)) { + throw CNMRException(NMR_ERROR_INVALIDPROPERTYRESOURCEID); + } + m_pPropertyIndexMapping->registerPropertyID(nUniqueResourceID, nPropertyID, iMulti); + + PModelMultiProperty pMultiProperty = pMultiPropertyGroup->getMultiProperty(nPropertyID); + std::vector vctPIndices; + for (nfUint32 iLayer = 0; iLayer < nLayerCount; iLayer++) { + MODELMULTIPROPERTYLAYER layer = pMultiPropertyGroup->getLayer(iLayer); + if (iLayer < pMultiProperty->size()) { + nfUint32 pIndex = m_pPropertyIndexMapping->mapPropertyIDToIndex(layer.m_nUniqueResourceID, (*pMultiProperty)[iLayer]); + vctPIndices.push_back(pIndex); + } else { + throw CNMRException(NMR_ERROR_MULTIPROPERTIES_NOT_ENOUGH_PROPERTYIDS_SPECIFIED); + } + } + + writeStartElementWithPrefix(XML_3MF_ELEMENT_MULTI, XML_3MF_NAMESPACEPREFIX_MATERIAL); + + writeStringAttribute(XML_3MF_ATTRIBUTE_MULTI_PINDICES, fnVectorToSpaceDelimitedString(vctPIndices)); + + writeEndElement(); + } + } + + void CModelWriterNode100_Model::writeMultiProperties() + { + nfUint32 nCount = m_pModel->getMultiPropertyGroupCount(); + + for (nfUint32 nIndex = 0; nIndex < nCount; nIndex++) { + m_pProgressMonitor->IncrementProgress(1); + + CModelMultiPropertyGroupResource * pMultiPropertyGroup = m_pModel->getMultiPropertyGroup(nIndex); + + pMultiPropertyGroup->buildResourceIndexMap(); + + writeStartElementWithPrefix(XML_3MF_ELEMENT_MULTIPROPERTIES, XML_3MF_NAMESPACEPREFIX_MATERIAL); + + writeMultiPropertyAttributes(pMultiPropertyGroup); + + writeMultiPropertyMultiElements(pMultiPropertyGroup); + + writeFullEndElement(); + } + } + + void CModelWriterNode100_Model::writeResources() + { + writeStartElement(XML_3MF_ELEMENT_RESOURCES); + + if (m_bIsRootModel) + { + if (m_bWriteBaseMaterials) + writeBaseMaterials(); + + if (m_bWriteMaterialExtension) { + writeTextures2D(); + writeColors(); + writeTex2Coords(); + writeCompositeMaterials(); + writeMultiProperties(); + } + if (m_bWriteSliceExtension) { + writeSliceStacks(); + } + if (m_bWriteObjects) + writeObjects(); + } + else { + if (m_bWriteSliceExtension) { + writeSliceStacks(); + } + if (m_bWriteObjects) { + writeObjects(); + } + } + + writeFullEndElement(); + } + + void CModelWriterNode100_Model::writeBuild() + { + writeStartElement(XML_3MF_ELEMENT_BUILD); + if (m_bWriteProductionExtension) { + if (!m_pModel->buildUUID().get()) { + throw CNMRException(NMR_ERROR_MISSINGUUID); + } + writePrefixedStringAttribute(XML_3MF_NAMESPACEPREFIX_PRODUCTION, XML_3MF_PRODUCTION_UUID, m_pModel->buildUUID()->toString()); + } + + if (m_bIsRootModel) + { + m_pProgressMonitor->IncrementProgress(1); + + nfUint32 nCount = m_pModel->getBuildItemCount(); + nfUint32 nIndex; + for (nIndex = 0; nIndex < nCount; nIndex++) { + PModelBuildItem pBuildItem = m_pModel->getBuildItem(nIndex); + + writeStartElement(XML_3MF_ELEMENT_ITEM); + + CModelObject* pObject = pBuildItem->getObject(); + PPackageResourceID pID = pObject->getPackageResourceID(); + + writeIntAttribute(XML_3MF_ATTRIBUTE_ITEM_OBJECTID, pID->getModelResourceID()); + if (pID->getPath() != m_pModel->currentPath()) + writePrefixedStringAttribute(XML_3MF_NAMESPACEPREFIX_PRODUCTION, XML_3MF_PRODUCTION_PATH, pID->getPath()); + + if (!pBuildItem->getPartNumber().empty()) + writeStringAttribute(XML_3MF_ATTRIBUTE_ITEM_PARTNUMBER, pBuildItem->getPartNumber()); + + + if (m_bWriteProductionExtension) { + if (!pBuildItem->uuid().get()) { + throw CNMRException(NMR_ERROR_MISSINGUUID); + } + writePrefixedStringAttribute(XML_3MF_NAMESPACEPREFIX_PRODUCTION, XML_3MF_PRODUCTION_UUID, pBuildItem->uuid()->toString()); + } + if (pBuildItem->hasTransform()) + writeStringAttribute(XML_3MF_ATTRIBUTE_ITEM_TRANSFORM, pBuildItem->getTransformString()); + + if (m_bWriteSliceExtension && !pBuildItem->isValidForSlices()) { + throw CNMRException(NMR_ERROR_SLICETRANSFORMATIONPLANAR); + } + + writeMetaDataGroup(pBuildItem->metaDataGroup()); + if (pBuildItem->metaDataGroup()->getMetaDataCount() > 0) + writeFullEndElement(); + else + writeEndElement(); + + } + } + writeFullEndElement(); + } + + void CModelWriterNode100_Model::writeComponentsObject(_In_ CModelComponentsObject * pComponentsObject) + { + __NMRASSERT(pComponentsObject); + + nfUint32 nIndex; + nfUint32 nCount = pComponentsObject->getComponentCount(); + + writeStartElement(XML_3MF_ELEMENT_COMPONENTS); + for (nIndex = 0; nIndex < nCount; nIndex++) { + PModelComponent pComponent = pComponentsObject->getComponent(nIndex); + writeStartElement(XML_3MF_ELEMENT_COMPONENT); + PPackageResourceID pObjectID = pComponent->getObject()->getPackageResourceID(); + writeIntAttribute(XML_3MF_ATTRIBUTE_COMPONENT_OBJECTID, pObjectID->getModelResourceID()); + if (pObjectID->getPath() != m_pModel->currentPath()) { + if (m_pModel->currentPath() != m_pModel->rootPath()) { + throw CNMRException(NMR_ERROR_REFERENCESTOODEEP); + } + if (m_bWriteProductionExtension) { + writePrefixedStringAttribute(XML_3MF_NAMESPACEPREFIX_PRODUCTION, XML_3MF_PRODUCTION_PATH, pObjectID->getPath()); + } + else { + throw CNMRException(NMR_ERROR_PRODUCTIONEXTENSION_REQUIRED); + } + } + if (pComponent->hasTransform()) + writeStringAttribute(XML_3MF_ATTRIBUTE_COMPONENT_TRANSFORM, pComponent->getTransformString()); + if (m_bWriteProductionExtension) { + if (!pComponent->uuid().get()) { + throw CNMRException(NMR_ERROR_MISSINGUUID); + } + writePrefixedStringAttribute(XML_3MF_NAMESPACEPREFIX_PRODUCTION, XML_3MF_PRODUCTION_UUID, pComponent->uuid()->toString()); + } + writeEndElement(); + } + + writeFullEndElement(); + } + +} diff --git a/Source/lib3mf_interfaceexception.cpp b/Source/lib3mf_interfaceexception.cpp new file mode 100644 index 0000000..f888b53 --- /dev/null +++ b/Source/lib3mf_interfaceexception.cpp @@ -0,0 +1,65 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +This file has been generated by the Automatic Component Toolkit (ACT) version 1.6.0. + +Abstract: This is an autogenerated C++ Implementation file with the basic internal + exception type in order to allow an easy use of the 3MF Library + +Interface version: 2.2.0 + +*/ + + +#include + +#include "lib3mf_interfaceexception.hpp" + +/************************************************************************************************************************* + Class ELib3MFInterfaceException +**************************************************************************************************************************/ +ELib3MFInterfaceException::ELib3MFInterfaceException(Lib3MFResult errorCode) + : m_errorMessage("Lib3MF Error " + std::to_string (errorCode)) +{ + m_errorCode = errorCode; +} + +ELib3MFInterfaceException::ELib3MFInterfaceException(Lib3MFResult errorCode, std::string errorMessage) + : m_errorMessage(errorMessage + " (" + std::to_string (errorCode) + ")") +{ + m_errorCode = errorCode; +} + +Lib3MFResult ELib3MFInterfaceException::getErrorCode () +{ + return m_errorCode; +} + +const char * ELib3MFInterfaceException::what () const +{ + return m_errorMessage.c_str(); +} + diff --git a/Source/lib3mf_interfacejournal.cpp b/Source/lib3mf_interfacejournal.cpp new file mode 100644 index 0000000..1d38a8d --- /dev/null +++ b/Source/lib3mf_interfacejournal.cpp @@ -0,0 +1,341 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +This file has been generated by the Automatic Component Toolkit (ACT) version 1.6.0. + +Abstract: This is an autogenerated C++ implementation file in order to allow easy +development of the 3MF Library. It provides an automatic Journaling mechanism for the library implementation. + +Interface version: 2.2.0 + +*/ + + +#include +#include +#include + +#include "lib3mf_interfacejournal.hpp" +#include "lib3mf_interfaceexception.hpp" + + +std::string Lib3MFHandleToHex (Lib3MFHandle pHandle) +{ + std::stringstream stream; + stream << std::setfill('0') << std::setw(sizeof(Lib3MF_uint64) * 2) + << std::hex << (Lib3MF_uint64) pHandle; + return stream.str(); +} + +CLib3MFInterfaceJournalEntry::CLib3MFInterfaceJournalEntry(CLib3MFInterfaceJournal * pJournal, std::string sClassName, std::string sMethodName, Lib3MFHandle pInstanceHandle) + : m_pJournal(pJournal), m_ErrorCode(LIB3MF_SUCCESS), m_sClassName(sClassName), m_sMethodName(sMethodName), m_nInitTimeStamp(0), m_nFinishTimeStamp(0) +{ + if (pJournal == nullptr) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDPARAM); + m_nInitTimeStamp = m_pJournal->getTimeStamp (); + m_sInstanceHandle = Lib3MFHandleToHex (pInstanceHandle); +} + +CLib3MFInterfaceJournalEntry::~CLib3MFInterfaceJournalEntry() +{ +} + +void CLib3MFInterfaceJournalEntry::addParameter(const std::string & sName, const std::string & sParameterType, const std::string & sParameterValue) +{ + m_sParameters.push_back(std::make_pair(std::make_pair(sName, sParameterType), sParameterValue)); +} + +void CLib3MFInterfaceJournalEntry::addResult(const std::string & sName, const std::string & sResultType, const std::string & sResultValue) +{ + m_sResultValues.push_back(std::make_pair(std::make_pair(sName, sResultType), sResultValue)); +} + +std::string CLib3MFInterfaceJournalEntry::getXMLString() +{ + std::stringstream sStream; + Lib3MF_uint64 nDuration = 0; + + if (m_nFinishTimeStamp > m_nInitTimeStamp) + nDuration = m_nFinishTimeStamp - m_nInitTimeStamp; + + sStream << " \n"; + + if (m_sClassName != "") + sStream << " \n"; + + auto iParamIter = m_sParameters.begin(); + while (iParamIter != m_sParameters.end()) { + sStream << " first.first << "\" type=\"" << iParamIter->first.second << "\" value=\"" << iParamIter->second <<"\" />\n"; + iParamIter++; + } + + auto iResultIter = m_sResultValues.begin(); + while (iResultIter != m_sResultValues.end()) { + sStream << " first.first << "\" type=\"" << iResultIter->first.second << "\" value=\"" << iResultIter->second << "\" />\n"; + iResultIter++; + } + + sStream << " \n"; + return sStream.str (); +} + +void CLib3MFInterfaceJournalEntry::writeSuccess() +{ + writeError(LIB3MF_SUCCESS); +} + +void CLib3MFInterfaceJournalEntry::writeError(Lib3MFResult nErrorCode) +{ + m_ErrorCode = nErrorCode; + m_nFinishTimeStamp = m_pJournal->getTimeStamp(); + m_pJournal->writeEntry(this); +} + +void CLib3MFInterfaceJournalEntry::addBooleanParameter(const std::string & sName, const bool bValue) +{ + addParameter (sName, "bool", std::to_string((int)bValue)); +} + +void CLib3MFInterfaceJournalEntry::addUInt8Parameter(const std::string & sName, const Lib3MF_uint8 nValue) +{ + addParameter(sName, "uint8", std::to_string(nValue)); +} + +void CLib3MFInterfaceJournalEntry::addUInt16Parameter(const std::string & sName, const Lib3MF_uint16 nValue) +{ + addParameter(sName, "uint16", std::to_string(nValue)); +} + +void CLib3MFInterfaceJournalEntry::addUInt32Parameter(const std::string & sName, const Lib3MF_uint32 nValue) +{ + addParameter(sName, "uint32", std::to_string(nValue)); +} + +void CLib3MFInterfaceJournalEntry::addUInt64Parameter(const std::string & sName, const Lib3MF_uint64 nValue) +{ + addParameter(sName, "uint64", std::to_string(nValue)); +} + +void CLib3MFInterfaceJournalEntry::addInt8Parameter(const std::string & sName, const Lib3MF_int8 nValue) +{ + addParameter(sName, "int8", std::to_string(nValue)); +} + +void CLib3MFInterfaceJournalEntry::addInt16Parameter(const std::string & sName, const Lib3MF_int16 nValue) +{ + addParameter(sName, "int16", std::to_string(nValue)); +} + +void CLib3MFInterfaceJournalEntry::addInt32Parameter(const std::string & sName, const Lib3MF_int32 nValue) +{ + addParameter(sName, "uint32", std::to_string(nValue)); +} + +void CLib3MFInterfaceJournalEntry::addInt64Parameter(const std::string & sName, const Lib3MF_int64 nValue) +{ + addParameter(sName, "int64", std::to_string(nValue)); +} + +void CLib3MFInterfaceJournalEntry::addSingleParameter(const std::string & sName, const Lib3MF_single fValue) +{ + addParameter(sName, "single", std::to_string(fValue)); +} + +void CLib3MFInterfaceJournalEntry::addDoubleParameter(const std::string & sName, const Lib3MF_double dValue) +{ + addParameter(sName, "double", std::to_string(dValue)); +} +void CLib3MFInterfaceJournalEntry::addPointerParameter(const std::string & sName, const Lib3MF_pvoid pValue) +{ + addParameter(sName, "pointer", std::to_string(reinterpret_cast(pValue))); +} + +void CLib3MFInterfaceJournalEntry::addStringParameter(const std::string & sName, const char * pValue) +{ + if (pValue != nullptr) { + addParameter(sName, "string", pValue); + } + else { + addParameter(sName, "nullstring", ""); + } +} + +void CLib3MFInterfaceJournalEntry::addHandleParameter(const std::string & sName, const Lib3MFHandle pHandle) +{ + addParameter(sName, "handle", Lib3MFHandleToHex(pHandle)); +} + +void CLib3MFInterfaceJournalEntry::addEnumParameter(const std::string & sName, const std::string & sEnumType, const Lib3MF_int32 nValue) +{ + addParameter(sName, "enum" + sEnumType, std::to_string(nValue)); +} + +void CLib3MFInterfaceJournalEntry::addBooleanResult(const std::string & sName, const bool bValue) +{ + addResult(sName, "bool", std::to_string((int)bValue)); +} + +void CLib3MFInterfaceJournalEntry::addUInt8Result(const std::string & sName, const Lib3MF_uint8 nValue) +{ + addResult(sName, "uint8", std::to_string(nValue)); +} + +void CLib3MFInterfaceJournalEntry::addUInt16Result(const std::string & sName, const Lib3MF_uint16 nValue) +{ + addResult(sName, "uint16", std::to_string(nValue)); +} + +void CLib3MFInterfaceJournalEntry::addUInt32Result(const std::string & sName, const Lib3MF_uint32 nValue) +{ + addResult(sName, "uint32", std::to_string(nValue)); +} + +void CLib3MFInterfaceJournalEntry::addUInt64Result(const std::string & sName, const Lib3MF_uint64 nValue) +{ + addResult(sName, "uint64", std::to_string(nValue)); +} + +void CLib3MFInterfaceJournalEntry::addInt8Result(const std::string & sName, const Lib3MF_int8 nValue) +{ + addResult(sName, "int8", std::to_string(nValue)); +} + +void CLib3MFInterfaceJournalEntry::addInt16Result(const std::string & sName, const Lib3MF_int16 nValue) +{ + addResult(sName, "int16", std::to_string(nValue)); +} + +void CLib3MFInterfaceJournalEntry::addInt32Result(const std::string & sName, const Lib3MF_int32 nValue) +{ + addResult(sName, "uint32", std::to_string(nValue)); +} + +void CLib3MFInterfaceJournalEntry::addInt64Result(const std::string & sName, const Lib3MF_int64 nValue) +{ + addResult(sName, "int64", std::to_string(nValue)); +} + +void CLib3MFInterfaceJournalEntry::addSingleResult(const std::string & sName, const Lib3MF_single fValue) +{ + addResult(sName, "single", std::to_string(fValue)); +} + +void CLib3MFInterfaceJournalEntry::addDoubleResult(const std::string & sName, const Lib3MF_double dValue) +{ + addResult(sName, "double", std::to_string(dValue)); +} + +void CLib3MFInterfaceJournalEntry::addPointerResult(const std::string & sName, const Lib3MF_pvoid pValue) +{ + addResult(sName, "pointer", std::to_string(reinterpret_cast(pValue))); +} + +void CLib3MFInterfaceJournalEntry::addStringResult(const std::string & sName, const char * pValue) +{ + if (pValue != nullptr) { + addResult(sName, "string", pValue); + } + else { + addResult(sName, "nullstring", ""); + } +} + +void CLib3MFInterfaceJournalEntry::addHandleResult(const std::string & sName, const Lib3MFHandle pHandle) +{ + addResult(sName, "handle", Lib3MFHandleToHex(pHandle)); +} + +void CLib3MFInterfaceJournalEntry::addEnumResult(const std::string & sName, const std::string & sEnumType, const Lib3MF_int32 nValue) +{ + addResult(sName, "enum" + sEnumType, std::to_string(nValue)); +} + + +CLib3MFInterfaceJournal::CLib3MFInterfaceJournal (const std::string & sFileName) + : m_sFileName (sFileName) +{ + m_StartTime = std::chrono::high_resolution_clock::now(); + m_Stream.open (sFileName, std::ios::out); + m_Stream << "\n"; + m_Stream << "\n"; + m_Stream << "\n"; + +} + +CLib3MFInterfaceJournal::~CLib3MFInterfaceJournal () +{ + m_Stream << "\n"; +} + +PLib3MFInterfaceJournalEntry CLib3MFInterfaceJournal::beginClassMethod(const Lib3MFHandle pHandle, const std::string & sClassName, const std::string & sMethodName) +{ + return std::make_shared(this, sClassName, sMethodName, pHandle); +} + +PLib3MFInterfaceJournalEntry CLib3MFInterfaceJournal::beginStaticFunction(const std::string & sMethodName) +{ + return std::make_shared(this, "", sMethodName, nullptr); +} + +void CLib3MFInterfaceJournal::writeEntry (CLib3MFInterfaceJournalEntry * pEntry) +{ + if (pEntry == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + + std::string sXMLString = pEntry->getXMLString(); + m_Mutex.lock(); + try { + m_Stream << sXMLString; + m_Stream << "\n"; + + m_Mutex.unlock(); + } + catch (...) { + m_Mutex.unlock(); + } +} + +Lib3MF_uint64 CLib3MFInterfaceJournal::getTimeStamp () +{ + auto currentTime = std::chrono::high_resolution_clock::now(); + if (m_StartTime < currentTime) { + auto duration = currentTime - m_StartTime; + auto milliSeconds = std::chrono::duration_cast (duration); + + return (Lib3MF_uint64) milliSeconds.count(); + } + else { + return 0; + } + +} + diff --git a/Source/lib3mf_interfacewrapper.cpp b/Source/lib3mf_interfacewrapper.cpp new file mode 100644 index 0000000..5f2810b --- /dev/null +++ b/Source/lib3mf_interfacewrapper.cpp @@ -0,0 +1,13441 @@ +/*++ + +Copyright (C) 2019 3MF Consortium (Original Author) + +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. + +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 HOLDER 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. + +This file has been generated by the Automatic Component Toolkit (ACT) version 1.6.0. + +Abstract: This is an autogenerated C++ implementation file in order to allow easy +development of the 3MF Library. The functions in this file need to be implemented. It needs to be generated only once. + +Interface version: 2.2.0 + +*/ + +#include "lib3mf_abi.hpp" +#include "lib3mf_interfaces.hpp" +#include "lib3mf_interfaceexception.hpp" +#include "lib3mf_interfacejournal.hpp" + +#include + +using namespace Lib3MF::Impl; + +PLib3MFInterfaceJournal m_GlobalJournal; + +Lib3MFResult handleLib3MFException(IBase * pIBaseClass, ELib3MFInterfaceException & Exception, CLib3MFInterfaceJournalEntry * pJournalEntry = nullptr) +{ + Lib3MFResult errorCode = Exception.getErrorCode(); + + if (pJournalEntry != nullptr) + pJournalEntry->writeError(errorCode); + + if (pIBaseClass != nullptr) + pIBaseClass->RegisterErrorMessage(Exception.what()); + + return errorCode; +} + +Lib3MFResult handleStdException(IBase * pIBaseClass, std::exception & Exception, CLib3MFInterfaceJournalEntry * pJournalEntry = nullptr) +{ + Lib3MFResult errorCode = LIB3MF_ERROR_GENERICEXCEPTION; + + if (pJournalEntry != nullptr) + pJournalEntry->writeError(errorCode); + + if (pIBaseClass != nullptr) + pIBaseClass->RegisterErrorMessage(Exception.what()); + + return errorCode; +} + +Lib3MFResult handleUnhandledException(IBase * pIBaseClass, CLib3MFInterfaceJournalEntry * pJournalEntry = nullptr) +{ + Lib3MFResult errorCode = LIB3MF_ERROR_GENERICEXCEPTION; + + if (pJournalEntry != nullptr) + pJournalEntry->writeError(errorCode); + + if (pIBaseClass != nullptr) + pIBaseClass->RegisterErrorMessage("Unhandled Exception"); + + return errorCode; +} + + + +/************************************************************************************************************************* + Class implementation for Base +**************************************************************************************************************************/ + +/************************************************************************************************************************* + Class implementation for Writer +**************************************************************************************************************************/ +Lib3MFResult lib3mf_writer_writetofile(Lib3MF_Writer pWriter, const char * pFilename) +{ + IBase* pIBaseClass = (IBase *)pWriter; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pWriter, "Writer", "WriteToFile"); + pJournalEntry->addStringParameter("Filename", pFilename); + } + if (pFilename == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sFilename(pFilename); + IWriter* pIWriter = dynamic_cast(pIBaseClass); + if (!pIWriter) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIWriter->WriteToFile(sFilename); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_writer_getstreamsize(Lib3MF_Writer pWriter, Lib3MF_uint64 * pStreamSize) +{ + IBase* pIBaseClass = (IBase *)pWriter; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pWriter, "Writer", "GetStreamSize"); + } + if (pStreamSize == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IWriter* pIWriter = dynamic_cast(pIBaseClass); + if (!pIWriter) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pStreamSize = pIWriter->GetStreamSize(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt64Result("StreamSize", *pStreamSize); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_writer_writetobuffer(Lib3MF_Writer pWriter, const Lib3MF_uint64 nBufferBufferSize, Lib3MF_uint64* pBufferNeededCount, Lib3MF_uint8 * pBufferBuffer) +{ + IBase* pIBaseClass = (IBase *)pWriter; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pWriter, "Writer", "WriteToBuffer"); + } + if ((!pBufferBuffer) && !(pBufferNeededCount)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IWriter* pIWriter = dynamic_cast(pIBaseClass); + if (!pIWriter) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIWriter->WriteToBuffer(nBufferBufferSize, pBufferNeededCount, pBufferBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_writer_writetocallback(Lib3MF_Writer pWriter, Lib3MFWriteCallback pTheWriteCallback, Lib3MFSeekCallback pTheSeekCallback, Lib3MF_pvoid pUserData) +{ + IBase* pIBaseClass = (IBase *)pWriter; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pWriter, "Writer", "WriteToCallback"); + pJournalEntry->addPointerParameter("UserData", pUserData); + } + IWriter* pIWriter = dynamic_cast(pIBaseClass); + if (!pIWriter) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIWriter->WriteToCallback(pTheWriteCallback, pTheSeekCallback, pUserData); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_writer_setprogresscallback(Lib3MF_Writer pWriter, Lib3MFProgressCallback pProgressCallback, Lib3MF_pvoid pUserData) +{ + IBase* pIBaseClass = (IBase *)pWriter; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pWriter, "Writer", "SetProgressCallback"); + pJournalEntry->addPointerParameter("UserData", pUserData); + } + IWriter* pIWriter = dynamic_cast(pIBaseClass); + if (!pIWriter) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIWriter->SetProgressCallback(pProgressCallback, pUserData); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_writer_getdecimalprecision(Lib3MF_Writer pWriter, Lib3MF_uint32 * pDecimalPrecision) +{ + IBase* pIBaseClass = (IBase *)pWriter; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pWriter, "Writer", "GetDecimalPrecision"); + } + if (pDecimalPrecision == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IWriter* pIWriter = dynamic_cast(pIBaseClass); + if (!pIWriter) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pDecimalPrecision = pIWriter->GetDecimalPrecision(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("DecimalPrecision", *pDecimalPrecision); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_writer_setdecimalprecision(Lib3MF_Writer pWriter, Lib3MF_uint32 nDecimalPrecision) +{ + IBase* pIBaseClass = (IBase *)pWriter; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pWriter, "Writer", "SetDecimalPrecision"); + pJournalEntry->addUInt32Parameter("DecimalPrecision", nDecimalPrecision); + } + IWriter* pIWriter = dynamic_cast(pIBaseClass); + if (!pIWriter) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIWriter->SetDecimalPrecision(nDecimalPrecision); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_writer_setstrictmodeactive(Lib3MF_Writer pWriter, bool bStrictModeActive) +{ + IBase* pIBaseClass = (IBase *)pWriter; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pWriter, "Writer", "SetStrictModeActive"); + pJournalEntry->addBooleanParameter("StrictModeActive", bStrictModeActive); + } + IWriter* pIWriter = dynamic_cast(pIBaseClass); + if (!pIWriter) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIWriter->SetStrictModeActive(bStrictModeActive); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_writer_getstrictmodeactive(Lib3MF_Writer pWriter, bool * pStrictModeActive) +{ + IBase* pIBaseClass = (IBase *)pWriter; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pWriter, "Writer", "GetStrictModeActive"); + } + if (pStrictModeActive == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IWriter* pIWriter = dynamic_cast(pIBaseClass); + if (!pIWriter) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pStrictModeActive = pIWriter->GetStrictModeActive(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addBooleanResult("StrictModeActive", *pStrictModeActive); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_writer_getwarning(Lib3MF_Writer pWriter, Lib3MF_uint32 nIndex, Lib3MF_uint32 * pErrorCode, const Lib3MF_uint32 nWarningBufferSize, Lib3MF_uint32* pWarningNeededChars, char * pWarningBuffer) +{ + IBase* pIBaseClass = (IBase *)pWriter; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pWriter, "Writer", "GetWarning"); + pJournalEntry->addUInt32Parameter("Index", nIndex); + } + if (!pErrorCode) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if ( (!pWarningBuffer) && !(pWarningNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sWarning(""); + IWriter* pIWriter = dynamic_cast(pIBaseClass); + if (!pIWriter) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + sWarning = pIWriter->GetWarning(nIndex, *pErrorCode); + + if (pWarningNeededChars) + *pWarningNeededChars = (Lib3MF_uint32) (sWarning.size()+1); + if (pWarningBuffer) { + if (sWarning.size() >= nWarningBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iWarning = 0; iWarning < sWarning.size(); iWarning++) + pWarningBuffer[iWarning] = sWarning[iWarning]; + pWarningBuffer[sWarning.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("ErrorCode", *pErrorCode); + pJournalEntry->addStringResult("Warning", sWarning.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_writer_getwarningcount(Lib3MF_Writer pWriter, Lib3MF_uint32 * pCount) +{ + IBase* pIBaseClass = (IBase *)pWriter; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pWriter, "Writer", "GetWarningCount"); + } + if (pCount == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IWriter* pIWriter = dynamic_cast(pIBaseClass); + if (!pIWriter) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pCount = pIWriter->GetWarningCount(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("Count", *pCount); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_writer_addkeywrappingcallback(Lib3MF_Writer pWriter, const char * pConsumerID, Lib3MFKeyWrappingCallback pTheCallback, Lib3MF_pvoid pUserData) +{ + IBase* pIBaseClass = (IBase *)pWriter; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pWriter, "Writer", "AddKeyWrappingCallback"); + pJournalEntry->addStringParameter("ConsumerID", pConsumerID); + pJournalEntry->addPointerParameter("UserData", pUserData); + } + if (pConsumerID == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sConsumerID(pConsumerID); + IWriter* pIWriter = dynamic_cast(pIBaseClass); + if (!pIWriter) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIWriter->AddKeyWrappingCallback(sConsumerID, pTheCallback, pUserData); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_writer_setcontentencryptioncallback(Lib3MF_Writer pWriter, Lib3MFContentEncryptionCallback pTheCallback, Lib3MF_pvoid pUserData) +{ + IBase* pIBaseClass = (IBase *)pWriter; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pWriter, "Writer", "SetContentEncryptionCallback"); + pJournalEntry->addPointerParameter("UserData", pUserData); + } + IWriter* pIWriter = dynamic_cast(pIBaseClass); + if (!pIWriter) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIWriter->SetContentEncryptionCallback(pTheCallback, pUserData); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for Reader +**************************************************************************************************************************/ +Lib3MFResult lib3mf_reader_readfromfile(Lib3MF_Reader pReader, const char * pFilename) +{ + IBase* pIBaseClass = (IBase *)pReader; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pReader, "Reader", "ReadFromFile"); + pJournalEntry->addStringParameter("Filename", pFilename); + } + if (pFilename == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sFilename(pFilename); + IReader* pIReader = dynamic_cast(pIBaseClass); + if (!pIReader) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIReader->ReadFromFile(sFilename); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_reader_readfrombuffer(Lib3MF_Reader pReader, Lib3MF_uint64 nBufferBufferSize, const Lib3MF_uint8 * pBufferBuffer) +{ + IBase* pIBaseClass = (IBase *)pReader; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pReader, "Reader", "ReadFromBuffer"); + } + if ( (!pBufferBuffer) && (nBufferBufferSize>0)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IReader* pIReader = dynamic_cast(pIBaseClass); + if (!pIReader) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIReader->ReadFromBuffer(nBufferBufferSize, pBufferBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_reader_readfromcallback(Lib3MF_Reader pReader, Lib3MFReadCallback pTheReadCallback, Lib3MF_uint64 nStreamSize, Lib3MFSeekCallback pTheSeekCallback, Lib3MF_pvoid pUserData) +{ + IBase* pIBaseClass = (IBase *)pReader; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pReader, "Reader", "ReadFromCallback"); + pJournalEntry->addUInt64Parameter("StreamSize", nStreamSize); + pJournalEntry->addPointerParameter("UserData", pUserData); + } + IReader* pIReader = dynamic_cast(pIBaseClass); + if (!pIReader) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIReader->ReadFromCallback(pTheReadCallback, nStreamSize, pTheSeekCallback, pUserData); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_reader_setprogresscallback(Lib3MF_Reader pReader, Lib3MFProgressCallback pProgressCallback, Lib3MF_pvoid pUserData) +{ + IBase* pIBaseClass = (IBase *)pReader; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pReader, "Reader", "SetProgressCallback"); + pJournalEntry->addPointerParameter("UserData", pUserData); + } + IReader* pIReader = dynamic_cast(pIBaseClass); + if (!pIReader) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIReader->SetProgressCallback(pProgressCallback, pUserData); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_reader_addrelationtoread(Lib3MF_Reader pReader, const char * pRelationShipType) +{ + IBase* pIBaseClass = (IBase *)pReader; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pReader, "Reader", "AddRelationToRead"); + pJournalEntry->addStringParameter("RelationShipType", pRelationShipType); + } + if (pRelationShipType == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sRelationShipType(pRelationShipType); + IReader* pIReader = dynamic_cast(pIBaseClass); + if (!pIReader) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIReader->AddRelationToRead(sRelationShipType); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_reader_removerelationtoread(Lib3MF_Reader pReader, const char * pRelationShipType) +{ + IBase* pIBaseClass = (IBase *)pReader; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pReader, "Reader", "RemoveRelationToRead"); + pJournalEntry->addStringParameter("RelationShipType", pRelationShipType); + } + if (pRelationShipType == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sRelationShipType(pRelationShipType); + IReader* pIReader = dynamic_cast(pIBaseClass); + if (!pIReader) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIReader->RemoveRelationToRead(sRelationShipType); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_reader_setstrictmodeactive(Lib3MF_Reader pReader, bool bStrictModeActive) +{ + IBase* pIBaseClass = (IBase *)pReader; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pReader, "Reader", "SetStrictModeActive"); + pJournalEntry->addBooleanParameter("StrictModeActive", bStrictModeActive); + } + IReader* pIReader = dynamic_cast(pIBaseClass); + if (!pIReader) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIReader->SetStrictModeActive(bStrictModeActive); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_reader_getstrictmodeactive(Lib3MF_Reader pReader, bool * pStrictModeActive) +{ + IBase* pIBaseClass = (IBase *)pReader; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pReader, "Reader", "GetStrictModeActive"); + } + if (pStrictModeActive == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IReader* pIReader = dynamic_cast(pIBaseClass); + if (!pIReader) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pStrictModeActive = pIReader->GetStrictModeActive(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addBooleanResult("StrictModeActive", *pStrictModeActive); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_reader_getwarning(Lib3MF_Reader pReader, Lib3MF_uint32 nIndex, Lib3MF_uint32 * pErrorCode, const Lib3MF_uint32 nWarningBufferSize, Lib3MF_uint32* pWarningNeededChars, char * pWarningBuffer) +{ + IBase* pIBaseClass = (IBase *)pReader; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pReader, "Reader", "GetWarning"); + pJournalEntry->addUInt32Parameter("Index", nIndex); + } + if (!pErrorCode) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if ( (!pWarningBuffer) && !(pWarningNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sWarning(""); + IReader* pIReader = dynamic_cast(pIBaseClass); + if (!pIReader) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + sWarning = pIReader->GetWarning(nIndex, *pErrorCode); + + if (pWarningNeededChars) + *pWarningNeededChars = (Lib3MF_uint32) (sWarning.size()+1); + if (pWarningBuffer) { + if (sWarning.size() >= nWarningBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iWarning = 0; iWarning < sWarning.size(); iWarning++) + pWarningBuffer[iWarning] = sWarning[iWarning]; + pWarningBuffer[sWarning.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("ErrorCode", *pErrorCode); + pJournalEntry->addStringResult("Warning", sWarning.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_reader_getwarningcount(Lib3MF_Reader pReader, Lib3MF_uint32 * pCount) +{ + IBase* pIBaseClass = (IBase *)pReader; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pReader, "Reader", "GetWarningCount"); + } + if (pCount == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IReader* pIReader = dynamic_cast(pIBaseClass); + if (!pIReader) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pCount = pIReader->GetWarningCount(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("Count", *pCount); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_reader_addkeywrappingcallback(Lib3MF_Reader pReader, const char * pConsumerID, Lib3MFKeyWrappingCallback pTheCallback, Lib3MF_pvoid pUserData) +{ + IBase* pIBaseClass = (IBase *)pReader; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pReader, "Reader", "AddKeyWrappingCallback"); + pJournalEntry->addStringParameter("ConsumerID", pConsumerID); + pJournalEntry->addPointerParameter("UserData", pUserData); + } + if (pConsumerID == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sConsumerID(pConsumerID); + IReader* pIReader = dynamic_cast(pIBaseClass); + if (!pIReader) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIReader->AddKeyWrappingCallback(sConsumerID, pTheCallback, pUserData); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_reader_setcontentencryptioncallback(Lib3MF_Reader pReader, Lib3MFContentEncryptionCallback pTheCallback, Lib3MF_pvoid pUserData) +{ + IBase* pIBaseClass = (IBase *)pReader; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pReader, "Reader", "SetContentEncryptionCallback"); + pJournalEntry->addPointerParameter("UserData", pUserData); + } + IReader* pIReader = dynamic_cast(pIBaseClass); + if (!pIReader) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIReader->SetContentEncryptionCallback(pTheCallback, pUserData); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for PackagePart +**************************************************************************************************************************/ +Lib3MFResult lib3mf_packagepart_getpath(Lib3MF_PackagePart pPackagePart, const Lib3MF_uint32 nPathBufferSize, Lib3MF_uint32* pPathNeededChars, char * pPathBuffer) +{ + IBase* pIBaseClass = (IBase *)pPackagePart; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pPackagePart, "PackagePart", "GetPath"); + } + if ( (!pPathBuffer) && !(pPathNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sPath(""); + IPackagePart* pIPackagePart = dynamic_cast(pIBaseClass); + if (!pIPackagePart) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + sPath = pIPackagePart->GetPath(); + + if (pPathNeededChars) + *pPathNeededChars = (Lib3MF_uint32) (sPath.size()+1); + if (pPathBuffer) { + if (sPath.size() >= nPathBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iPath = 0; iPath < sPath.size(); iPath++) + pPathBuffer[iPath] = sPath[iPath]; + pPathBuffer[sPath.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addStringResult("Path", sPath.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_packagepart_setpath(Lib3MF_PackagePart pPackagePart, const char * pPath) +{ + IBase* pIBaseClass = (IBase *)pPackagePart; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pPackagePart, "PackagePart", "SetPath"); + pJournalEntry->addStringParameter("Path", pPath); + } + if (pPath == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sPath(pPath); + IPackagePart* pIPackagePart = dynamic_cast(pIBaseClass); + if (!pIPackagePart) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIPackagePart->SetPath(sPath); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for Resource +**************************************************************************************************************************/ +Lib3MFResult lib3mf_resource_getresourceid(Lib3MF_Resource pResource, Lib3MF_uint32 * pUniqueResourceID) +{ + IBase* pIBaseClass = (IBase *)pResource; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pResource, "Resource", "GetResourceID"); + } + if (pUniqueResourceID == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IResource* pIResource = dynamic_cast(pIBaseClass); + if (!pIResource) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pUniqueResourceID = pIResource->GetResourceID(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("UniqueResourceID", *pUniqueResourceID); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_resource_getuniqueresourceid(Lib3MF_Resource pResource, Lib3MF_uint32 * pUniqueResourceID) +{ + IBase* pIBaseClass = (IBase *)pResource; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pResource, "Resource", "GetUniqueResourceID"); + } + if (pUniqueResourceID == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IResource* pIResource = dynamic_cast(pIBaseClass); + if (!pIResource) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pUniqueResourceID = pIResource->GetUniqueResourceID(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("UniqueResourceID", *pUniqueResourceID); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_resource_packagepart(Lib3MF_Resource pResource, Lib3MF_PackagePart * pPackagePart) +{ + IBase* pIBaseClass = (IBase *)pResource; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pResource, "Resource", "PackagePart"); + } + if (pPackagePart == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBasePackagePart(nullptr); + IResource* pIResource = dynamic_cast(pIBaseClass); + if (!pIResource) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBasePackagePart = pIResource->PackagePart(); + + *pPackagePart = (IBase*)(pBasePackagePart); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("PackagePart", *pPackagePart); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_resource_setpackagepart(Lib3MF_Resource pResource, Lib3MF_PackagePart pPackagePart) +{ + IBase* pIBaseClass = (IBase *)pResource; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pResource, "Resource", "SetPackagePart"); + pJournalEntry->addHandleParameter("PackagePart", pPackagePart); + } + IBase* pIBaseClassPackagePart = (IBase *)pPackagePart; + IPackagePart* pIPackagePart = dynamic_cast(pIBaseClassPackagePart); + if (!pIPackagePart) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDCAST); + + IResource* pIResource = dynamic_cast(pIBaseClass); + if (!pIResource) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIResource->SetPackagePart(pIPackagePart); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_resource_getmodelresourceid(Lib3MF_Resource pResource, Lib3MF_uint32 * pModelResourceId) +{ + IBase* pIBaseClass = (IBase *)pResource; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pResource, "Resource", "GetModelResourceID"); + } + if (pModelResourceId == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IResource* pIResource = dynamic_cast(pIBaseClass); + if (!pIResource) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pModelResourceId = pIResource->GetModelResourceID(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("ModelResourceId", *pModelResourceId); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for ResourceIterator +**************************************************************************************************************************/ +Lib3MFResult lib3mf_resourceiterator_movenext(Lib3MF_ResourceIterator pResourceIterator, bool * pHasNext) +{ + IBase* pIBaseClass = (IBase *)pResourceIterator; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pResourceIterator, "ResourceIterator", "MoveNext"); + } + if (pHasNext == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IResourceIterator* pIResourceIterator = dynamic_cast(pIBaseClass); + if (!pIResourceIterator) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pHasNext = pIResourceIterator->MoveNext(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addBooleanResult("HasNext", *pHasNext); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_resourceiterator_moveprevious(Lib3MF_ResourceIterator pResourceIterator, bool * pHasPrevious) +{ + IBase* pIBaseClass = (IBase *)pResourceIterator; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pResourceIterator, "ResourceIterator", "MovePrevious"); + } + if (pHasPrevious == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IResourceIterator* pIResourceIterator = dynamic_cast(pIBaseClass); + if (!pIResourceIterator) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pHasPrevious = pIResourceIterator->MovePrevious(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addBooleanResult("HasPrevious", *pHasPrevious); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_resourceiterator_getcurrent(Lib3MF_ResourceIterator pResourceIterator, Lib3MF_Resource * pResource) +{ + IBase* pIBaseClass = (IBase *)pResourceIterator; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pResourceIterator, "ResourceIterator", "GetCurrent"); + } + if (pResource == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseResource(nullptr); + IResourceIterator* pIResourceIterator = dynamic_cast(pIBaseClass); + if (!pIResourceIterator) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseResource = pIResourceIterator->GetCurrent(); + + *pResource = (IBase*)(pBaseResource); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("Resource", *pResource); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_resourceiterator_clone(Lib3MF_ResourceIterator pResourceIterator, Lib3MF_ResourceIterator * pOutResourceIterator) +{ + IBase* pIBaseClass = (IBase *)pResourceIterator; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pResourceIterator, "ResourceIterator", "Clone"); + } + if (pOutResourceIterator == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseOutResourceIterator(nullptr); + IResourceIterator* pIResourceIterator = dynamic_cast(pIBaseClass); + if (!pIResourceIterator) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseOutResourceIterator = pIResourceIterator->Clone(); + + *pOutResourceIterator = (IBase*)(pBaseOutResourceIterator); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("OutResourceIterator", *pOutResourceIterator); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_resourceiterator_count(Lib3MF_ResourceIterator pResourceIterator, Lib3MF_uint64 * pCount) +{ + IBase* pIBaseClass = (IBase *)pResourceIterator; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pResourceIterator, "ResourceIterator", "Count"); + } + if (pCount == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IResourceIterator* pIResourceIterator = dynamic_cast(pIBaseClass); + if (!pIResourceIterator) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pCount = pIResourceIterator->Count(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt64Result("Count", *pCount); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for SliceStackIterator +**************************************************************************************************************************/ +Lib3MFResult lib3mf_slicestackiterator_getcurrentslicestack(Lib3MF_SliceStackIterator pSliceStackIterator, Lib3MF_SliceStack * pResource) +{ + IBase* pIBaseClass = (IBase *)pSliceStackIterator; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pSliceStackIterator, "SliceStackIterator", "GetCurrentSliceStack"); + } + if (pResource == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseResource(nullptr); + ISliceStackIterator* pISliceStackIterator = dynamic_cast(pIBaseClass); + if (!pISliceStackIterator) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseResource = pISliceStackIterator->GetCurrentSliceStack(); + + *pResource = (IBase*)(pBaseResource); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("Resource", *pResource); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for ObjectIterator +**************************************************************************************************************************/ +Lib3MFResult lib3mf_objectiterator_getcurrentobject(Lib3MF_ObjectIterator pObjectIterator, Lib3MF_Object * pResource) +{ + IBase* pIBaseClass = (IBase *)pObjectIterator; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pObjectIterator, "ObjectIterator", "GetCurrentObject"); + } + if (pResource == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseResource(nullptr); + IObjectIterator* pIObjectIterator = dynamic_cast(pIBaseClass); + if (!pIObjectIterator) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseResource = pIObjectIterator->GetCurrentObject(); + + *pResource = (IBase*)(pBaseResource); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("Resource", *pResource); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for MeshObjectIterator +**************************************************************************************************************************/ +Lib3MFResult lib3mf_meshobjectiterator_getcurrentmeshobject(Lib3MF_MeshObjectIterator pMeshObjectIterator, Lib3MF_MeshObject * pResource) +{ + IBase* pIBaseClass = (IBase *)pMeshObjectIterator; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMeshObjectIterator, "MeshObjectIterator", "GetCurrentMeshObject"); + } + if (pResource == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseResource(nullptr); + IMeshObjectIterator* pIMeshObjectIterator = dynamic_cast(pIBaseClass); + if (!pIMeshObjectIterator) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseResource = pIMeshObjectIterator->GetCurrentMeshObject(); + + *pResource = (IBase*)(pBaseResource); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("Resource", *pResource); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for ComponentsObjectIterator +**************************************************************************************************************************/ +Lib3MFResult lib3mf_componentsobjectiterator_getcurrentcomponentsobject(Lib3MF_ComponentsObjectIterator pComponentsObjectIterator, Lib3MF_ComponentsObject * pResource) +{ + IBase* pIBaseClass = (IBase *)pComponentsObjectIterator; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pComponentsObjectIterator, "ComponentsObjectIterator", "GetCurrentComponentsObject"); + } + if (pResource == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseResource(nullptr); + IComponentsObjectIterator* pIComponentsObjectIterator = dynamic_cast(pIBaseClass); + if (!pIComponentsObjectIterator) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseResource = pIComponentsObjectIterator->GetCurrentComponentsObject(); + + *pResource = (IBase*)(pBaseResource); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("Resource", *pResource); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for Texture2DIterator +**************************************************************************************************************************/ +Lib3MFResult lib3mf_texture2diterator_getcurrenttexture2d(Lib3MF_Texture2DIterator pTexture2DIterator, Lib3MF_Texture2D * pResource) +{ + IBase* pIBaseClass = (IBase *)pTexture2DIterator; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pTexture2DIterator, "Texture2DIterator", "GetCurrentTexture2D"); + } + if (pResource == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseResource(nullptr); + ITexture2DIterator* pITexture2DIterator = dynamic_cast(pIBaseClass); + if (!pITexture2DIterator) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseResource = pITexture2DIterator->GetCurrentTexture2D(); + + *pResource = (IBase*)(pBaseResource); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("Resource", *pResource); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for BaseMaterialGroupIterator +**************************************************************************************************************************/ +Lib3MFResult lib3mf_basematerialgroupiterator_getcurrentbasematerialgroup(Lib3MF_BaseMaterialGroupIterator pBaseMaterialGroupIterator, Lib3MF_BaseMaterialGroup * pResource) +{ + IBase* pIBaseClass = (IBase *)pBaseMaterialGroupIterator; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBaseMaterialGroupIterator, "BaseMaterialGroupIterator", "GetCurrentBaseMaterialGroup"); + } + if (pResource == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseResource(nullptr); + IBaseMaterialGroupIterator* pIBaseMaterialGroupIterator = dynamic_cast(pIBaseClass); + if (!pIBaseMaterialGroupIterator) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseResource = pIBaseMaterialGroupIterator->GetCurrentBaseMaterialGroup(); + + *pResource = (IBase*)(pBaseResource); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("Resource", *pResource); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for ColorGroupIterator +**************************************************************************************************************************/ +Lib3MFResult lib3mf_colorgroupiterator_getcurrentcolorgroup(Lib3MF_ColorGroupIterator pColorGroupIterator, Lib3MF_ColorGroup * pResource) +{ + IBase* pIBaseClass = (IBase *)pColorGroupIterator; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pColorGroupIterator, "ColorGroupIterator", "GetCurrentColorGroup"); + } + if (pResource == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseResource(nullptr); + IColorGroupIterator* pIColorGroupIterator = dynamic_cast(pIBaseClass); + if (!pIColorGroupIterator) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseResource = pIColorGroupIterator->GetCurrentColorGroup(); + + *pResource = (IBase*)(pBaseResource); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("Resource", *pResource); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for Texture2DGroupIterator +**************************************************************************************************************************/ +Lib3MFResult lib3mf_texture2dgroupiterator_getcurrenttexture2dgroup(Lib3MF_Texture2DGroupIterator pTexture2DGroupIterator, Lib3MF_Texture2DGroup * pResource) +{ + IBase* pIBaseClass = (IBase *)pTexture2DGroupIterator; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pTexture2DGroupIterator, "Texture2DGroupIterator", "GetCurrentTexture2DGroup"); + } + if (pResource == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseResource(nullptr); + ITexture2DGroupIterator* pITexture2DGroupIterator = dynamic_cast(pIBaseClass); + if (!pITexture2DGroupIterator) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseResource = pITexture2DGroupIterator->GetCurrentTexture2DGroup(); + + *pResource = (IBase*)(pBaseResource); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("Resource", *pResource); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for CompositeMaterialsIterator +**************************************************************************************************************************/ +Lib3MFResult lib3mf_compositematerialsiterator_getcurrentcompositematerials(Lib3MF_CompositeMaterialsIterator pCompositeMaterialsIterator, Lib3MF_CompositeMaterials * pResource) +{ + IBase* pIBaseClass = (IBase *)pCompositeMaterialsIterator; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pCompositeMaterialsIterator, "CompositeMaterialsIterator", "GetCurrentCompositeMaterials"); + } + if (pResource == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseResource(nullptr); + ICompositeMaterialsIterator* pICompositeMaterialsIterator = dynamic_cast(pIBaseClass); + if (!pICompositeMaterialsIterator) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseResource = pICompositeMaterialsIterator->GetCurrentCompositeMaterials(); + + *pResource = (IBase*)(pBaseResource); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("Resource", *pResource); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for MultiPropertyGroupIterator +**************************************************************************************************************************/ +Lib3MFResult lib3mf_multipropertygroupiterator_getcurrentmultipropertygroup(Lib3MF_MultiPropertyGroupIterator pMultiPropertyGroupIterator, Lib3MF_MultiPropertyGroup * pResource) +{ + IBase* pIBaseClass = (IBase *)pMultiPropertyGroupIterator; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMultiPropertyGroupIterator, "MultiPropertyGroupIterator", "GetCurrentMultiPropertyGroup"); + } + if (pResource == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseResource(nullptr); + IMultiPropertyGroupIterator* pIMultiPropertyGroupIterator = dynamic_cast(pIBaseClass); + if (!pIMultiPropertyGroupIterator) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseResource = pIMultiPropertyGroupIterator->GetCurrentMultiPropertyGroup(); + + *pResource = (IBase*)(pBaseResource); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("Resource", *pResource); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for MetaData +**************************************************************************************************************************/ +Lib3MFResult lib3mf_metadata_getnamespace(Lib3MF_MetaData pMetaData, const Lib3MF_uint32 nNameSpaceBufferSize, Lib3MF_uint32* pNameSpaceNeededChars, char * pNameSpaceBuffer) +{ + IBase* pIBaseClass = (IBase *)pMetaData; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMetaData, "MetaData", "GetNameSpace"); + } + if ( (!pNameSpaceBuffer) && !(pNameSpaceNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sNameSpace(""); + IMetaData* pIMetaData = dynamic_cast(pIBaseClass); + if (!pIMetaData) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + sNameSpace = pIMetaData->GetNameSpace(); + + if (pNameSpaceNeededChars) + *pNameSpaceNeededChars = (Lib3MF_uint32) (sNameSpace.size()+1); + if (pNameSpaceBuffer) { + if (sNameSpace.size() >= nNameSpaceBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iNameSpace = 0; iNameSpace < sNameSpace.size(); iNameSpace++) + pNameSpaceBuffer[iNameSpace] = sNameSpace[iNameSpace]; + pNameSpaceBuffer[sNameSpace.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addStringResult("NameSpace", sNameSpace.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_metadata_setnamespace(Lib3MF_MetaData pMetaData, const char * pNameSpace) +{ + IBase* pIBaseClass = (IBase *)pMetaData; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMetaData, "MetaData", "SetNameSpace"); + pJournalEntry->addStringParameter("NameSpace", pNameSpace); + } + if (pNameSpace == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sNameSpace(pNameSpace); + IMetaData* pIMetaData = dynamic_cast(pIBaseClass); + if (!pIMetaData) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIMetaData->SetNameSpace(sNameSpace); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_metadata_getname(Lib3MF_MetaData pMetaData, const Lib3MF_uint32 nNameBufferSize, Lib3MF_uint32* pNameNeededChars, char * pNameBuffer) +{ + IBase* pIBaseClass = (IBase *)pMetaData; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMetaData, "MetaData", "GetName"); + } + if ( (!pNameBuffer) && !(pNameNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sName(""); + IMetaData* pIMetaData = dynamic_cast(pIBaseClass); + if (!pIMetaData) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + sName = pIMetaData->GetName(); + + if (pNameNeededChars) + *pNameNeededChars = (Lib3MF_uint32) (sName.size()+1); + if (pNameBuffer) { + if (sName.size() >= nNameBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iName = 0; iName < sName.size(); iName++) + pNameBuffer[iName] = sName[iName]; + pNameBuffer[sName.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addStringResult("Name", sName.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_metadata_setname(Lib3MF_MetaData pMetaData, const char * pName) +{ + IBase* pIBaseClass = (IBase *)pMetaData; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMetaData, "MetaData", "SetName"); + pJournalEntry->addStringParameter("Name", pName); + } + if (pName == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sName(pName); + IMetaData* pIMetaData = dynamic_cast(pIBaseClass); + if (!pIMetaData) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIMetaData->SetName(sName); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_metadata_getkey(Lib3MF_MetaData pMetaData, const Lib3MF_uint32 nKeyBufferSize, Lib3MF_uint32* pKeyNeededChars, char * pKeyBuffer) +{ + IBase* pIBaseClass = (IBase *)pMetaData; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMetaData, "MetaData", "GetKey"); + } + if ( (!pKeyBuffer) && !(pKeyNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sKey(""); + IMetaData* pIMetaData = dynamic_cast(pIBaseClass); + if (!pIMetaData) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + sKey = pIMetaData->GetKey(); + + if (pKeyNeededChars) + *pKeyNeededChars = (Lib3MF_uint32) (sKey.size()+1); + if (pKeyBuffer) { + if (sKey.size() >= nKeyBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iKey = 0; iKey < sKey.size(); iKey++) + pKeyBuffer[iKey] = sKey[iKey]; + pKeyBuffer[sKey.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addStringResult("Key", sKey.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_metadata_getmustpreserve(Lib3MF_MetaData pMetaData, bool * pMustPreserve) +{ + IBase* pIBaseClass = (IBase *)pMetaData; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMetaData, "MetaData", "GetMustPreserve"); + } + if (pMustPreserve == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IMetaData* pIMetaData = dynamic_cast(pIBaseClass); + if (!pIMetaData) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pMustPreserve = pIMetaData->GetMustPreserve(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addBooleanResult("MustPreserve", *pMustPreserve); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_metadata_setmustpreserve(Lib3MF_MetaData pMetaData, bool bMustPreserve) +{ + IBase* pIBaseClass = (IBase *)pMetaData; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMetaData, "MetaData", "SetMustPreserve"); + pJournalEntry->addBooleanParameter("MustPreserve", bMustPreserve); + } + IMetaData* pIMetaData = dynamic_cast(pIBaseClass); + if (!pIMetaData) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIMetaData->SetMustPreserve(bMustPreserve); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_metadata_gettype(Lib3MF_MetaData pMetaData, const Lib3MF_uint32 nTypeBufferSize, Lib3MF_uint32* pTypeNeededChars, char * pTypeBuffer) +{ + IBase* pIBaseClass = (IBase *)pMetaData; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMetaData, "MetaData", "GetType"); + } + if ( (!pTypeBuffer) && !(pTypeNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sType(""); + IMetaData* pIMetaData = dynamic_cast(pIBaseClass); + if (!pIMetaData) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + sType = pIMetaData->GetType(); + + if (pTypeNeededChars) + *pTypeNeededChars = (Lib3MF_uint32) (sType.size()+1); + if (pTypeBuffer) { + if (sType.size() >= nTypeBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iType = 0; iType < sType.size(); iType++) + pTypeBuffer[iType] = sType[iType]; + pTypeBuffer[sType.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addStringResult("Type", sType.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_metadata_settype(Lib3MF_MetaData pMetaData, const char * pType) +{ + IBase* pIBaseClass = (IBase *)pMetaData; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMetaData, "MetaData", "SetType"); + pJournalEntry->addStringParameter("Type", pType); + } + if (pType == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sType(pType); + IMetaData* pIMetaData = dynamic_cast(pIBaseClass); + if (!pIMetaData) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIMetaData->SetType(sType); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_metadata_getvalue(Lib3MF_MetaData pMetaData, const Lib3MF_uint32 nValueBufferSize, Lib3MF_uint32* pValueNeededChars, char * pValueBuffer) +{ + IBase* pIBaseClass = (IBase *)pMetaData; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMetaData, "MetaData", "GetValue"); + } + if ( (!pValueBuffer) && !(pValueNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sValue(""); + IMetaData* pIMetaData = dynamic_cast(pIBaseClass); + if (!pIMetaData) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + sValue = pIMetaData->GetValue(); + + if (pValueNeededChars) + *pValueNeededChars = (Lib3MF_uint32) (sValue.size()+1); + if (pValueBuffer) { + if (sValue.size() >= nValueBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iValue = 0; iValue < sValue.size(); iValue++) + pValueBuffer[iValue] = sValue[iValue]; + pValueBuffer[sValue.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addStringResult("Value", sValue.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_metadata_setvalue(Lib3MF_MetaData pMetaData, const char * pValue) +{ + IBase* pIBaseClass = (IBase *)pMetaData; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMetaData, "MetaData", "SetValue"); + pJournalEntry->addStringParameter("Value", pValue); + } + if (pValue == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sValue(pValue); + IMetaData* pIMetaData = dynamic_cast(pIBaseClass); + if (!pIMetaData) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIMetaData->SetValue(sValue); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for MetaDataGroup +**************************************************************************************************************************/ +Lib3MFResult lib3mf_metadatagroup_getmetadatacount(Lib3MF_MetaDataGroup pMetaDataGroup, Lib3MF_uint32 * pCount) +{ + IBase* pIBaseClass = (IBase *)pMetaDataGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMetaDataGroup, "MetaDataGroup", "GetMetaDataCount"); + } + if (pCount == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IMetaDataGroup* pIMetaDataGroup = dynamic_cast(pIBaseClass); + if (!pIMetaDataGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pCount = pIMetaDataGroup->GetMetaDataCount(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("Count", *pCount); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_metadatagroup_getmetadata(Lib3MF_MetaDataGroup pMetaDataGroup, Lib3MF_uint32 nIndex, Lib3MF_MetaData * pMetaData) +{ + IBase* pIBaseClass = (IBase *)pMetaDataGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMetaDataGroup, "MetaDataGroup", "GetMetaData"); + pJournalEntry->addUInt32Parameter("Index", nIndex); + } + if (pMetaData == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseMetaData(nullptr); + IMetaDataGroup* pIMetaDataGroup = dynamic_cast(pIBaseClass); + if (!pIMetaDataGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseMetaData = pIMetaDataGroup->GetMetaData(nIndex); + + *pMetaData = (IBase*)(pBaseMetaData); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("MetaData", *pMetaData); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_metadatagroup_getmetadatabykey(Lib3MF_MetaDataGroup pMetaDataGroup, const char * pNameSpace, const char * pName, Lib3MF_MetaData * pMetaData) +{ + IBase* pIBaseClass = (IBase *)pMetaDataGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMetaDataGroup, "MetaDataGroup", "GetMetaDataByKey"); + pJournalEntry->addStringParameter("NameSpace", pNameSpace); + pJournalEntry->addStringParameter("Name", pName); + } + if (pNameSpace == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (pName == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (pMetaData == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sNameSpace(pNameSpace); + std::string sName(pName); + IBase* pBaseMetaData(nullptr); + IMetaDataGroup* pIMetaDataGroup = dynamic_cast(pIBaseClass); + if (!pIMetaDataGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseMetaData = pIMetaDataGroup->GetMetaDataByKey(sNameSpace, sName); + + *pMetaData = (IBase*)(pBaseMetaData); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("MetaData", *pMetaData); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_metadatagroup_removemetadatabyindex(Lib3MF_MetaDataGroup pMetaDataGroup, Lib3MF_uint32 nIndex) +{ + IBase* pIBaseClass = (IBase *)pMetaDataGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMetaDataGroup, "MetaDataGroup", "RemoveMetaDataByIndex"); + pJournalEntry->addUInt32Parameter("Index", nIndex); + } + IMetaDataGroup* pIMetaDataGroup = dynamic_cast(pIBaseClass); + if (!pIMetaDataGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIMetaDataGroup->RemoveMetaDataByIndex(nIndex); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_metadatagroup_removemetadata(Lib3MF_MetaDataGroup pMetaDataGroup, Lib3MF_MetaData pTheMetaData) +{ + IBase* pIBaseClass = (IBase *)pMetaDataGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMetaDataGroup, "MetaDataGroup", "RemoveMetaData"); + pJournalEntry->addHandleParameter("TheMetaData", pTheMetaData); + } + IBase* pIBaseClassTheMetaData = (IBase *)pTheMetaData; + IMetaData* pITheMetaData = dynamic_cast(pIBaseClassTheMetaData); + if (!pITheMetaData) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDCAST); + + IMetaDataGroup* pIMetaDataGroup = dynamic_cast(pIBaseClass); + if (!pIMetaDataGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIMetaDataGroup->RemoveMetaData(pITheMetaData); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_metadatagroup_addmetadata(Lib3MF_MetaDataGroup pMetaDataGroup, const char * pNameSpace, const char * pName, const char * pValue, const char * pType, bool bMustPreserve, Lib3MF_MetaData * pMetaData) +{ + IBase* pIBaseClass = (IBase *)pMetaDataGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMetaDataGroup, "MetaDataGroup", "AddMetaData"); + pJournalEntry->addStringParameter("NameSpace", pNameSpace); + pJournalEntry->addStringParameter("Name", pName); + pJournalEntry->addStringParameter("Value", pValue); + pJournalEntry->addStringParameter("Type", pType); + pJournalEntry->addBooleanParameter("MustPreserve", bMustPreserve); + } + if (pNameSpace == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (pName == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (pValue == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (pType == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (pMetaData == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sNameSpace(pNameSpace); + std::string sName(pName); + std::string sValue(pValue); + std::string sType(pType); + IBase* pBaseMetaData(nullptr); + IMetaDataGroup* pIMetaDataGroup = dynamic_cast(pIBaseClass); + if (!pIMetaDataGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseMetaData = pIMetaDataGroup->AddMetaData(sNameSpace, sName, sValue, sType, bMustPreserve); + + *pMetaData = (IBase*)(pBaseMetaData); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("MetaData", *pMetaData); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for Object +**************************************************************************************************************************/ +Lib3MFResult lib3mf_object_gettype(Lib3MF_Object pObject, eLib3MFObjectType * pObjectType) +{ + IBase* pIBaseClass = (IBase *)pObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pObject, "Object", "GetType"); + } + if (pObjectType == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IObject* pIObject = dynamic_cast(pIBaseClass); + if (!pIObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pObjectType = pIObject->GetType(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addEnumResult("ObjectType", "ObjectType", (Lib3MF_int32)(*pObjectType)); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_object_settype(Lib3MF_Object pObject, eLib3MFObjectType eObjectType) +{ + IBase* pIBaseClass = (IBase *)pObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pObject, "Object", "SetType"); + pJournalEntry->addEnumParameter("ObjectType", "ObjectType", (Lib3MF_int32)(eObjectType)); + } + IObject* pIObject = dynamic_cast(pIBaseClass); + if (!pIObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIObject->SetType(eObjectType); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_object_getname(Lib3MF_Object pObject, const Lib3MF_uint32 nNameBufferSize, Lib3MF_uint32* pNameNeededChars, char * pNameBuffer) +{ + IBase* pIBaseClass = (IBase *)pObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pObject, "Object", "GetName"); + } + if ( (!pNameBuffer) && !(pNameNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sName(""); + IObject* pIObject = dynamic_cast(pIBaseClass); + if (!pIObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + sName = pIObject->GetName(); + + if (pNameNeededChars) + *pNameNeededChars = (Lib3MF_uint32) (sName.size()+1); + if (pNameBuffer) { + if (sName.size() >= nNameBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iName = 0; iName < sName.size(); iName++) + pNameBuffer[iName] = sName[iName]; + pNameBuffer[sName.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addStringResult("Name", sName.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_object_setname(Lib3MF_Object pObject, const char * pName) +{ + IBase* pIBaseClass = (IBase *)pObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pObject, "Object", "SetName"); + pJournalEntry->addStringParameter("Name", pName); + } + if (pName == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sName(pName); + IObject* pIObject = dynamic_cast(pIBaseClass); + if (!pIObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIObject->SetName(sName); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_object_getpartnumber(Lib3MF_Object pObject, const Lib3MF_uint32 nPartNumberBufferSize, Lib3MF_uint32* pPartNumberNeededChars, char * pPartNumberBuffer) +{ + IBase* pIBaseClass = (IBase *)pObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pObject, "Object", "GetPartNumber"); + } + if ( (!pPartNumberBuffer) && !(pPartNumberNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sPartNumber(""); + IObject* pIObject = dynamic_cast(pIBaseClass); + if (!pIObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + sPartNumber = pIObject->GetPartNumber(); + + if (pPartNumberNeededChars) + *pPartNumberNeededChars = (Lib3MF_uint32) (sPartNumber.size()+1); + if (pPartNumberBuffer) { + if (sPartNumber.size() >= nPartNumberBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iPartNumber = 0; iPartNumber < sPartNumber.size(); iPartNumber++) + pPartNumberBuffer[iPartNumber] = sPartNumber[iPartNumber]; + pPartNumberBuffer[sPartNumber.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addStringResult("PartNumber", sPartNumber.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_object_setpartnumber(Lib3MF_Object pObject, const char * pPartNumber) +{ + IBase* pIBaseClass = (IBase *)pObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pObject, "Object", "SetPartNumber"); + pJournalEntry->addStringParameter("PartNumber", pPartNumber); + } + if (pPartNumber == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sPartNumber(pPartNumber); + IObject* pIObject = dynamic_cast(pIBaseClass); + if (!pIObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIObject->SetPartNumber(sPartNumber); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_object_ismeshobject(Lib3MF_Object pObject, bool * pIsMeshObject) +{ + IBase* pIBaseClass = (IBase *)pObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pObject, "Object", "IsMeshObject"); + } + if (pIsMeshObject == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IObject* pIObject = dynamic_cast(pIBaseClass); + if (!pIObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pIsMeshObject = pIObject->IsMeshObject(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addBooleanResult("IsMeshObject", *pIsMeshObject); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_object_iscomponentsobject(Lib3MF_Object pObject, bool * pIsComponentsObject) +{ + IBase* pIBaseClass = (IBase *)pObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pObject, "Object", "IsComponentsObject"); + } + if (pIsComponentsObject == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IObject* pIObject = dynamic_cast(pIBaseClass); + if (!pIObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pIsComponentsObject = pIObject->IsComponentsObject(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addBooleanResult("IsComponentsObject", *pIsComponentsObject); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_object_isvalid(Lib3MF_Object pObject, bool * pIsValid) +{ + IBase* pIBaseClass = (IBase *)pObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pObject, "Object", "IsValid"); + } + if (pIsValid == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IObject* pIObject = dynamic_cast(pIBaseClass); + if (!pIObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pIsValid = pIObject->IsValid(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addBooleanResult("IsValid", *pIsValid); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_object_setattachmentasthumbnail(Lib3MF_Object pObject, Lib3MF_Attachment pAttachment) +{ + IBase* pIBaseClass = (IBase *)pObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pObject, "Object", "SetAttachmentAsThumbnail"); + pJournalEntry->addHandleParameter("Attachment", pAttachment); + } + IBase* pIBaseClassAttachment = (IBase *)pAttachment; + IAttachment* pIAttachment = dynamic_cast(pIBaseClassAttachment); + if (!pIAttachment) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDCAST); + + IObject* pIObject = dynamic_cast(pIBaseClass); + if (!pIObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIObject->SetAttachmentAsThumbnail(pIAttachment); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_object_getthumbnailattachment(Lib3MF_Object pObject, Lib3MF_Attachment * pAttachment) +{ + IBase* pIBaseClass = (IBase *)pObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pObject, "Object", "GetThumbnailAttachment"); + } + if (pAttachment == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseAttachment(nullptr); + IObject* pIObject = dynamic_cast(pIBaseClass); + if (!pIObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseAttachment = pIObject->GetThumbnailAttachment(); + + *pAttachment = (IBase*)(pBaseAttachment); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("Attachment", *pAttachment); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_object_clearthumbnailattachment(Lib3MF_Object pObject) +{ + IBase* pIBaseClass = (IBase *)pObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pObject, "Object", "ClearThumbnailAttachment"); + } + IObject* pIObject = dynamic_cast(pIBaseClass); + if (!pIObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIObject->ClearThumbnailAttachment(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_object_getoutbox(Lib3MF_Object pObject, sLib3MFBox * pOutbox) +{ + IBase* pIBaseClass = (IBase *)pObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pObject, "Object", "GetOutbox"); + } + if (pOutbox == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IObject* pIObject = dynamic_cast(pIBaseClass); + if (!pIObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pOutbox = pIObject->GetOutbox(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_object_getuuid(Lib3MF_Object pObject, bool * pHasUUID, const Lib3MF_uint32 nUUIDBufferSize, Lib3MF_uint32* pUUIDNeededChars, char * pUUIDBuffer) +{ + IBase* pIBaseClass = (IBase *)pObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pObject, "Object", "GetUUID"); + } + if (!pHasUUID) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if ( (!pUUIDBuffer) && !(pUUIDNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sUUID(""); + IObject* pIObject = dynamic_cast(pIBaseClass); + if (!pIObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + sUUID = pIObject->GetUUID(*pHasUUID); + + if (pUUIDNeededChars) + *pUUIDNeededChars = (Lib3MF_uint32) (sUUID.size()+1); + if (pUUIDBuffer) { + if (sUUID.size() >= nUUIDBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iUUID = 0; iUUID < sUUID.size(); iUUID++) + pUUIDBuffer[iUUID] = sUUID[iUUID]; + pUUIDBuffer[sUUID.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addBooleanResult("HasUUID", *pHasUUID); + pJournalEntry->addStringResult("UUID", sUUID.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_object_setuuid(Lib3MF_Object pObject, const char * pUUID) +{ + IBase* pIBaseClass = (IBase *)pObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pObject, "Object", "SetUUID"); + pJournalEntry->addStringParameter("UUID", pUUID); + } + if (pUUID == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sUUID(pUUID); + IObject* pIObject = dynamic_cast(pIBaseClass); + if (!pIObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIObject->SetUUID(sUUID); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_object_getmetadatagroup(Lib3MF_Object pObject, Lib3MF_MetaDataGroup * pMetaDataGroup) +{ + IBase* pIBaseClass = (IBase *)pObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pObject, "Object", "GetMetaDataGroup"); + } + if (pMetaDataGroup == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseMetaDataGroup(nullptr); + IObject* pIObject = dynamic_cast(pIBaseClass); + if (!pIObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseMetaDataGroup = pIObject->GetMetaDataGroup(); + + *pMetaDataGroup = (IBase*)(pBaseMetaDataGroup); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("MetaDataGroup", *pMetaDataGroup); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_object_setslicesmeshresolution(Lib3MF_Object pObject, eLib3MFSlicesMeshResolution eMeshResolution) +{ + IBase* pIBaseClass = (IBase *)pObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pObject, "Object", "SetSlicesMeshResolution"); + pJournalEntry->addEnumParameter("MeshResolution", "SlicesMeshResolution", (Lib3MF_int32)(eMeshResolution)); + } + IObject* pIObject = dynamic_cast(pIBaseClass); + if (!pIObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIObject->SetSlicesMeshResolution(eMeshResolution); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_object_getslicesmeshresolution(Lib3MF_Object pObject, eLib3MFSlicesMeshResolution * pMeshResolution) +{ + IBase* pIBaseClass = (IBase *)pObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pObject, "Object", "GetSlicesMeshResolution"); + } + if (pMeshResolution == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IObject* pIObject = dynamic_cast(pIBaseClass); + if (!pIObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pMeshResolution = pIObject->GetSlicesMeshResolution(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addEnumResult("MeshResolution", "SlicesMeshResolution", (Lib3MF_int32)(*pMeshResolution)); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_object_hasslices(Lib3MF_Object pObject, bool bRecursive, bool * pHasSlices) +{ + IBase* pIBaseClass = (IBase *)pObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pObject, "Object", "HasSlices"); + pJournalEntry->addBooleanParameter("Recursive", bRecursive); + } + if (pHasSlices == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IObject* pIObject = dynamic_cast(pIBaseClass); + if (!pIObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pHasSlices = pIObject->HasSlices(bRecursive); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addBooleanResult("HasSlices", *pHasSlices); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_object_clearslicestack(Lib3MF_Object pObject) +{ + IBase* pIBaseClass = (IBase *)pObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pObject, "Object", "ClearSliceStack"); + } + IObject* pIObject = dynamic_cast(pIBaseClass); + if (!pIObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIObject->ClearSliceStack(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_object_getslicestack(Lib3MF_Object pObject, Lib3MF_SliceStack * pSliceStackInstance) +{ + IBase* pIBaseClass = (IBase *)pObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pObject, "Object", "GetSliceStack"); + } + if (pSliceStackInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseSliceStackInstance(nullptr); + IObject* pIObject = dynamic_cast(pIBaseClass); + if (!pIObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseSliceStackInstance = pIObject->GetSliceStack(); + + *pSliceStackInstance = (IBase*)(pBaseSliceStackInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("SliceStackInstance", *pSliceStackInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_object_assignslicestack(Lib3MF_Object pObject, Lib3MF_SliceStack pSliceStackInstance) +{ + IBase* pIBaseClass = (IBase *)pObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pObject, "Object", "AssignSliceStack"); + pJournalEntry->addHandleParameter("SliceStackInstance", pSliceStackInstance); + } + IBase* pIBaseClassSliceStackInstance = (IBase *)pSliceStackInstance; + ISliceStack* pISliceStackInstance = dynamic_cast(pIBaseClassSliceStackInstance); + if (!pISliceStackInstance) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDCAST); + + IObject* pIObject = dynamic_cast(pIBaseClass); + if (!pIObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIObject->AssignSliceStack(pISliceStackInstance); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for MeshObject +**************************************************************************************************************************/ +Lib3MFResult lib3mf_meshobject_getvertexcount(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 * pVertexCount) +{ + IBase* pIBaseClass = (IBase *)pMeshObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMeshObject, "MeshObject", "GetVertexCount"); + } + if (pVertexCount == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IMeshObject* pIMeshObject = dynamic_cast(pIBaseClass); + if (!pIMeshObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pVertexCount = pIMeshObject->GetVertexCount(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("VertexCount", *pVertexCount); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_meshobject_gettrianglecount(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 * pVertexCount) +{ + IBase* pIBaseClass = (IBase *)pMeshObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMeshObject, "MeshObject", "GetTriangleCount"); + } + if (pVertexCount == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IMeshObject* pIMeshObject = dynamic_cast(pIBaseClass); + if (!pIMeshObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pVertexCount = pIMeshObject->GetTriangleCount(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("VertexCount", *pVertexCount); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_meshobject_getvertex(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 nIndex, sLib3MFPosition * pCoordinates) +{ + IBase* pIBaseClass = (IBase *)pMeshObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMeshObject, "MeshObject", "GetVertex"); + pJournalEntry->addUInt32Parameter("Index", nIndex); + } + if (pCoordinates == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IMeshObject* pIMeshObject = dynamic_cast(pIBaseClass); + if (!pIMeshObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pCoordinates = pIMeshObject->GetVertex(nIndex); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_meshobject_setvertex(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 nIndex, const sLib3MFPosition * pCoordinates) +{ + IBase* pIBaseClass = (IBase *)pMeshObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMeshObject, "MeshObject", "SetVertex"); + pJournalEntry->addUInt32Parameter("Index", nIndex); + } + IMeshObject* pIMeshObject = dynamic_cast(pIBaseClass); + if (!pIMeshObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIMeshObject->SetVertex(nIndex, *pCoordinates); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_meshobject_addvertex(Lib3MF_MeshObject pMeshObject, const sLib3MFPosition * pCoordinates, Lib3MF_uint32 * pNewIndex) +{ + IBase* pIBaseClass = (IBase *)pMeshObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMeshObject, "MeshObject", "AddVertex"); + } + if (pNewIndex == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IMeshObject* pIMeshObject = dynamic_cast(pIBaseClass); + if (!pIMeshObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pNewIndex = pIMeshObject->AddVertex(*pCoordinates); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("NewIndex", *pNewIndex); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_meshobject_getvertices(Lib3MF_MeshObject pMeshObject, const Lib3MF_uint64 nVerticesBufferSize, Lib3MF_uint64* pVerticesNeededCount, sLib3MFPosition * pVerticesBuffer) +{ + IBase* pIBaseClass = (IBase *)pMeshObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMeshObject, "MeshObject", "GetVertices"); + } + if ((!pVerticesBuffer) && !(pVerticesNeededCount)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IMeshObject* pIMeshObject = dynamic_cast(pIBaseClass); + if (!pIMeshObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIMeshObject->GetVertices(nVerticesBufferSize, pVerticesNeededCount, pVerticesBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_meshobject_gettriangle(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 nIndex, sLib3MFTriangle * pIndices) +{ + IBase* pIBaseClass = (IBase *)pMeshObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMeshObject, "MeshObject", "GetTriangle"); + pJournalEntry->addUInt32Parameter("Index", nIndex); + } + if (pIndices == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IMeshObject* pIMeshObject = dynamic_cast(pIBaseClass); + if (!pIMeshObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pIndices = pIMeshObject->GetTriangle(nIndex); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_meshobject_settriangle(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 nIndex, const sLib3MFTriangle * pIndices) +{ + IBase* pIBaseClass = (IBase *)pMeshObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMeshObject, "MeshObject", "SetTriangle"); + pJournalEntry->addUInt32Parameter("Index", nIndex); + } + IMeshObject* pIMeshObject = dynamic_cast(pIBaseClass); + if (!pIMeshObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIMeshObject->SetTriangle(nIndex, *pIndices); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_meshobject_addtriangle(Lib3MF_MeshObject pMeshObject, const sLib3MFTriangle * pIndices, Lib3MF_uint32 * pNewIndex) +{ + IBase* pIBaseClass = (IBase *)pMeshObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMeshObject, "MeshObject", "AddTriangle"); + } + if (pNewIndex == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IMeshObject* pIMeshObject = dynamic_cast(pIBaseClass); + if (!pIMeshObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pNewIndex = pIMeshObject->AddTriangle(*pIndices); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("NewIndex", *pNewIndex); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_meshobject_gettriangleindices(Lib3MF_MeshObject pMeshObject, const Lib3MF_uint64 nIndicesBufferSize, Lib3MF_uint64* pIndicesNeededCount, sLib3MFTriangle * pIndicesBuffer) +{ + IBase* pIBaseClass = (IBase *)pMeshObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMeshObject, "MeshObject", "GetTriangleIndices"); + } + if ((!pIndicesBuffer) && !(pIndicesNeededCount)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IMeshObject* pIMeshObject = dynamic_cast(pIBaseClass); + if (!pIMeshObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIMeshObject->GetTriangleIndices(nIndicesBufferSize, pIndicesNeededCount, pIndicesBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_meshobject_setobjectlevelproperty(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 nUniqueResourceID, Lib3MF_uint32 nPropertyID) +{ + IBase* pIBaseClass = (IBase *)pMeshObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMeshObject, "MeshObject", "SetObjectLevelProperty"); + pJournalEntry->addUInt32Parameter("UniqueResourceID", nUniqueResourceID); + pJournalEntry->addUInt32Parameter("PropertyID", nPropertyID); + } + IMeshObject* pIMeshObject = dynamic_cast(pIBaseClass); + if (!pIMeshObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIMeshObject->SetObjectLevelProperty(nUniqueResourceID, nPropertyID); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_meshobject_getobjectlevelproperty(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 * pUniqueResourceID, Lib3MF_uint32 * pPropertyID, bool * pHasObjectLevelProperty) +{ + IBase* pIBaseClass = (IBase *)pMeshObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMeshObject, "MeshObject", "GetObjectLevelProperty"); + } + if (!pUniqueResourceID) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (!pPropertyID) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (pHasObjectLevelProperty == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IMeshObject* pIMeshObject = dynamic_cast(pIBaseClass); + if (!pIMeshObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pHasObjectLevelProperty = pIMeshObject->GetObjectLevelProperty(*pUniqueResourceID, *pPropertyID); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("UniqueResourceID", *pUniqueResourceID); + pJournalEntry->addUInt32Result("PropertyID", *pPropertyID); + pJournalEntry->addBooleanResult("HasObjectLevelProperty", *pHasObjectLevelProperty); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_meshobject_settriangleproperties(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 nIndex, const sLib3MFTriangleProperties * pProperties) +{ + IBase* pIBaseClass = (IBase *)pMeshObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMeshObject, "MeshObject", "SetTriangleProperties"); + pJournalEntry->addUInt32Parameter("Index", nIndex); + } + IMeshObject* pIMeshObject = dynamic_cast(pIBaseClass); + if (!pIMeshObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIMeshObject->SetTriangleProperties(nIndex, *pProperties); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_meshobject_gettriangleproperties(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 nIndex, sLib3MFTriangleProperties * pProperty) +{ + IBase* pIBaseClass = (IBase *)pMeshObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMeshObject, "MeshObject", "GetTriangleProperties"); + pJournalEntry->addUInt32Parameter("Index", nIndex); + } + if (!pProperty) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IMeshObject* pIMeshObject = dynamic_cast(pIBaseClass); + if (!pIMeshObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIMeshObject->GetTriangleProperties(nIndex, *pProperty); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_meshobject_setalltriangleproperties(Lib3MF_MeshObject pMeshObject, Lib3MF_uint64 nPropertiesArrayBufferSize, const sLib3MFTriangleProperties * pPropertiesArrayBuffer) +{ + IBase* pIBaseClass = (IBase *)pMeshObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMeshObject, "MeshObject", "SetAllTriangleProperties"); + } + if ( (!pPropertiesArrayBuffer) && (nPropertiesArrayBufferSize>0)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IMeshObject* pIMeshObject = dynamic_cast(pIBaseClass); + if (!pIMeshObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIMeshObject->SetAllTriangleProperties(nPropertiesArrayBufferSize, pPropertiesArrayBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_meshobject_getalltriangleproperties(Lib3MF_MeshObject pMeshObject, const Lib3MF_uint64 nPropertiesArrayBufferSize, Lib3MF_uint64* pPropertiesArrayNeededCount, sLib3MFTriangleProperties * pPropertiesArrayBuffer) +{ + IBase* pIBaseClass = (IBase *)pMeshObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMeshObject, "MeshObject", "GetAllTriangleProperties"); + } + if ((!pPropertiesArrayBuffer) && !(pPropertiesArrayNeededCount)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IMeshObject* pIMeshObject = dynamic_cast(pIBaseClass); + if (!pIMeshObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIMeshObject->GetAllTriangleProperties(nPropertiesArrayBufferSize, pPropertiesArrayNeededCount, pPropertiesArrayBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_meshobject_clearallproperties(Lib3MF_MeshObject pMeshObject) +{ + IBase* pIBaseClass = (IBase *)pMeshObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMeshObject, "MeshObject", "ClearAllProperties"); + } + IMeshObject* pIMeshObject = dynamic_cast(pIBaseClass); + if (!pIMeshObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIMeshObject->ClearAllProperties(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_meshobject_setgeometry(Lib3MF_MeshObject pMeshObject, Lib3MF_uint64 nVerticesBufferSize, const sLib3MFPosition * pVerticesBuffer, Lib3MF_uint64 nIndicesBufferSize, const sLib3MFTriangle * pIndicesBuffer) +{ + IBase* pIBaseClass = (IBase *)pMeshObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMeshObject, "MeshObject", "SetGeometry"); + } + if ( (!pVerticesBuffer) && (nVerticesBufferSize>0)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if ( (!pIndicesBuffer) && (nIndicesBufferSize>0)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IMeshObject* pIMeshObject = dynamic_cast(pIBaseClass); + if (!pIMeshObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIMeshObject->SetGeometry(nVerticesBufferSize, pVerticesBuffer, nIndicesBufferSize, pIndicesBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_meshobject_ismanifoldandoriented(Lib3MF_MeshObject pMeshObject, bool * pIsManifoldAndOriented) +{ + IBase* pIBaseClass = (IBase *)pMeshObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMeshObject, "MeshObject", "IsManifoldAndOriented"); + } + if (pIsManifoldAndOriented == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IMeshObject* pIMeshObject = dynamic_cast(pIBaseClass); + if (!pIMeshObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pIsManifoldAndOriented = pIMeshObject->IsManifoldAndOriented(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addBooleanResult("IsManifoldAndOriented", *pIsManifoldAndOriented); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_meshobject_beamlattice(Lib3MF_MeshObject pMeshObject, Lib3MF_BeamLattice * pTheBeamLattice) +{ + IBase* pIBaseClass = (IBase *)pMeshObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMeshObject, "MeshObject", "BeamLattice"); + } + if (pTheBeamLattice == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseTheBeamLattice(nullptr); + IMeshObject* pIMeshObject = dynamic_cast(pIBaseClass); + if (!pIMeshObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseTheBeamLattice = pIMeshObject->BeamLattice(); + + *pTheBeamLattice = (IBase*)(pBaseTheBeamLattice); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("TheBeamLattice", *pTheBeamLattice); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for BeamLattice +**************************************************************************************************************************/ +Lib3MFResult lib3mf_beamlattice_getminlength(Lib3MF_BeamLattice pBeamLattice, Lib3MF_double * pMinLength) +{ + IBase* pIBaseClass = (IBase *)pBeamLattice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamLattice, "BeamLattice", "GetMinLength"); + } + if (pMinLength == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBeamLattice* pIBeamLattice = dynamic_cast(pIBaseClass); + if (!pIBeamLattice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pMinLength = pIBeamLattice->GetMinLength(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addDoubleResult("MinLength", *pMinLength); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamlattice_setminlength(Lib3MF_BeamLattice pBeamLattice, Lib3MF_double dMinLength) +{ + IBase* pIBaseClass = (IBase *)pBeamLattice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamLattice, "BeamLattice", "SetMinLength"); + pJournalEntry->addDoubleParameter("MinLength", dMinLength); + } + IBeamLattice* pIBeamLattice = dynamic_cast(pIBaseClass); + if (!pIBeamLattice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIBeamLattice->SetMinLength(dMinLength); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamlattice_getclipping(Lib3MF_BeamLattice pBeamLattice, eLib3MFBeamLatticeClipMode * pClipMode, Lib3MF_uint32 * pUniqueResourceID) +{ + IBase* pIBaseClass = (IBase *)pBeamLattice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamLattice, "BeamLattice", "GetClipping"); + } + if (!pClipMode) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (!pUniqueResourceID) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBeamLattice* pIBeamLattice = dynamic_cast(pIBaseClass); + if (!pIBeamLattice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIBeamLattice->GetClipping(*pClipMode, *pUniqueResourceID); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addEnumResult("ClipMode", "BeamLatticeClipMode", (Lib3MF_int32)(*pClipMode)); + pJournalEntry->addUInt32Result("UniqueResourceID", *pUniqueResourceID); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamlattice_setclipping(Lib3MF_BeamLattice pBeamLattice, eLib3MFBeamLatticeClipMode eClipMode, Lib3MF_uint32 nUniqueResourceID) +{ + IBase* pIBaseClass = (IBase *)pBeamLattice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamLattice, "BeamLattice", "SetClipping"); + pJournalEntry->addEnumParameter("ClipMode", "BeamLatticeClipMode", (Lib3MF_int32)(eClipMode)); + pJournalEntry->addUInt32Parameter("UniqueResourceID", nUniqueResourceID); + } + IBeamLattice* pIBeamLattice = dynamic_cast(pIBaseClass); + if (!pIBeamLattice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIBeamLattice->SetClipping(eClipMode, nUniqueResourceID); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamlattice_getrepresentation(Lib3MF_BeamLattice pBeamLattice, bool * pHasRepresentation, Lib3MF_uint32 * pUniqueResourceID) +{ + IBase* pIBaseClass = (IBase *)pBeamLattice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamLattice, "BeamLattice", "GetRepresentation"); + } + if (pHasRepresentation == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (!pUniqueResourceID) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBeamLattice* pIBeamLattice = dynamic_cast(pIBaseClass); + if (!pIBeamLattice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pHasRepresentation = pIBeamLattice->GetRepresentation(*pUniqueResourceID); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addBooleanResult("HasRepresentation", *pHasRepresentation); + pJournalEntry->addUInt32Result("UniqueResourceID", *pUniqueResourceID); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamlattice_setrepresentation(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint32 nUniqueResourceID) +{ + IBase* pIBaseClass = (IBase *)pBeamLattice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamLattice, "BeamLattice", "SetRepresentation"); + pJournalEntry->addUInt32Parameter("UniqueResourceID", nUniqueResourceID); + } + IBeamLattice* pIBeamLattice = dynamic_cast(pIBaseClass); + if (!pIBeamLattice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIBeamLattice->SetRepresentation(nUniqueResourceID); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamlattice_getballoptions(Lib3MF_BeamLattice pBeamLattice, eLib3MFBeamLatticeBallMode * pBallMode, Lib3MF_double * pBallRadius) +{ + IBase* pIBaseClass = (IBase *)pBeamLattice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamLattice, "BeamLattice", "GetBallOptions"); + } + if (!pBallMode) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (!pBallRadius) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBeamLattice* pIBeamLattice = dynamic_cast(pIBaseClass); + if (!pIBeamLattice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIBeamLattice->GetBallOptions(*pBallMode, *pBallRadius); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addEnumResult("BallMode", "BeamLatticeBallMode", (Lib3MF_int32)(*pBallMode)); + pJournalEntry->addDoubleResult("BallRadius", *pBallRadius); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamlattice_setballoptions(Lib3MF_BeamLattice pBeamLattice, eLib3MFBeamLatticeBallMode eBallMode, Lib3MF_double dBallRadius) +{ + IBase* pIBaseClass = (IBase *)pBeamLattice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamLattice, "BeamLattice", "SetBallOptions"); + pJournalEntry->addEnumParameter("BallMode", "BeamLatticeBallMode", (Lib3MF_int32)(eBallMode)); + pJournalEntry->addDoubleParameter("BallRadius", dBallRadius); + } + IBeamLattice* pIBeamLattice = dynamic_cast(pIBaseClass); + if (!pIBeamLattice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIBeamLattice->SetBallOptions(eBallMode, dBallRadius); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamlattice_getbeamcount(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint32 * pCount) +{ + IBase* pIBaseClass = (IBase *)pBeamLattice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamLattice, "BeamLattice", "GetBeamCount"); + } + if (pCount == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBeamLattice* pIBeamLattice = dynamic_cast(pIBaseClass); + if (!pIBeamLattice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pCount = pIBeamLattice->GetBeamCount(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("Count", *pCount); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamlattice_getbeam(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint32 nIndex, sLib3MFBeam * pBeamInfo) +{ + IBase* pIBaseClass = (IBase *)pBeamLattice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamLattice, "BeamLattice", "GetBeam"); + pJournalEntry->addUInt32Parameter("Index", nIndex); + } + if (pBeamInfo == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBeamLattice* pIBeamLattice = dynamic_cast(pIBaseClass); + if (!pIBeamLattice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pBeamInfo = pIBeamLattice->GetBeam(nIndex); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamlattice_addbeam(Lib3MF_BeamLattice pBeamLattice, const sLib3MFBeam * pBeamInfo, Lib3MF_uint32 * pIndex) +{ + IBase* pIBaseClass = (IBase *)pBeamLattice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamLattice, "BeamLattice", "AddBeam"); + } + if (pIndex == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBeamLattice* pIBeamLattice = dynamic_cast(pIBaseClass); + if (!pIBeamLattice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pIndex = pIBeamLattice->AddBeam(*pBeamInfo); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("Index", *pIndex); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamlattice_setbeam(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint32 nIndex, const sLib3MFBeam * pBeamInfo) +{ + IBase* pIBaseClass = (IBase *)pBeamLattice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamLattice, "BeamLattice", "SetBeam"); + pJournalEntry->addUInt32Parameter("Index", nIndex); + } + IBeamLattice* pIBeamLattice = dynamic_cast(pIBaseClass); + if (!pIBeamLattice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIBeamLattice->SetBeam(nIndex, *pBeamInfo); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamlattice_setbeams(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint64 nBeamInfoBufferSize, const sLib3MFBeam * pBeamInfoBuffer) +{ + IBase* pIBaseClass = (IBase *)pBeamLattice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamLattice, "BeamLattice", "SetBeams"); + } + if ( (!pBeamInfoBuffer) && (nBeamInfoBufferSize>0)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBeamLattice* pIBeamLattice = dynamic_cast(pIBaseClass); + if (!pIBeamLattice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIBeamLattice->SetBeams(nBeamInfoBufferSize, pBeamInfoBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamlattice_getbeams(Lib3MF_BeamLattice pBeamLattice, const Lib3MF_uint64 nBeamInfoBufferSize, Lib3MF_uint64* pBeamInfoNeededCount, sLib3MFBeam * pBeamInfoBuffer) +{ + IBase* pIBaseClass = (IBase *)pBeamLattice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamLattice, "BeamLattice", "GetBeams"); + } + if ((!pBeamInfoBuffer) && !(pBeamInfoNeededCount)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBeamLattice* pIBeamLattice = dynamic_cast(pIBaseClass); + if (!pIBeamLattice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIBeamLattice->GetBeams(nBeamInfoBufferSize, pBeamInfoNeededCount, pBeamInfoBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamlattice_getballcount(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint32 * pCount) +{ + IBase* pIBaseClass = (IBase *)pBeamLattice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamLattice, "BeamLattice", "GetBallCount"); + } + if (pCount == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBeamLattice* pIBeamLattice = dynamic_cast(pIBaseClass); + if (!pIBeamLattice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pCount = pIBeamLattice->GetBallCount(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("Count", *pCount); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamlattice_getball(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint32 nIndex, sLib3MFBall * pBallInfo) +{ + IBase* pIBaseClass = (IBase *)pBeamLattice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamLattice, "BeamLattice", "GetBall"); + pJournalEntry->addUInt32Parameter("Index", nIndex); + } + if (pBallInfo == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBeamLattice* pIBeamLattice = dynamic_cast(pIBaseClass); + if (!pIBeamLattice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pBallInfo = pIBeamLattice->GetBall(nIndex); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamlattice_addball(Lib3MF_BeamLattice pBeamLattice, const sLib3MFBall * pBallInfo, Lib3MF_uint32 * pIndex) +{ + IBase* pIBaseClass = (IBase *)pBeamLattice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamLattice, "BeamLattice", "AddBall"); + } + if (pIndex == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBeamLattice* pIBeamLattice = dynamic_cast(pIBaseClass); + if (!pIBeamLattice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pIndex = pIBeamLattice->AddBall(*pBallInfo); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("Index", *pIndex); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamlattice_setball(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint32 nIndex, const sLib3MFBall * pBallInfo) +{ + IBase* pIBaseClass = (IBase *)pBeamLattice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamLattice, "BeamLattice", "SetBall"); + pJournalEntry->addUInt32Parameter("Index", nIndex); + } + IBeamLattice* pIBeamLattice = dynamic_cast(pIBaseClass); + if (!pIBeamLattice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIBeamLattice->SetBall(nIndex, *pBallInfo); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamlattice_setballs(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint64 nBallInfoBufferSize, const sLib3MFBall * pBallInfoBuffer) +{ + IBase* pIBaseClass = (IBase *)pBeamLattice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamLattice, "BeamLattice", "SetBalls"); + } + if ( (!pBallInfoBuffer) && (nBallInfoBufferSize>0)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBeamLattice* pIBeamLattice = dynamic_cast(pIBaseClass); + if (!pIBeamLattice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIBeamLattice->SetBalls(nBallInfoBufferSize, pBallInfoBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamlattice_getballs(Lib3MF_BeamLattice pBeamLattice, const Lib3MF_uint64 nBallInfoBufferSize, Lib3MF_uint64* pBallInfoNeededCount, sLib3MFBall * pBallInfoBuffer) +{ + IBase* pIBaseClass = (IBase *)pBeamLattice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamLattice, "BeamLattice", "GetBalls"); + } + if ((!pBallInfoBuffer) && !(pBallInfoNeededCount)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBeamLattice* pIBeamLattice = dynamic_cast(pIBaseClass); + if (!pIBeamLattice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIBeamLattice->GetBalls(nBallInfoBufferSize, pBallInfoNeededCount, pBallInfoBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamlattice_getbeamsetcount(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint32 * pCount) +{ + IBase* pIBaseClass = (IBase *)pBeamLattice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamLattice, "BeamLattice", "GetBeamSetCount"); + } + if (pCount == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBeamLattice* pIBeamLattice = dynamic_cast(pIBaseClass); + if (!pIBeamLattice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pCount = pIBeamLattice->GetBeamSetCount(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("Count", *pCount); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamlattice_addbeamset(Lib3MF_BeamLattice pBeamLattice, Lib3MF_BeamSet * pBeamSet) +{ + IBase* pIBaseClass = (IBase *)pBeamLattice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamLattice, "BeamLattice", "AddBeamSet"); + } + if (pBeamSet == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseBeamSet(nullptr); + IBeamLattice* pIBeamLattice = dynamic_cast(pIBaseClass); + if (!pIBeamLattice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseBeamSet = pIBeamLattice->AddBeamSet(); + + *pBeamSet = (IBase*)(pBaseBeamSet); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("BeamSet", *pBeamSet); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamlattice_getbeamset(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint32 nIndex, Lib3MF_BeamSet * pBeamSet) +{ + IBase* pIBaseClass = (IBase *)pBeamLattice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamLattice, "BeamLattice", "GetBeamSet"); + pJournalEntry->addUInt32Parameter("Index", nIndex); + } + if (pBeamSet == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseBeamSet(nullptr); + IBeamLattice* pIBeamLattice = dynamic_cast(pIBaseClass); + if (!pIBeamLattice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseBeamSet = pIBeamLattice->GetBeamSet(nIndex); + + *pBeamSet = (IBase*)(pBaseBeamSet); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("BeamSet", *pBeamSet); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for Component +**************************************************************************************************************************/ +Lib3MFResult lib3mf_component_getobjectresource(Lib3MF_Component pComponent, Lib3MF_Object * pObjectResource) +{ + IBase* pIBaseClass = (IBase *)pComponent; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pComponent, "Component", "GetObjectResource"); + } + if (pObjectResource == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseObjectResource(nullptr); + IComponent* pIComponent = dynamic_cast(pIBaseClass); + if (!pIComponent) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseObjectResource = pIComponent->GetObjectResource(); + + *pObjectResource = (IBase*)(pBaseObjectResource); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("ObjectResource", *pObjectResource); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_component_getobjectresourceid(Lib3MF_Component pComponent, Lib3MF_uint32 * pUniqueResourceID) +{ + IBase* pIBaseClass = (IBase *)pComponent; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pComponent, "Component", "GetObjectResourceID"); + } + if (pUniqueResourceID == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IComponent* pIComponent = dynamic_cast(pIBaseClass); + if (!pIComponent) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pUniqueResourceID = pIComponent->GetObjectResourceID(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("UniqueResourceID", *pUniqueResourceID); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_component_getuuid(Lib3MF_Component pComponent, bool * pHasUUID, const Lib3MF_uint32 nUUIDBufferSize, Lib3MF_uint32* pUUIDNeededChars, char * pUUIDBuffer) +{ + IBase* pIBaseClass = (IBase *)pComponent; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pComponent, "Component", "GetUUID"); + } + if (!pHasUUID) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if ( (!pUUIDBuffer) && !(pUUIDNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sUUID(""); + IComponent* pIComponent = dynamic_cast(pIBaseClass); + if (!pIComponent) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + sUUID = pIComponent->GetUUID(*pHasUUID); + + if (pUUIDNeededChars) + *pUUIDNeededChars = (Lib3MF_uint32) (sUUID.size()+1); + if (pUUIDBuffer) { + if (sUUID.size() >= nUUIDBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iUUID = 0; iUUID < sUUID.size(); iUUID++) + pUUIDBuffer[iUUID] = sUUID[iUUID]; + pUUIDBuffer[sUUID.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addBooleanResult("HasUUID", *pHasUUID); + pJournalEntry->addStringResult("UUID", sUUID.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_component_setuuid(Lib3MF_Component pComponent, const char * pUUID) +{ + IBase* pIBaseClass = (IBase *)pComponent; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pComponent, "Component", "SetUUID"); + pJournalEntry->addStringParameter("UUID", pUUID); + } + if (pUUID == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sUUID(pUUID); + IComponent* pIComponent = dynamic_cast(pIBaseClass); + if (!pIComponent) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIComponent->SetUUID(sUUID); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_component_hastransform(Lib3MF_Component pComponent, bool * pHasTransform) +{ + IBase* pIBaseClass = (IBase *)pComponent; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pComponent, "Component", "HasTransform"); + } + if (pHasTransform == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IComponent* pIComponent = dynamic_cast(pIBaseClass); + if (!pIComponent) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pHasTransform = pIComponent->HasTransform(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addBooleanResult("HasTransform", *pHasTransform); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_component_gettransform(Lib3MF_Component pComponent, sLib3MFTransform * pTransform) +{ + IBase* pIBaseClass = (IBase *)pComponent; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pComponent, "Component", "GetTransform"); + } + if (pTransform == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IComponent* pIComponent = dynamic_cast(pIBaseClass); + if (!pIComponent) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pTransform = pIComponent->GetTransform(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_component_settransform(Lib3MF_Component pComponent, const sLib3MFTransform * pTransform) +{ + IBase* pIBaseClass = (IBase *)pComponent; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pComponent, "Component", "SetTransform"); + } + IComponent* pIComponent = dynamic_cast(pIBaseClass); + if (!pIComponent) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIComponent->SetTransform(*pTransform); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for ComponentsObject +**************************************************************************************************************************/ +Lib3MFResult lib3mf_componentsobject_addcomponent(Lib3MF_ComponentsObject pComponentsObject, Lib3MF_Object pObjectResource, const sLib3MFTransform * pTransform, Lib3MF_Component * pComponentInstance) +{ + IBase* pIBaseClass = (IBase *)pComponentsObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pComponentsObject, "ComponentsObject", "AddComponent"); + pJournalEntry->addHandleParameter("ObjectResource", pObjectResource); + } + if (pComponentInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pIBaseClassObjectResource = (IBase *)pObjectResource; + IObject* pIObjectResource = dynamic_cast(pIBaseClassObjectResource); + if (!pIObjectResource) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDCAST); + + IBase* pBaseComponentInstance(nullptr); + IComponentsObject* pIComponentsObject = dynamic_cast(pIBaseClass); + if (!pIComponentsObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseComponentInstance = pIComponentsObject->AddComponent(pIObjectResource, *pTransform); + + *pComponentInstance = (IBase*)(pBaseComponentInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("ComponentInstance", *pComponentInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_componentsobject_getcomponent(Lib3MF_ComponentsObject pComponentsObject, Lib3MF_uint32 nIndex, Lib3MF_Component * pComponentInstance) +{ + IBase* pIBaseClass = (IBase *)pComponentsObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pComponentsObject, "ComponentsObject", "GetComponent"); + pJournalEntry->addUInt32Parameter("Index", nIndex); + } + if (pComponentInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseComponentInstance(nullptr); + IComponentsObject* pIComponentsObject = dynamic_cast(pIBaseClass); + if (!pIComponentsObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseComponentInstance = pIComponentsObject->GetComponent(nIndex); + + *pComponentInstance = (IBase*)(pBaseComponentInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("ComponentInstance", *pComponentInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_componentsobject_getcomponentcount(Lib3MF_ComponentsObject pComponentsObject, Lib3MF_uint32 * pCount) +{ + IBase* pIBaseClass = (IBase *)pComponentsObject; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pComponentsObject, "ComponentsObject", "GetComponentCount"); + } + if (pCount == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IComponentsObject* pIComponentsObject = dynamic_cast(pIBaseClass); + if (!pIComponentsObject) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pCount = pIComponentsObject->GetComponentCount(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("Count", *pCount); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for BeamSet +**************************************************************************************************************************/ +Lib3MFResult lib3mf_beamset_setname(Lib3MF_BeamSet pBeamSet, const char * pName) +{ + IBase* pIBaseClass = (IBase *)pBeamSet; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamSet, "BeamSet", "SetName"); + pJournalEntry->addStringParameter("Name", pName); + } + if (pName == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sName(pName); + IBeamSet* pIBeamSet = dynamic_cast(pIBaseClass); + if (!pIBeamSet) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIBeamSet->SetName(sName); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamset_getname(Lib3MF_BeamSet pBeamSet, const Lib3MF_uint32 nNameBufferSize, Lib3MF_uint32* pNameNeededChars, char * pNameBuffer) +{ + IBase* pIBaseClass = (IBase *)pBeamSet; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamSet, "BeamSet", "GetName"); + } + if ( (!pNameBuffer) && !(pNameNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sName(""); + IBeamSet* pIBeamSet = dynamic_cast(pIBaseClass); + if (!pIBeamSet) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + sName = pIBeamSet->GetName(); + + if (pNameNeededChars) + *pNameNeededChars = (Lib3MF_uint32) (sName.size()+1); + if (pNameBuffer) { + if (sName.size() >= nNameBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iName = 0; iName < sName.size(); iName++) + pNameBuffer[iName] = sName[iName]; + pNameBuffer[sName.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addStringResult("Name", sName.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamset_setidentifier(Lib3MF_BeamSet pBeamSet, const char * pIdentifier) +{ + IBase* pIBaseClass = (IBase *)pBeamSet; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamSet, "BeamSet", "SetIdentifier"); + pJournalEntry->addStringParameter("Identifier", pIdentifier); + } + if (pIdentifier == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sIdentifier(pIdentifier); + IBeamSet* pIBeamSet = dynamic_cast(pIBaseClass); + if (!pIBeamSet) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIBeamSet->SetIdentifier(sIdentifier); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamset_getidentifier(Lib3MF_BeamSet pBeamSet, const Lib3MF_uint32 nIdentifierBufferSize, Lib3MF_uint32* pIdentifierNeededChars, char * pIdentifierBuffer) +{ + IBase* pIBaseClass = (IBase *)pBeamSet; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamSet, "BeamSet", "GetIdentifier"); + } + if ( (!pIdentifierBuffer) && !(pIdentifierNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sIdentifier(""); + IBeamSet* pIBeamSet = dynamic_cast(pIBaseClass); + if (!pIBeamSet) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + sIdentifier = pIBeamSet->GetIdentifier(); + + if (pIdentifierNeededChars) + *pIdentifierNeededChars = (Lib3MF_uint32) (sIdentifier.size()+1); + if (pIdentifierBuffer) { + if (sIdentifier.size() >= nIdentifierBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iIdentifier = 0; iIdentifier < sIdentifier.size(); iIdentifier++) + pIdentifierBuffer[iIdentifier] = sIdentifier[iIdentifier]; + pIdentifierBuffer[sIdentifier.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addStringResult("Identifier", sIdentifier.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamset_getreferencecount(Lib3MF_BeamSet pBeamSet, Lib3MF_uint32 * pCount) +{ + IBase* pIBaseClass = (IBase *)pBeamSet; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamSet, "BeamSet", "GetReferenceCount"); + } + if (pCount == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBeamSet* pIBeamSet = dynamic_cast(pIBaseClass); + if (!pIBeamSet) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pCount = pIBeamSet->GetReferenceCount(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("Count", *pCount); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamset_setreferences(Lib3MF_BeamSet pBeamSet, Lib3MF_uint64 nReferencesBufferSize, const Lib3MF_uint32 * pReferencesBuffer) +{ + IBase* pIBaseClass = (IBase *)pBeamSet; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamSet, "BeamSet", "SetReferences"); + } + if ( (!pReferencesBuffer) && (nReferencesBufferSize>0)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBeamSet* pIBeamSet = dynamic_cast(pIBaseClass); + if (!pIBeamSet) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIBeamSet->SetReferences(nReferencesBufferSize, pReferencesBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamset_getreferences(Lib3MF_BeamSet pBeamSet, const Lib3MF_uint64 nReferencesBufferSize, Lib3MF_uint64* pReferencesNeededCount, Lib3MF_uint32 * pReferencesBuffer) +{ + IBase* pIBaseClass = (IBase *)pBeamSet; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamSet, "BeamSet", "GetReferences"); + } + if ((!pReferencesBuffer) && !(pReferencesNeededCount)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBeamSet* pIBeamSet = dynamic_cast(pIBaseClass); + if (!pIBeamSet) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIBeamSet->GetReferences(nReferencesBufferSize, pReferencesNeededCount, pReferencesBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamset_getballreferencecount(Lib3MF_BeamSet pBeamSet, Lib3MF_uint32 * pCount) +{ + IBase* pIBaseClass = (IBase *)pBeamSet; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamSet, "BeamSet", "GetBallReferenceCount"); + } + if (pCount == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBeamSet* pIBeamSet = dynamic_cast(pIBaseClass); + if (!pIBeamSet) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pCount = pIBeamSet->GetBallReferenceCount(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("Count", *pCount); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamset_setballreferences(Lib3MF_BeamSet pBeamSet, Lib3MF_uint64 nBallReferencesBufferSize, const Lib3MF_uint32 * pBallReferencesBuffer) +{ + IBase* pIBaseClass = (IBase *)pBeamSet; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamSet, "BeamSet", "SetBallReferences"); + } + if ( (!pBallReferencesBuffer) && (nBallReferencesBufferSize>0)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBeamSet* pIBeamSet = dynamic_cast(pIBaseClass); + if (!pIBeamSet) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIBeamSet->SetBallReferences(nBallReferencesBufferSize, pBallReferencesBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_beamset_getballreferences(Lib3MF_BeamSet pBeamSet, const Lib3MF_uint64 nBallReferencesBufferSize, Lib3MF_uint64* pBallReferencesNeededCount, Lib3MF_uint32 * pBallReferencesBuffer) +{ + IBase* pIBaseClass = (IBase *)pBeamSet; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBeamSet, "BeamSet", "GetBallReferences"); + } + if ((!pBallReferencesBuffer) && !(pBallReferencesNeededCount)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBeamSet* pIBeamSet = dynamic_cast(pIBaseClass); + if (!pIBeamSet) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIBeamSet->GetBallReferences(nBallReferencesBufferSize, pBallReferencesNeededCount, pBallReferencesBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for BaseMaterialGroup +**************************************************************************************************************************/ +Lib3MFResult lib3mf_basematerialgroup_getcount(Lib3MF_BaseMaterialGroup pBaseMaterialGroup, Lib3MF_uint32 * pCount) +{ + IBase* pIBaseClass = (IBase *)pBaseMaterialGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBaseMaterialGroup, "BaseMaterialGroup", "GetCount"); + } + if (pCount == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBaseMaterialGroup* pIBaseMaterialGroup = dynamic_cast(pIBaseClass); + if (!pIBaseMaterialGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pCount = pIBaseMaterialGroup->GetCount(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("Count", *pCount); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_basematerialgroup_getallpropertyids(Lib3MF_BaseMaterialGroup pBaseMaterialGroup, const Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer) +{ + IBase* pIBaseClass = (IBase *)pBaseMaterialGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBaseMaterialGroup, "BaseMaterialGroup", "GetAllPropertyIDs"); + } + if ((!pPropertyIDsBuffer) && !(pPropertyIDsNeededCount)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBaseMaterialGroup* pIBaseMaterialGroup = dynamic_cast(pIBaseClass); + if (!pIBaseMaterialGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIBaseMaterialGroup->GetAllPropertyIDs(nPropertyIDsBufferSize, pPropertyIDsNeededCount, pPropertyIDsBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_basematerialgroup_addmaterial(Lib3MF_BaseMaterialGroup pBaseMaterialGroup, const char * pName, const sLib3MFColor * pDisplayColor, Lib3MF_uint32 * pPropertyID) +{ + IBase* pIBaseClass = (IBase *)pBaseMaterialGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBaseMaterialGroup, "BaseMaterialGroup", "AddMaterial"); + pJournalEntry->addStringParameter("Name", pName); + } + if (pName == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (pPropertyID == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sName(pName); + IBaseMaterialGroup* pIBaseMaterialGroup = dynamic_cast(pIBaseClass); + if (!pIBaseMaterialGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pPropertyID = pIBaseMaterialGroup->AddMaterial(sName, *pDisplayColor); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("PropertyID", *pPropertyID); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_basematerialgroup_removematerial(Lib3MF_BaseMaterialGroup pBaseMaterialGroup, Lib3MF_uint32 nPropertyID) +{ + IBase* pIBaseClass = (IBase *)pBaseMaterialGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBaseMaterialGroup, "BaseMaterialGroup", "RemoveMaterial"); + pJournalEntry->addUInt32Parameter("PropertyID", nPropertyID); + } + IBaseMaterialGroup* pIBaseMaterialGroup = dynamic_cast(pIBaseClass); + if (!pIBaseMaterialGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIBaseMaterialGroup->RemoveMaterial(nPropertyID); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_basematerialgroup_getname(Lib3MF_BaseMaterialGroup pBaseMaterialGroup, Lib3MF_uint32 nPropertyID, const Lib3MF_uint32 nNameBufferSize, Lib3MF_uint32* pNameNeededChars, char * pNameBuffer) +{ + IBase* pIBaseClass = (IBase *)pBaseMaterialGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBaseMaterialGroup, "BaseMaterialGroup", "GetName"); + pJournalEntry->addUInt32Parameter("PropertyID", nPropertyID); + } + if ( (!pNameBuffer) && !(pNameNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sName(""); + IBaseMaterialGroup* pIBaseMaterialGroup = dynamic_cast(pIBaseClass); + if (!pIBaseMaterialGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + sName = pIBaseMaterialGroup->GetName(nPropertyID); + + if (pNameNeededChars) + *pNameNeededChars = (Lib3MF_uint32) (sName.size()+1); + if (pNameBuffer) { + if (sName.size() >= nNameBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iName = 0; iName < sName.size(); iName++) + pNameBuffer[iName] = sName[iName]; + pNameBuffer[sName.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addStringResult("Name", sName.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_basematerialgroup_setname(Lib3MF_BaseMaterialGroup pBaseMaterialGroup, Lib3MF_uint32 nPropertyID, const char * pName) +{ + IBase* pIBaseClass = (IBase *)pBaseMaterialGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBaseMaterialGroup, "BaseMaterialGroup", "SetName"); + pJournalEntry->addUInt32Parameter("PropertyID", nPropertyID); + pJournalEntry->addStringParameter("Name", pName); + } + if (pName == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sName(pName); + IBaseMaterialGroup* pIBaseMaterialGroup = dynamic_cast(pIBaseClass); + if (!pIBaseMaterialGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIBaseMaterialGroup->SetName(nPropertyID, sName); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_basematerialgroup_setdisplaycolor(Lib3MF_BaseMaterialGroup pBaseMaterialGroup, Lib3MF_uint32 nPropertyID, const sLib3MFColor * pTheColor) +{ + IBase* pIBaseClass = (IBase *)pBaseMaterialGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBaseMaterialGroup, "BaseMaterialGroup", "SetDisplayColor"); + pJournalEntry->addUInt32Parameter("PropertyID", nPropertyID); + } + IBaseMaterialGroup* pIBaseMaterialGroup = dynamic_cast(pIBaseClass); + if (!pIBaseMaterialGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIBaseMaterialGroup->SetDisplayColor(nPropertyID, *pTheColor); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_basematerialgroup_getdisplaycolor(Lib3MF_BaseMaterialGroup pBaseMaterialGroup, Lib3MF_uint32 nPropertyID, sLib3MFColor * pTheColor) +{ + IBase* pIBaseClass = (IBase *)pBaseMaterialGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBaseMaterialGroup, "BaseMaterialGroup", "GetDisplayColor"); + pJournalEntry->addUInt32Parameter("PropertyID", nPropertyID); + } + if (pTheColor == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBaseMaterialGroup* pIBaseMaterialGroup = dynamic_cast(pIBaseClass); + if (!pIBaseMaterialGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pTheColor = pIBaseMaterialGroup->GetDisplayColor(nPropertyID); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for ColorGroup +**************************************************************************************************************************/ +Lib3MFResult lib3mf_colorgroup_getcount(Lib3MF_ColorGroup pColorGroup, Lib3MF_uint32 * pCount) +{ + IBase* pIBaseClass = (IBase *)pColorGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pColorGroup, "ColorGroup", "GetCount"); + } + if (pCount == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IColorGroup* pIColorGroup = dynamic_cast(pIBaseClass); + if (!pIColorGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pCount = pIColorGroup->GetCount(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("Count", *pCount); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_colorgroup_getallpropertyids(Lib3MF_ColorGroup pColorGroup, const Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer) +{ + IBase* pIBaseClass = (IBase *)pColorGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pColorGroup, "ColorGroup", "GetAllPropertyIDs"); + } + if ((!pPropertyIDsBuffer) && !(pPropertyIDsNeededCount)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IColorGroup* pIColorGroup = dynamic_cast(pIBaseClass); + if (!pIColorGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIColorGroup->GetAllPropertyIDs(nPropertyIDsBufferSize, pPropertyIDsNeededCount, pPropertyIDsBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_colorgroup_addcolor(Lib3MF_ColorGroup pColorGroup, const sLib3MFColor * pTheColor, Lib3MF_uint32 * pPropertyID) +{ + IBase* pIBaseClass = (IBase *)pColorGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pColorGroup, "ColorGroup", "AddColor"); + } + if (pPropertyID == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IColorGroup* pIColorGroup = dynamic_cast(pIBaseClass); + if (!pIColorGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pPropertyID = pIColorGroup->AddColor(*pTheColor); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("PropertyID", *pPropertyID); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_colorgroup_removecolor(Lib3MF_ColorGroup pColorGroup, Lib3MF_uint32 nPropertyID) +{ + IBase* pIBaseClass = (IBase *)pColorGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pColorGroup, "ColorGroup", "RemoveColor"); + pJournalEntry->addUInt32Parameter("PropertyID", nPropertyID); + } + IColorGroup* pIColorGroup = dynamic_cast(pIBaseClass); + if (!pIColorGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIColorGroup->RemoveColor(nPropertyID); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_colorgroup_setcolor(Lib3MF_ColorGroup pColorGroup, Lib3MF_uint32 nPropertyID, const sLib3MFColor * pTheColor) +{ + IBase* pIBaseClass = (IBase *)pColorGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pColorGroup, "ColorGroup", "SetColor"); + pJournalEntry->addUInt32Parameter("PropertyID", nPropertyID); + } + IColorGroup* pIColorGroup = dynamic_cast(pIBaseClass); + if (!pIColorGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIColorGroup->SetColor(nPropertyID, *pTheColor); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_colorgroup_getcolor(Lib3MF_ColorGroup pColorGroup, Lib3MF_uint32 nPropertyID, sLib3MFColor * pTheColor) +{ + IBase* pIBaseClass = (IBase *)pColorGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pColorGroup, "ColorGroup", "GetColor"); + pJournalEntry->addUInt32Parameter("PropertyID", nPropertyID); + } + if (pTheColor == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IColorGroup* pIColorGroup = dynamic_cast(pIBaseClass); + if (!pIColorGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pTheColor = pIColorGroup->GetColor(nPropertyID); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for Texture2DGroup +**************************************************************************************************************************/ +Lib3MFResult lib3mf_texture2dgroup_getcount(Lib3MF_Texture2DGroup pTexture2DGroup, Lib3MF_uint32 * pCount) +{ + IBase* pIBaseClass = (IBase *)pTexture2DGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pTexture2DGroup, "Texture2DGroup", "GetCount"); + } + if (pCount == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + ITexture2DGroup* pITexture2DGroup = dynamic_cast(pIBaseClass); + if (!pITexture2DGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pCount = pITexture2DGroup->GetCount(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("Count", *pCount); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_texture2dgroup_getallpropertyids(Lib3MF_Texture2DGroup pTexture2DGroup, const Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer) +{ + IBase* pIBaseClass = (IBase *)pTexture2DGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pTexture2DGroup, "Texture2DGroup", "GetAllPropertyIDs"); + } + if ((!pPropertyIDsBuffer) && !(pPropertyIDsNeededCount)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + ITexture2DGroup* pITexture2DGroup = dynamic_cast(pIBaseClass); + if (!pITexture2DGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pITexture2DGroup->GetAllPropertyIDs(nPropertyIDsBufferSize, pPropertyIDsNeededCount, pPropertyIDsBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_texture2dgroup_addtex2coord(Lib3MF_Texture2DGroup pTexture2DGroup, const sLib3MFTex2Coord * pUVCoordinate, Lib3MF_uint32 * pPropertyID) +{ + IBase* pIBaseClass = (IBase *)pTexture2DGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pTexture2DGroup, "Texture2DGroup", "AddTex2Coord"); + } + if (pPropertyID == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + ITexture2DGroup* pITexture2DGroup = dynamic_cast(pIBaseClass); + if (!pITexture2DGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pPropertyID = pITexture2DGroup->AddTex2Coord(*pUVCoordinate); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("PropertyID", *pPropertyID); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_texture2dgroup_gettex2coord(Lib3MF_Texture2DGroup pTexture2DGroup, Lib3MF_uint32 nPropertyID, sLib3MFTex2Coord * pUVCoordinate) +{ + IBase* pIBaseClass = (IBase *)pTexture2DGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pTexture2DGroup, "Texture2DGroup", "GetTex2Coord"); + pJournalEntry->addUInt32Parameter("PropertyID", nPropertyID); + } + if (pUVCoordinate == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + ITexture2DGroup* pITexture2DGroup = dynamic_cast(pIBaseClass); + if (!pITexture2DGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pUVCoordinate = pITexture2DGroup->GetTex2Coord(nPropertyID); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_texture2dgroup_removetex2coord(Lib3MF_Texture2DGroup pTexture2DGroup, Lib3MF_uint32 nPropertyID) +{ + IBase* pIBaseClass = (IBase *)pTexture2DGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pTexture2DGroup, "Texture2DGroup", "RemoveTex2Coord"); + pJournalEntry->addUInt32Parameter("PropertyID", nPropertyID); + } + ITexture2DGroup* pITexture2DGroup = dynamic_cast(pIBaseClass); + if (!pITexture2DGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pITexture2DGroup->RemoveTex2Coord(nPropertyID); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_texture2dgroup_gettexture2d(Lib3MF_Texture2DGroup pTexture2DGroup, Lib3MF_Texture2D * pTexture2DInstance) +{ + IBase* pIBaseClass = (IBase *)pTexture2DGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pTexture2DGroup, "Texture2DGroup", "GetTexture2D"); + } + if (pTexture2DInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseTexture2DInstance(nullptr); + ITexture2DGroup* pITexture2DGroup = dynamic_cast(pIBaseClass); + if (!pITexture2DGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseTexture2DInstance = pITexture2DGroup->GetTexture2D(); + + *pTexture2DInstance = (IBase*)(pBaseTexture2DInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("Texture2DInstance", *pTexture2DInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for CompositeMaterials +**************************************************************************************************************************/ +Lib3MFResult lib3mf_compositematerials_getcount(Lib3MF_CompositeMaterials pCompositeMaterials, Lib3MF_uint32 * pCount) +{ + IBase* pIBaseClass = (IBase *)pCompositeMaterials; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pCompositeMaterials, "CompositeMaterials", "GetCount"); + } + if (pCount == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + ICompositeMaterials* pICompositeMaterials = dynamic_cast(pIBaseClass); + if (!pICompositeMaterials) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pCount = pICompositeMaterials->GetCount(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("Count", *pCount); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_compositematerials_getallpropertyids(Lib3MF_CompositeMaterials pCompositeMaterials, const Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer) +{ + IBase* pIBaseClass = (IBase *)pCompositeMaterials; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pCompositeMaterials, "CompositeMaterials", "GetAllPropertyIDs"); + } + if ((!pPropertyIDsBuffer) && !(pPropertyIDsNeededCount)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + ICompositeMaterials* pICompositeMaterials = dynamic_cast(pIBaseClass); + if (!pICompositeMaterials) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pICompositeMaterials->GetAllPropertyIDs(nPropertyIDsBufferSize, pPropertyIDsNeededCount, pPropertyIDsBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_compositematerials_getbasematerialgroup(Lib3MF_CompositeMaterials pCompositeMaterials, Lib3MF_BaseMaterialGroup * pBaseMaterialGroupInstance) +{ + IBase* pIBaseClass = (IBase *)pCompositeMaterials; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pCompositeMaterials, "CompositeMaterials", "GetBaseMaterialGroup"); + } + if (pBaseMaterialGroupInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseBaseMaterialGroupInstance(nullptr); + ICompositeMaterials* pICompositeMaterials = dynamic_cast(pIBaseClass); + if (!pICompositeMaterials) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseBaseMaterialGroupInstance = pICompositeMaterials->GetBaseMaterialGroup(); + + *pBaseMaterialGroupInstance = (IBase*)(pBaseBaseMaterialGroupInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("BaseMaterialGroupInstance", *pBaseMaterialGroupInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_compositematerials_addcomposite(Lib3MF_CompositeMaterials pCompositeMaterials, Lib3MF_uint64 nCompositeBufferSize, const sLib3MFCompositeConstituent * pCompositeBuffer, Lib3MF_uint32 * pPropertyID) +{ + IBase* pIBaseClass = (IBase *)pCompositeMaterials; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pCompositeMaterials, "CompositeMaterials", "AddComposite"); + } + if ( (!pCompositeBuffer) && (nCompositeBufferSize>0)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (pPropertyID == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + ICompositeMaterials* pICompositeMaterials = dynamic_cast(pIBaseClass); + if (!pICompositeMaterials) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pPropertyID = pICompositeMaterials->AddComposite(nCompositeBufferSize, pCompositeBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("PropertyID", *pPropertyID); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_compositematerials_removecomposite(Lib3MF_CompositeMaterials pCompositeMaterials, Lib3MF_uint32 nPropertyID) +{ + IBase* pIBaseClass = (IBase *)pCompositeMaterials; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pCompositeMaterials, "CompositeMaterials", "RemoveComposite"); + pJournalEntry->addUInt32Parameter("PropertyID", nPropertyID); + } + ICompositeMaterials* pICompositeMaterials = dynamic_cast(pIBaseClass); + if (!pICompositeMaterials) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pICompositeMaterials->RemoveComposite(nPropertyID); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_compositematerials_getcomposite(Lib3MF_CompositeMaterials pCompositeMaterials, Lib3MF_uint32 nPropertyID, const Lib3MF_uint64 nCompositeBufferSize, Lib3MF_uint64* pCompositeNeededCount, sLib3MFCompositeConstituent * pCompositeBuffer) +{ + IBase* pIBaseClass = (IBase *)pCompositeMaterials; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pCompositeMaterials, "CompositeMaterials", "GetComposite"); + pJournalEntry->addUInt32Parameter("PropertyID", nPropertyID); + } + if ((!pCompositeBuffer) && !(pCompositeNeededCount)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + ICompositeMaterials* pICompositeMaterials = dynamic_cast(pIBaseClass); + if (!pICompositeMaterials) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pICompositeMaterials->GetComposite(nPropertyID, nCompositeBufferSize, pCompositeNeededCount, pCompositeBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for MultiPropertyGroup +**************************************************************************************************************************/ +Lib3MFResult lib3mf_multipropertygroup_getcount(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, Lib3MF_uint32 * pCount) +{ + IBase* pIBaseClass = (IBase *)pMultiPropertyGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMultiPropertyGroup, "MultiPropertyGroup", "GetCount"); + } + if (pCount == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IMultiPropertyGroup* pIMultiPropertyGroup = dynamic_cast(pIBaseClass); + if (!pIMultiPropertyGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pCount = pIMultiPropertyGroup->GetCount(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("Count", *pCount); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_multipropertygroup_getallpropertyids(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, const Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer) +{ + IBase* pIBaseClass = (IBase *)pMultiPropertyGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMultiPropertyGroup, "MultiPropertyGroup", "GetAllPropertyIDs"); + } + if ((!pPropertyIDsBuffer) && !(pPropertyIDsNeededCount)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IMultiPropertyGroup* pIMultiPropertyGroup = dynamic_cast(pIBaseClass); + if (!pIMultiPropertyGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIMultiPropertyGroup->GetAllPropertyIDs(nPropertyIDsBufferSize, pPropertyIDsNeededCount, pPropertyIDsBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_multipropertygroup_addmultiproperty(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, Lib3MF_uint64 nPropertyIDsBufferSize, const Lib3MF_uint32 * pPropertyIDsBuffer, Lib3MF_uint32 * pPropertyID) +{ + IBase* pIBaseClass = (IBase *)pMultiPropertyGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMultiPropertyGroup, "MultiPropertyGroup", "AddMultiProperty"); + } + if ( (!pPropertyIDsBuffer) && (nPropertyIDsBufferSize>0)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (pPropertyID == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IMultiPropertyGroup* pIMultiPropertyGroup = dynamic_cast(pIBaseClass); + if (!pIMultiPropertyGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pPropertyID = pIMultiPropertyGroup->AddMultiProperty(nPropertyIDsBufferSize, pPropertyIDsBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("PropertyID", *pPropertyID); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_multipropertygroup_setmultiproperty(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, Lib3MF_uint32 nPropertyID, Lib3MF_uint64 nPropertyIDsBufferSize, const Lib3MF_uint32 * pPropertyIDsBuffer) +{ + IBase* pIBaseClass = (IBase *)pMultiPropertyGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMultiPropertyGroup, "MultiPropertyGroup", "SetMultiProperty"); + pJournalEntry->addUInt32Parameter("PropertyID", nPropertyID); + } + if ( (!pPropertyIDsBuffer) && (nPropertyIDsBufferSize>0)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IMultiPropertyGroup* pIMultiPropertyGroup = dynamic_cast(pIBaseClass); + if (!pIMultiPropertyGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIMultiPropertyGroup->SetMultiProperty(nPropertyID, nPropertyIDsBufferSize, pPropertyIDsBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_multipropertygroup_getmultiproperty(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, Lib3MF_uint32 nPropertyID, const Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer) +{ + IBase* pIBaseClass = (IBase *)pMultiPropertyGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMultiPropertyGroup, "MultiPropertyGroup", "GetMultiProperty"); + pJournalEntry->addUInt32Parameter("PropertyID", nPropertyID); + } + if ((!pPropertyIDsBuffer) && !(pPropertyIDsNeededCount)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IMultiPropertyGroup* pIMultiPropertyGroup = dynamic_cast(pIBaseClass); + if (!pIMultiPropertyGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIMultiPropertyGroup->GetMultiProperty(nPropertyID, nPropertyIDsBufferSize, pPropertyIDsNeededCount, pPropertyIDsBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_multipropertygroup_removemultiproperty(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, Lib3MF_uint32 nPropertyID) +{ + IBase* pIBaseClass = (IBase *)pMultiPropertyGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMultiPropertyGroup, "MultiPropertyGroup", "RemoveMultiProperty"); + pJournalEntry->addUInt32Parameter("PropertyID", nPropertyID); + } + IMultiPropertyGroup* pIMultiPropertyGroup = dynamic_cast(pIBaseClass); + if (!pIMultiPropertyGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIMultiPropertyGroup->RemoveMultiProperty(nPropertyID); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_multipropertygroup_getlayercount(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, Lib3MF_uint32 * pCount) +{ + IBase* pIBaseClass = (IBase *)pMultiPropertyGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMultiPropertyGroup, "MultiPropertyGroup", "GetLayerCount"); + } + if (pCount == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IMultiPropertyGroup* pIMultiPropertyGroup = dynamic_cast(pIBaseClass); + if (!pIMultiPropertyGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pCount = pIMultiPropertyGroup->GetLayerCount(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("Count", *pCount); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_multipropertygroup_addlayer(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, const sLib3MFMultiPropertyLayer * pTheLayer, Lib3MF_uint32 * pLayerIndex) +{ + IBase* pIBaseClass = (IBase *)pMultiPropertyGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMultiPropertyGroup, "MultiPropertyGroup", "AddLayer"); + } + if (pLayerIndex == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IMultiPropertyGroup* pIMultiPropertyGroup = dynamic_cast(pIBaseClass); + if (!pIMultiPropertyGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pLayerIndex = pIMultiPropertyGroup->AddLayer(*pTheLayer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("LayerIndex", *pLayerIndex); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_multipropertygroup_getlayer(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, Lib3MF_uint32 nLayerIndex, sLib3MFMultiPropertyLayer * pTheLayer) +{ + IBase* pIBaseClass = (IBase *)pMultiPropertyGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMultiPropertyGroup, "MultiPropertyGroup", "GetLayer"); + pJournalEntry->addUInt32Parameter("LayerIndex", nLayerIndex); + } + if (pTheLayer == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IMultiPropertyGroup* pIMultiPropertyGroup = dynamic_cast(pIBaseClass); + if (!pIMultiPropertyGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pTheLayer = pIMultiPropertyGroup->GetLayer(nLayerIndex); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_multipropertygroup_removelayer(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, Lib3MF_uint32 nLayerIndex) +{ + IBase* pIBaseClass = (IBase *)pMultiPropertyGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pMultiPropertyGroup, "MultiPropertyGroup", "RemoveLayer"); + pJournalEntry->addUInt32Parameter("LayerIndex", nLayerIndex); + } + IMultiPropertyGroup* pIMultiPropertyGroup = dynamic_cast(pIBaseClass); + if (!pIMultiPropertyGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIMultiPropertyGroup->RemoveLayer(nLayerIndex); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for Attachment +**************************************************************************************************************************/ +Lib3MFResult lib3mf_attachment_getpath(Lib3MF_Attachment pAttachment, const Lib3MF_uint32 nPathBufferSize, Lib3MF_uint32* pPathNeededChars, char * pPathBuffer) +{ + IBase* pIBaseClass = (IBase *)pAttachment; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pAttachment, "Attachment", "GetPath"); + } + if ( (!pPathBuffer) && !(pPathNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sPath(""); + IAttachment* pIAttachment = dynamic_cast(pIBaseClass); + if (!pIAttachment) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + sPath = pIAttachment->GetPath(); + + if (pPathNeededChars) + *pPathNeededChars = (Lib3MF_uint32) (sPath.size()+1); + if (pPathBuffer) { + if (sPath.size() >= nPathBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iPath = 0; iPath < sPath.size(); iPath++) + pPathBuffer[iPath] = sPath[iPath]; + pPathBuffer[sPath.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addStringResult("Path", sPath.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_attachment_setpath(Lib3MF_Attachment pAttachment, const char * pPath) +{ + IBase* pIBaseClass = (IBase *)pAttachment; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pAttachment, "Attachment", "SetPath"); + pJournalEntry->addStringParameter("Path", pPath); + } + if (pPath == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sPath(pPath); + IAttachment* pIAttachment = dynamic_cast(pIBaseClass); + if (!pIAttachment) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIAttachment->SetPath(sPath); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_attachment_packagepart(Lib3MF_Attachment pAttachment, Lib3MF_PackagePart * pPackagePart) +{ + IBase* pIBaseClass = (IBase *)pAttachment; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pAttachment, "Attachment", "PackagePart"); + } + if (pPackagePart == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBasePackagePart(nullptr); + IAttachment* pIAttachment = dynamic_cast(pIBaseClass); + if (!pIAttachment) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBasePackagePart = pIAttachment->PackagePart(); + + *pPackagePart = (IBase*)(pBasePackagePart); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("PackagePart", *pPackagePart); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_attachment_getrelationshiptype(Lib3MF_Attachment pAttachment, const Lib3MF_uint32 nPathBufferSize, Lib3MF_uint32* pPathNeededChars, char * pPathBuffer) +{ + IBase* pIBaseClass = (IBase *)pAttachment; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pAttachment, "Attachment", "GetRelationShipType"); + } + if ( (!pPathBuffer) && !(pPathNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sPath(""); + IAttachment* pIAttachment = dynamic_cast(pIBaseClass); + if (!pIAttachment) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + sPath = pIAttachment->GetRelationShipType(); + + if (pPathNeededChars) + *pPathNeededChars = (Lib3MF_uint32) (sPath.size()+1); + if (pPathBuffer) { + if (sPath.size() >= nPathBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iPath = 0; iPath < sPath.size(); iPath++) + pPathBuffer[iPath] = sPath[iPath]; + pPathBuffer[sPath.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addStringResult("Path", sPath.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_attachment_setrelationshiptype(Lib3MF_Attachment pAttachment, const char * pPath) +{ + IBase* pIBaseClass = (IBase *)pAttachment; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pAttachment, "Attachment", "SetRelationShipType"); + pJournalEntry->addStringParameter("Path", pPath); + } + if (pPath == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sPath(pPath); + IAttachment* pIAttachment = dynamic_cast(pIBaseClass); + if (!pIAttachment) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIAttachment->SetRelationShipType(sPath); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_attachment_writetofile(Lib3MF_Attachment pAttachment, const char * pFileName) +{ + IBase* pIBaseClass = (IBase *)pAttachment; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pAttachment, "Attachment", "WriteToFile"); + pJournalEntry->addStringParameter("FileName", pFileName); + } + if (pFileName == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sFileName(pFileName); + IAttachment* pIAttachment = dynamic_cast(pIBaseClass); + if (!pIAttachment) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIAttachment->WriteToFile(sFileName); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_attachment_readfromfile(Lib3MF_Attachment pAttachment, const char * pFileName) +{ + IBase* pIBaseClass = (IBase *)pAttachment; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pAttachment, "Attachment", "ReadFromFile"); + pJournalEntry->addStringParameter("FileName", pFileName); + } + if (pFileName == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sFileName(pFileName); + IAttachment* pIAttachment = dynamic_cast(pIBaseClass); + if (!pIAttachment) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIAttachment->ReadFromFile(sFileName); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_attachment_readfromcallback(Lib3MF_Attachment pAttachment, Lib3MFReadCallback pTheReadCallback, Lib3MF_uint64 nStreamSize, Lib3MFSeekCallback pTheSeekCallback, Lib3MF_pvoid pUserData) +{ + IBase* pIBaseClass = (IBase *)pAttachment; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pAttachment, "Attachment", "ReadFromCallback"); + pJournalEntry->addUInt64Parameter("StreamSize", nStreamSize); + pJournalEntry->addPointerParameter("UserData", pUserData); + } + IAttachment* pIAttachment = dynamic_cast(pIBaseClass); + if (!pIAttachment) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIAttachment->ReadFromCallback(pTheReadCallback, nStreamSize, pTheSeekCallback, pUserData); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_attachment_getstreamsize(Lib3MF_Attachment pAttachment, Lib3MF_uint64 * pStreamSize) +{ + IBase* pIBaseClass = (IBase *)pAttachment; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pAttachment, "Attachment", "GetStreamSize"); + } + if (pStreamSize == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IAttachment* pIAttachment = dynamic_cast(pIBaseClass); + if (!pIAttachment) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pStreamSize = pIAttachment->GetStreamSize(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt64Result("StreamSize", *pStreamSize); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_attachment_writetobuffer(Lib3MF_Attachment pAttachment, const Lib3MF_uint64 nBufferBufferSize, Lib3MF_uint64* pBufferNeededCount, Lib3MF_uint8 * pBufferBuffer) +{ + IBase* pIBaseClass = (IBase *)pAttachment; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pAttachment, "Attachment", "WriteToBuffer"); + } + if ((!pBufferBuffer) && !(pBufferNeededCount)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IAttachment* pIAttachment = dynamic_cast(pIBaseClass); + if (!pIAttachment) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIAttachment->WriteToBuffer(nBufferBufferSize, pBufferNeededCount, pBufferBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_attachment_readfrombuffer(Lib3MF_Attachment pAttachment, Lib3MF_uint64 nBufferBufferSize, const Lib3MF_uint8 * pBufferBuffer) +{ + IBase* pIBaseClass = (IBase *)pAttachment; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pAttachment, "Attachment", "ReadFromBuffer"); + } + if ( (!pBufferBuffer) && (nBufferBufferSize>0)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IAttachment* pIAttachment = dynamic_cast(pIBaseClass); + if (!pIAttachment) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIAttachment->ReadFromBuffer(nBufferBufferSize, pBufferBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for Texture2D +**************************************************************************************************************************/ +Lib3MFResult lib3mf_texture2d_getattachment(Lib3MF_Texture2D pTexture2D, Lib3MF_Attachment * pAttachment) +{ + IBase* pIBaseClass = (IBase *)pTexture2D; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pTexture2D, "Texture2D", "GetAttachment"); + } + if (pAttachment == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseAttachment(nullptr); + ITexture2D* pITexture2D = dynamic_cast(pIBaseClass); + if (!pITexture2D) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseAttachment = pITexture2D->GetAttachment(); + + *pAttachment = (IBase*)(pBaseAttachment); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("Attachment", *pAttachment); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_texture2d_setattachment(Lib3MF_Texture2D pTexture2D, Lib3MF_Attachment pAttachment) +{ + IBase* pIBaseClass = (IBase *)pTexture2D; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pTexture2D, "Texture2D", "SetAttachment"); + pJournalEntry->addHandleParameter("Attachment", pAttachment); + } + IBase* pIBaseClassAttachment = (IBase *)pAttachment; + IAttachment* pIAttachment = dynamic_cast(pIBaseClassAttachment); + if (!pIAttachment) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDCAST); + + ITexture2D* pITexture2D = dynamic_cast(pIBaseClass); + if (!pITexture2D) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pITexture2D->SetAttachment(pIAttachment); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_texture2d_getcontenttype(Lib3MF_Texture2D pTexture2D, eLib3MFTextureType * pContentType) +{ + IBase* pIBaseClass = (IBase *)pTexture2D; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pTexture2D, "Texture2D", "GetContentType"); + } + if (pContentType == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + ITexture2D* pITexture2D = dynamic_cast(pIBaseClass); + if (!pITexture2D) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pContentType = pITexture2D->GetContentType(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addEnumResult("ContentType", "TextureType", (Lib3MF_int32)(*pContentType)); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_texture2d_setcontenttype(Lib3MF_Texture2D pTexture2D, eLib3MFTextureType eContentType) +{ + IBase* pIBaseClass = (IBase *)pTexture2D; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pTexture2D, "Texture2D", "SetContentType"); + pJournalEntry->addEnumParameter("ContentType", "TextureType", (Lib3MF_int32)(eContentType)); + } + ITexture2D* pITexture2D = dynamic_cast(pIBaseClass); + if (!pITexture2D) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pITexture2D->SetContentType(eContentType); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_texture2d_gettilestyleuv(Lib3MF_Texture2D pTexture2D, eLib3MFTextureTileStyle * pTileStyleU, eLib3MFTextureTileStyle * pTileStyleV) +{ + IBase* pIBaseClass = (IBase *)pTexture2D; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pTexture2D, "Texture2D", "GetTileStyleUV"); + } + if (!pTileStyleU) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (!pTileStyleV) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + ITexture2D* pITexture2D = dynamic_cast(pIBaseClass); + if (!pITexture2D) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pITexture2D->GetTileStyleUV(*pTileStyleU, *pTileStyleV); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addEnumResult("TileStyleU", "TextureTileStyle", (Lib3MF_int32)(*pTileStyleU)); + pJournalEntry->addEnumResult("TileStyleV", "TextureTileStyle", (Lib3MF_int32)(*pTileStyleV)); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_texture2d_settilestyleuv(Lib3MF_Texture2D pTexture2D, eLib3MFTextureTileStyle eTileStyleU, eLib3MFTextureTileStyle eTileStyleV) +{ + IBase* pIBaseClass = (IBase *)pTexture2D; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pTexture2D, "Texture2D", "SetTileStyleUV"); + pJournalEntry->addEnumParameter("TileStyleU", "TextureTileStyle", (Lib3MF_int32)(eTileStyleU)); + pJournalEntry->addEnumParameter("TileStyleV", "TextureTileStyle", (Lib3MF_int32)(eTileStyleV)); + } + ITexture2D* pITexture2D = dynamic_cast(pIBaseClass); + if (!pITexture2D) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pITexture2D->SetTileStyleUV(eTileStyleU, eTileStyleV); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_texture2d_getfilter(Lib3MF_Texture2D pTexture2D, eLib3MFTextureFilter * pFilter) +{ + IBase* pIBaseClass = (IBase *)pTexture2D; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pTexture2D, "Texture2D", "GetFilter"); + } + if (pFilter == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + ITexture2D* pITexture2D = dynamic_cast(pIBaseClass); + if (!pITexture2D) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pFilter = pITexture2D->GetFilter(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addEnumResult("Filter", "TextureFilter", (Lib3MF_int32)(*pFilter)); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_texture2d_setfilter(Lib3MF_Texture2D pTexture2D, eLib3MFTextureFilter eFilter) +{ + IBase* pIBaseClass = (IBase *)pTexture2D; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pTexture2D, "Texture2D", "SetFilter"); + pJournalEntry->addEnumParameter("Filter", "TextureFilter", (Lib3MF_int32)(eFilter)); + } + ITexture2D* pITexture2D = dynamic_cast(pIBaseClass); + if (!pITexture2D) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pITexture2D->SetFilter(eFilter); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for BuildItem +**************************************************************************************************************************/ +Lib3MFResult lib3mf_builditem_getobjectresource(Lib3MF_BuildItem pBuildItem, Lib3MF_Object * pObjectResource) +{ + IBase* pIBaseClass = (IBase *)pBuildItem; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBuildItem, "BuildItem", "GetObjectResource"); + } + if (pObjectResource == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseObjectResource(nullptr); + IBuildItem* pIBuildItem = dynamic_cast(pIBaseClass); + if (!pIBuildItem) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseObjectResource = pIBuildItem->GetObjectResource(); + + *pObjectResource = (IBase*)(pBaseObjectResource); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("ObjectResource", *pObjectResource); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_builditem_getuuid(Lib3MF_BuildItem pBuildItem, bool * pHasUUID, const Lib3MF_uint32 nUUIDBufferSize, Lib3MF_uint32* pUUIDNeededChars, char * pUUIDBuffer) +{ + IBase* pIBaseClass = (IBase *)pBuildItem; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBuildItem, "BuildItem", "GetUUID"); + } + if (!pHasUUID) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if ( (!pUUIDBuffer) && !(pUUIDNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sUUID(""); + IBuildItem* pIBuildItem = dynamic_cast(pIBaseClass); + if (!pIBuildItem) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + sUUID = pIBuildItem->GetUUID(*pHasUUID); + + if (pUUIDNeededChars) + *pUUIDNeededChars = (Lib3MF_uint32) (sUUID.size()+1); + if (pUUIDBuffer) { + if (sUUID.size() >= nUUIDBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iUUID = 0; iUUID < sUUID.size(); iUUID++) + pUUIDBuffer[iUUID] = sUUID[iUUID]; + pUUIDBuffer[sUUID.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addBooleanResult("HasUUID", *pHasUUID); + pJournalEntry->addStringResult("UUID", sUUID.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_builditem_setuuid(Lib3MF_BuildItem pBuildItem, const char * pUUID) +{ + IBase* pIBaseClass = (IBase *)pBuildItem; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBuildItem, "BuildItem", "SetUUID"); + pJournalEntry->addStringParameter("UUID", pUUID); + } + if (pUUID == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sUUID(pUUID); + IBuildItem* pIBuildItem = dynamic_cast(pIBaseClass); + if (!pIBuildItem) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIBuildItem->SetUUID(sUUID); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_builditem_getobjectresourceid(Lib3MF_BuildItem pBuildItem, Lib3MF_uint32 * pUniqueResourceID) +{ + IBase* pIBaseClass = (IBase *)pBuildItem; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBuildItem, "BuildItem", "GetObjectResourceID"); + } + if (pUniqueResourceID == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBuildItem* pIBuildItem = dynamic_cast(pIBaseClass); + if (!pIBuildItem) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pUniqueResourceID = pIBuildItem->GetObjectResourceID(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("UniqueResourceID", *pUniqueResourceID); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_builditem_hasobjecttransform(Lib3MF_BuildItem pBuildItem, bool * pHasTransform) +{ + IBase* pIBaseClass = (IBase *)pBuildItem; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBuildItem, "BuildItem", "HasObjectTransform"); + } + if (pHasTransform == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBuildItem* pIBuildItem = dynamic_cast(pIBaseClass); + if (!pIBuildItem) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pHasTransform = pIBuildItem->HasObjectTransform(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addBooleanResult("HasTransform", *pHasTransform); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_builditem_getobjecttransform(Lib3MF_BuildItem pBuildItem, sLib3MFTransform * pTransform) +{ + IBase* pIBaseClass = (IBase *)pBuildItem; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBuildItem, "BuildItem", "GetObjectTransform"); + } + if (pTransform == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBuildItem* pIBuildItem = dynamic_cast(pIBaseClass); + if (!pIBuildItem) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pTransform = pIBuildItem->GetObjectTransform(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_builditem_setobjecttransform(Lib3MF_BuildItem pBuildItem, const sLib3MFTransform * pTransform) +{ + IBase* pIBaseClass = (IBase *)pBuildItem; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBuildItem, "BuildItem", "SetObjectTransform"); + } + IBuildItem* pIBuildItem = dynamic_cast(pIBaseClass); + if (!pIBuildItem) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIBuildItem->SetObjectTransform(*pTransform); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_builditem_getpartnumber(Lib3MF_BuildItem pBuildItem, const Lib3MF_uint32 nPartNumberBufferSize, Lib3MF_uint32* pPartNumberNeededChars, char * pPartNumberBuffer) +{ + IBase* pIBaseClass = (IBase *)pBuildItem; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBuildItem, "BuildItem", "GetPartNumber"); + } + if ( (!pPartNumberBuffer) && !(pPartNumberNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sPartNumber(""); + IBuildItem* pIBuildItem = dynamic_cast(pIBaseClass); + if (!pIBuildItem) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + sPartNumber = pIBuildItem->GetPartNumber(); + + if (pPartNumberNeededChars) + *pPartNumberNeededChars = (Lib3MF_uint32) (sPartNumber.size()+1); + if (pPartNumberBuffer) { + if (sPartNumber.size() >= nPartNumberBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iPartNumber = 0; iPartNumber < sPartNumber.size(); iPartNumber++) + pPartNumberBuffer[iPartNumber] = sPartNumber[iPartNumber]; + pPartNumberBuffer[sPartNumber.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addStringResult("PartNumber", sPartNumber.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_builditem_setpartnumber(Lib3MF_BuildItem pBuildItem, const char * pSetPartnumber) +{ + IBase* pIBaseClass = (IBase *)pBuildItem; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBuildItem, "BuildItem", "SetPartNumber"); + pJournalEntry->addStringParameter("SetPartnumber", pSetPartnumber); + } + if (pSetPartnumber == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sSetPartnumber(pSetPartnumber); + IBuildItem* pIBuildItem = dynamic_cast(pIBaseClass); + if (!pIBuildItem) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIBuildItem->SetPartNumber(sSetPartnumber); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_builditem_getmetadatagroup(Lib3MF_BuildItem pBuildItem, Lib3MF_MetaDataGroup * pMetaDataGroup) +{ + IBase* pIBaseClass = (IBase *)pBuildItem; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBuildItem, "BuildItem", "GetMetaDataGroup"); + } + if (pMetaDataGroup == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseMetaDataGroup(nullptr); + IBuildItem* pIBuildItem = dynamic_cast(pIBaseClass); + if (!pIBuildItem) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseMetaDataGroup = pIBuildItem->GetMetaDataGroup(); + + *pMetaDataGroup = (IBase*)(pBaseMetaDataGroup); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("MetaDataGroup", *pMetaDataGroup); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_builditem_getoutbox(Lib3MF_BuildItem pBuildItem, sLib3MFBox * pOutbox) +{ + IBase* pIBaseClass = (IBase *)pBuildItem; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBuildItem, "BuildItem", "GetOutbox"); + } + if (pOutbox == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBuildItem* pIBuildItem = dynamic_cast(pIBaseClass); + if (!pIBuildItem) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pOutbox = pIBuildItem->GetOutbox(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for BuildItemIterator +**************************************************************************************************************************/ +Lib3MFResult lib3mf_builditemiterator_movenext(Lib3MF_BuildItemIterator pBuildItemIterator, bool * pHasNext) +{ + IBase* pIBaseClass = (IBase *)pBuildItemIterator; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBuildItemIterator, "BuildItemIterator", "MoveNext"); + } + if (pHasNext == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBuildItemIterator* pIBuildItemIterator = dynamic_cast(pIBaseClass); + if (!pIBuildItemIterator) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pHasNext = pIBuildItemIterator->MoveNext(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addBooleanResult("HasNext", *pHasNext); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_builditemiterator_moveprevious(Lib3MF_BuildItemIterator pBuildItemIterator, bool * pHasPrevious) +{ + IBase* pIBaseClass = (IBase *)pBuildItemIterator; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBuildItemIterator, "BuildItemIterator", "MovePrevious"); + } + if (pHasPrevious == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBuildItemIterator* pIBuildItemIterator = dynamic_cast(pIBaseClass); + if (!pIBuildItemIterator) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pHasPrevious = pIBuildItemIterator->MovePrevious(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addBooleanResult("HasPrevious", *pHasPrevious); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_builditemiterator_getcurrent(Lib3MF_BuildItemIterator pBuildItemIterator, Lib3MF_BuildItem * pBuildItem) +{ + IBase* pIBaseClass = (IBase *)pBuildItemIterator; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBuildItemIterator, "BuildItemIterator", "GetCurrent"); + } + if (pBuildItem == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseBuildItem(nullptr); + IBuildItemIterator* pIBuildItemIterator = dynamic_cast(pIBaseClass); + if (!pIBuildItemIterator) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseBuildItem = pIBuildItemIterator->GetCurrent(); + + *pBuildItem = (IBase*)(pBaseBuildItem); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("BuildItem", *pBuildItem); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_builditemiterator_clone(Lib3MF_BuildItemIterator pBuildItemIterator, Lib3MF_BuildItemIterator * pOutBuildItemIterator) +{ + IBase* pIBaseClass = (IBase *)pBuildItemIterator; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBuildItemIterator, "BuildItemIterator", "Clone"); + } + if (pOutBuildItemIterator == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseOutBuildItemIterator(nullptr); + IBuildItemIterator* pIBuildItemIterator = dynamic_cast(pIBaseClass); + if (!pIBuildItemIterator) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseOutBuildItemIterator = pIBuildItemIterator->Clone(); + + *pOutBuildItemIterator = (IBase*)(pBaseOutBuildItemIterator); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("OutBuildItemIterator", *pOutBuildItemIterator); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_builditemiterator_count(Lib3MF_BuildItemIterator pBuildItemIterator, Lib3MF_uint64 * pCount) +{ + IBase* pIBaseClass = (IBase *)pBuildItemIterator; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pBuildItemIterator, "BuildItemIterator", "Count"); + } + if (pCount == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBuildItemIterator* pIBuildItemIterator = dynamic_cast(pIBaseClass); + if (!pIBuildItemIterator) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pCount = pIBuildItemIterator->Count(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt64Result("Count", *pCount); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for Slice +**************************************************************************************************************************/ +Lib3MFResult lib3mf_slice_setvertices(Lib3MF_Slice pSlice, Lib3MF_uint64 nVerticesBufferSize, const sLib3MFPosition2D * pVerticesBuffer) +{ + IBase* pIBaseClass = (IBase *)pSlice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pSlice, "Slice", "SetVertices"); + } + if ( (!pVerticesBuffer) && (nVerticesBufferSize>0)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + ISlice* pISlice = dynamic_cast(pIBaseClass); + if (!pISlice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pISlice->SetVertices(nVerticesBufferSize, pVerticesBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_slice_getvertices(Lib3MF_Slice pSlice, const Lib3MF_uint64 nVerticesBufferSize, Lib3MF_uint64* pVerticesNeededCount, sLib3MFPosition2D * pVerticesBuffer) +{ + IBase* pIBaseClass = (IBase *)pSlice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pSlice, "Slice", "GetVertices"); + } + if ((!pVerticesBuffer) && !(pVerticesNeededCount)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + ISlice* pISlice = dynamic_cast(pIBaseClass); + if (!pISlice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pISlice->GetVertices(nVerticesBufferSize, pVerticesNeededCount, pVerticesBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_slice_getvertexcount(Lib3MF_Slice pSlice, Lib3MF_uint64 * pCount) +{ + IBase* pIBaseClass = (IBase *)pSlice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pSlice, "Slice", "GetVertexCount"); + } + if (pCount == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + ISlice* pISlice = dynamic_cast(pIBaseClass); + if (!pISlice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pCount = pISlice->GetVertexCount(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt64Result("Count", *pCount); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_slice_addpolygon(Lib3MF_Slice pSlice, Lib3MF_uint64 nIndicesBufferSize, const Lib3MF_uint32 * pIndicesBuffer, Lib3MF_uint64 * pIndex) +{ + IBase* pIBaseClass = (IBase *)pSlice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pSlice, "Slice", "AddPolygon"); + } + if ( (!pIndicesBuffer) && (nIndicesBufferSize>0)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (pIndex == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + ISlice* pISlice = dynamic_cast(pIBaseClass); + if (!pISlice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pIndex = pISlice->AddPolygon(nIndicesBufferSize, pIndicesBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt64Result("Index", *pIndex); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_slice_getpolygoncount(Lib3MF_Slice pSlice, Lib3MF_uint64 * pCount) +{ + IBase* pIBaseClass = (IBase *)pSlice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pSlice, "Slice", "GetPolygonCount"); + } + if (pCount == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + ISlice* pISlice = dynamic_cast(pIBaseClass); + if (!pISlice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pCount = pISlice->GetPolygonCount(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt64Result("Count", *pCount); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_slice_setpolygonindices(Lib3MF_Slice pSlice, Lib3MF_uint64 nIndex, Lib3MF_uint64 nIndicesBufferSize, const Lib3MF_uint32 * pIndicesBuffer) +{ + IBase* pIBaseClass = (IBase *)pSlice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pSlice, "Slice", "SetPolygonIndices"); + pJournalEntry->addUInt64Parameter("Index", nIndex); + } + if ( (!pIndicesBuffer) && (nIndicesBufferSize>0)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + ISlice* pISlice = dynamic_cast(pIBaseClass); + if (!pISlice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pISlice->SetPolygonIndices(nIndex, nIndicesBufferSize, pIndicesBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_slice_getpolygonindices(Lib3MF_Slice pSlice, Lib3MF_uint64 nIndex, const Lib3MF_uint64 nIndicesBufferSize, Lib3MF_uint64* pIndicesNeededCount, Lib3MF_uint32 * pIndicesBuffer) +{ + IBase* pIBaseClass = (IBase *)pSlice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pSlice, "Slice", "GetPolygonIndices"); + pJournalEntry->addUInt64Parameter("Index", nIndex); + } + if ((!pIndicesBuffer) && !(pIndicesNeededCount)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + ISlice* pISlice = dynamic_cast(pIBaseClass); + if (!pISlice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pISlice->GetPolygonIndices(nIndex, nIndicesBufferSize, pIndicesNeededCount, pIndicesBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_slice_getpolygonindexcount(Lib3MF_Slice pSlice, Lib3MF_uint64 nIndex, Lib3MF_uint64 * pCount) +{ + IBase* pIBaseClass = (IBase *)pSlice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pSlice, "Slice", "GetPolygonIndexCount"); + pJournalEntry->addUInt64Parameter("Index", nIndex); + } + if (pCount == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + ISlice* pISlice = dynamic_cast(pIBaseClass); + if (!pISlice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pCount = pISlice->GetPolygonIndexCount(nIndex); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt64Result("Count", *pCount); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_slice_getztop(Lib3MF_Slice pSlice, Lib3MF_double * pZTop) +{ + IBase* pIBaseClass = (IBase *)pSlice; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pSlice, "Slice", "GetZTop"); + } + if (pZTop == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + ISlice* pISlice = dynamic_cast(pIBaseClass); + if (!pISlice) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pZTop = pISlice->GetZTop(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addDoubleResult("ZTop", *pZTop); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for SliceStack +**************************************************************************************************************************/ +Lib3MFResult lib3mf_slicestack_getbottomz(Lib3MF_SliceStack pSliceStack, Lib3MF_double * pZBottom) +{ + IBase* pIBaseClass = (IBase *)pSliceStack; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pSliceStack, "SliceStack", "GetBottomZ"); + } + if (pZBottom == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + ISliceStack* pISliceStack = dynamic_cast(pIBaseClass); + if (!pISliceStack) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pZBottom = pISliceStack->GetBottomZ(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addDoubleResult("ZBottom", *pZBottom); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_slicestack_getslicecount(Lib3MF_SliceStack pSliceStack, Lib3MF_uint64 * pCount) +{ + IBase* pIBaseClass = (IBase *)pSliceStack; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pSliceStack, "SliceStack", "GetSliceCount"); + } + if (pCount == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + ISliceStack* pISliceStack = dynamic_cast(pIBaseClass); + if (!pISliceStack) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pCount = pISliceStack->GetSliceCount(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt64Result("Count", *pCount); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_slicestack_getslice(Lib3MF_SliceStack pSliceStack, Lib3MF_uint64 nSliceIndex, Lib3MF_Slice * pTheSlice) +{ + IBase* pIBaseClass = (IBase *)pSliceStack; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pSliceStack, "SliceStack", "GetSlice"); + pJournalEntry->addUInt64Parameter("SliceIndex", nSliceIndex); + } + if (pTheSlice == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseTheSlice(nullptr); + ISliceStack* pISliceStack = dynamic_cast(pIBaseClass); + if (!pISliceStack) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseTheSlice = pISliceStack->GetSlice(nSliceIndex); + + *pTheSlice = (IBase*)(pBaseTheSlice); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("TheSlice", *pTheSlice); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_slicestack_addslice(Lib3MF_SliceStack pSliceStack, Lib3MF_double dZTop, Lib3MF_Slice * pTheSlice) +{ + IBase* pIBaseClass = (IBase *)pSliceStack; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pSliceStack, "SliceStack", "AddSlice"); + pJournalEntry->addDoubleParameter("ZTop", dZTop); + } + if (pTheSlice == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseTheSlice(nullptr); + ISliceStack* pISliceStack = dynamic_cast(pIBaseClass); + if (!pISliceStack) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseTheSlice = pISliceStack->AddSlice(dZTop); + + *pTheSlice = (IBase*)(pBaseTheSlice); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("TheSlice", *pTheSlice); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_slicestack_getslicerefcount(Lib3MF_SliceStack pSliceStack, Lib3MF_uint64 * pCount) +{ + IBase* pIBaseClass = (IBase *)pSliceStack; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pSliceStack, "SliceStack", "GetSliceRefCount"); + } + if (pCount == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + ISliceStack* pISliceStack = dynamic_cast(pIBaseClass); + if (!pISliceStack) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pCount = pISliceStack->GetSliceRefCount(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt64Result("Count", *pCount); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_slicestack_addslicestackreference(Lib3MF_SliceStack pSliceStack, Lib3MF_SliceStack pTheSliceStack) +{ + IBase* pIBaseClass = (IBase *)pSliceStack; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pSliceStack, "SliceStack", "AddSliceStackReference"); + pJournalEntry->addHandleParameter("TheSliceStack", pTheSliceStack); + } + IBase* pIBaseClassTheSliceStack = (IBase *)pTheSliceStack; + ISliceStack* pITheSliceStack = dynamic_cast(pIBaseClassTheSliceStack); + if (!pITheSliceStack) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDCAST); + + ISliceStack* pISliceStack = dynamic_cast(pIBaseClass); + if (!pISliceStack) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pISliceStack->AddSliceStackReference(pITheSliceStack); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_slicestack_getslicestackreference(Lib3MF_SliceStack pSliceStack, Lib3MF_uint64 nSliceRefIndex, Lib3MF_SliceStack * pTheSliceStack) +{ + IBase* pIBaseClass = (IBase *)pSliceStack; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pSliceStack, "SliceStack", "GetSliceStackReference"); + pJournalEntry->addUInt64Parameter("SliceRefIndex", nSliceRefIndex); + } + if (pTheSliceStack == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseTheSliceStack(nullptr); + ISliceStack* pISliceStack = dynamic_cast(pIBaseClass); + if (!pISliceStack) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseTheSliceStack = pISliceStack->GetSliceStackReference(nSliceRefIndex); + + *pTheSliceStack = (IBase*)(pBaseTheSliceStack); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("TheSliceStack", *pTheSliceStack); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_slicestack_collapseslicereferences(Lib3MF_SliceStack pSliceStack) +{ + IBase* pIBaseClass = (IBase *)pSliceStack; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pSliceStack, "SliceStack", "CollapseSliceReferences"); + } + ISliceStack* pISliceStack = dynamic_cast(pIBaseClass); + if (!pISliceStack) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pISliceStack->CollapseSliceReferences(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_slicestack_setownpath(Lib3MF_SliceStack pSliceStack, const char * pPath) +{ + IBase* pIBaseClass = (IBase *)pSliceStack; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pSliceStack, "SliceStack", "SetOwnPath"); + pJournalEntry->addStringParameter("Path", pPath); + } + if (pPath == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sPath(pPath); + ISliceStack* pISliceStack = dynamic_cast(pIBaseClass); + if (!pISliceStack) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pISliceStack->SetOwnPath(sPath); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_slicestack_getownpath(Lib3MF_SliceStack pSliceStack, const Lib3MF_uint32 nPathBufferSize, Lib3MF_uint32* pPathNeededChars, char * pPathBuffer) +{ + IBase* pIBaseClass = (IBase *)pSliceStack; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pSliceStack, "SliceStack", "GetOwnPath"); + } + if ( (!pPathBuffer) && !(pPathNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sPath(""); + ISliceStack* pISliceStack = dynamic_cast(pIBaseClass); + if (!pISliceStack) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + sPath = pISliceStack->GetOwnPath(); + + if (pPathNeededChars) + *pPathNeededChars = (Lib3MF_uint32) (sPath.size()+1); + if (pPathBuffer) { + if (sPath.size() >= nPathBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iPath = 0; iPath < sPath.size(); iPath++) + pPathBuffer[iPath] = sPath[iPath]; + pPathBuffer[sPath.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addStringResult("Path", sPath.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for Consumer +**************************************************************************************************************************/ +Lib3MFResult lib3mf_consumer_getconsumerid(Lib3MF_Consumer pConsumer, const Lib3MF_uint32 nConsumerIDBufferSize, Lib3MF_uint32* pConsumerIDNeededChars, char * pConsumerIDBuffer) +{ + IBase* pIBaseClass = (IBase *)pConsumer; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pConsumer, "Consumer", "GetConsumerID"); + } + if ( (!pConsumerIDBuffer) && !(pConsumerIDNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sConsumerID(""); + IConsumer* pIConsumer = dynamic_cast(pIBaseClass); + if (!pIConsumer) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + sConsumerID = pIConsumer->GetConsumerID(); + + if (pConsumerIDNeededChars) + *pConsumerIDNeededChars = (Lib3MF_uint32) (sConsumerID.size()+1); + if (pConsumerIDBuffer) { + if (sConsumerID.size() >= nConsumerIDBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iConsumerID = 0; iConsumerID < sConsumerID.size(); iConsumerID++) + pConsumerIDBuffer[iConsumerID] = sConsumerID[iConsumerID]; + pConsumerIDBuffer[sConsumerID.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addStringResult("ConsumerID", sConsumerID.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_consumer_getkeyid(Lib3MF_Consumer pConsumer, const Lib3MF_uint32 nKeyIDBufferSize, Lib3MF_uint32* pKeyIDNeededChars, char * pKeyIDBuffer) +{ + IBase* pIBaseClass = (IBase *)pConsumer; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pConsumer, "Consumer", "GetKeyID"); + } + if ( (!pKeyIDBuffer) && !(pKeyIDNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sKeyID(""); + IConsumer* pIConsumer = dynamic_cast(pIBaseClass); + if (!pIConsumer) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + sKeyID = pIConsumer->GetKeyID(); + + if (pKeyIDNeededChars) + *pKeyIDNeededChars = (Lib3MF_uint32) (sKeyID.size()+1); + if (pKeyIDBuffer) { + if (sKeyID.size() >= nKeyIDBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iKeyID = 0; iKeyID < sKeyID.size(); iKeyID++) + pKeyIDBuffer[iKeyID] = sKeyID[iKeyID]; + pKeyIDBuffer[sKeyID.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addStringResult("KeyID", sKeyID.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_consumer_getkeyvalue(Lib3MF_Consumer pConsumer, const Lib3MF_uint32 nKeyValueBufferSize, Lib3MF_uint32* pKeyValueNeededChars, char * pKeyValueBuffer) +{ + IBase* pIBaseClass = (IBase *)pConsumer; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pConsumer, "Consumer", "GetKeyValue"); + } + if ( (!pKeyValueBuffer) && !(pKeyValueNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sKeyValue(""); + IConsumer* pIConsumer = dynamic_cast(pIBaseClass); + if (!pIConsumer) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + sKeyValue = pIConsumer->GetKeyValue(); + + if (pKeyValueNeededChars) + *pKeyValueNeededChars = (Lib3MF_uint32) (sKeyValue.size()+1); + if (pKeyValueBuffer) { + if (sKeyValue.size() >= nKeyValueBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iKeyValue = 0; iKeyValue < sKeyValue.size(); iKeyValue++) + pKeyValueBuffer[iKeyValue] = sKeyValue[iKeyValue]; + pKeyValueBuffer[sKeyValue.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addStringResult("KeyValue", sKeyValue.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for AccessRight +**************************************************************************************************************************/ +Lib3MFResult lib3mf_accessright_getconsumer(Lib3MF_AccessRight pAccessRight, Lib3MF_Consumer * pConsumer) +{ + IBase* pIBaseClass = (IBase *)pAccessRight; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pAccessRight, "AccessRight", "GetConsumer"); + } + if (pConsumer == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseConsumer(nullptr); + IAccessRight* pIAccessRight = dynamic_cast(pIBaseClass); + if (!pIAccessRight) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseConsumer = pIAccessRight->GetConsumer(); + + *pConsumer = (IBase*)(pBaseConsumer); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("Consumer", *pConsumer); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_accessright_getwrappingalgorithm(Lib3MF_AccessRight pAccessRight, eLib3MFWrappingAlgorithm * pAlgorithm) +{ + IBase* pIBaseClass = (IBase *)pAccessRight; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pAccessRight, "AccessRight", "GetWrappingAlgorithm"); + } + if (pAlgorithm == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IAccessRight* pIAccessRight = dynamic_cast(pIBaseClass); + if (!pIAccessRight) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pAlgorithm = pIAccessRight->GetWrappingAlgorithm(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addEnumResult("Algorithm", "WrappingAlgorithm", (Lib3MF_int32)(*pAlgorithm)); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_accessright_getmgfalgorithm(Lib3MF_AccessRight pAccessRight, eLib3MFMgfAlgorithm * pAlgorithm) +{ + IBase* pIBaseClass = (IBase *)pAccessRight; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pAccessRight, "AccessRight", "GetMgfAlgorithm"); + } + if (pAlgorithm == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IAccessRight* pIAccessRight = dynamic_cast(pIBaseClass); + if (!pIAccessRight) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pAlgorithm = pIAccessRight->GetMgfAlgorithm(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addEnumResult("Algorithm", "MgfAlgorithm", (Lib3MF_int32)(*pAlgorithm)); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_accessright_getdigestmethod(Lib3MF_AccessRight pAccessRight, eLib3MFDigestMethod * pAlgorithm) +{ + IBase* pIBaseClass = (IBase *)pAccessRight; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pAccessRight, "AccessRight", "GetDigestMethod"); + } + if (pAlgorithm == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IAccessRight* pIAccessRight = dynamic_cast(pIBaseClass); + if (!pIAccessRight) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pAlgorithm = pIAccessRight->GetDigestMethod(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addEnumResult("Algorithm", "DigestMethod", (Lib3MF_int32)(*pAlgorithm)); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for ContentEncryptionParams +**************************************************************************************************************************/ +Lib3MFResult lib3mf_contentencryptionparams_getencryptionalgorithm(Lib3MF_ContentEncryptionParams pContentEncryptionParams, eLib3MFEncryptionAlgorithm * pAlgorithm) +{ + IBase* pIBaseClass = (IBase *)pContentEncryptionParams; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pContentEncryptionParams, "ContentEncryptionParams", "GetEncryptionAlgorithm"); + } + if (pAlgorithm == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IContentEncryptionParams* pIContentEncryptionParams = dynamic_cast(pIBaseClass); + if (!pIContentEncryptionParams) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pAlgorithm = pIContentEncryptionParams->GetEncryptionAlgorithm(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addEnumResult("Algorithm", "EncryptionAlgorithm", (Lib3MF_int32)(*pAlgorithm)); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_contentencryptionparams_getkey(Lib3MF_ContentEncryptionParams pContentEncryptionParams, const Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64* pByteDataNeededCount, Lib3MF_uint8 * pByteDataBuffer) +{ + IBase* pIBaseClass = (IBase *)pContentEncryptionParams; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pContentEncryptionParams, "ContentEncryptionParams", "GetKey"); + } + if ((!pByteDataBuffer) && !(pByteDataNeededCount)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IContentEncryptionParams* pIContentEncryptionParams = dynamic_cast(pIBaseClass); + if (!pIContentEncryptionParams) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIContentEncryptionParams->GetKey(nByteDataBufferSize, pByteDataNeededCount, pByteDataBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_contentencryptionparams_getinitializationvector(Lib3MF_ContentEncryptionParams pContentEncryptionParams, const Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64* pByteDataNeededCount, Lib3MF_uint8 * pByteDataBuffer) +{ + IBase* pIBaseClass = (IBase *)pContentEncryptionParams; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pContentEncryptionParams, "ContentEncryptionParams", "GetInitializationVector"); + } + if ((!pByteDataBuffer) && !(pByteDataNeededCount)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IContentEncryptionParams* pIContentEncryptionParams = dynamic_cast(pIBaseClass); + if (!pIContentEncryptionParams) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIContentEncryptionParams->GetInitializationVector(nByteDataBufferSize, pByteDataNeededCount, pByteDataBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_contentencryptionparams_getauthenticationtag(Lib3MF_ContentEncryptionParams pContentEncryptionParams, const Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64* pByteDataNeededCount, Lib3MF_uint8 * pByteDataBuffer) +{ + IBase* pIBaseClass = (IBase *)pContentEncryptionParams; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pContentEncryptionParams, "ContentEncryptionParams", "GetAuthenticationTag"); + } + if ((!pByteDataBuffer) && !(pByteDataNeededCount)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IContentEncryptionParams* pIContentEncryptionParams = dynamic_cast(pIBaseClass); + if (!pIContentEncryptionParams) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIContentEncryptionParams->GetAuthenticationTag(nByteDataBufferSize, pByteDataNeededCount, pByteDataBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_contentencryptionparams_setauthenticationtag(Lib3MF_ContentEncryptionParams pContentEncryptionParams, Lib3MF_uint64 nByteDataBufferSize, const Lib3MF_uint8 * pByteDataBuffer) +{ + IBase* pIBaseClass = (IBase *)pContentEncryptionParams; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pContentEncryptionParams, "ContentEncryptionParams", "SetAuthenticationTag"); + } + if ( (!pByteDataBuffer) && (nByteDataBufferSize>0)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IContentEncryptionParams* pIContentEncryptionParams = dynamic_cast(pIBaseClass); + if (!pIContentEncryptionParams) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIContentEncryptionParams->SetAuthenticationTag(nByteDataBufferSize, pByteDataBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_contentencryptionparams_getadditionalauthenticationdata(Lib3MF_ContentEncryptionParams pContentEncryptionParams, const Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64* pByteDataNeededCount, Lib3MF_uint8 * pByteDataBuffer) +{ + IBase* pIBaseClass = (IBase *)pContentEncryptionParams; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pContentEncryptionParams, "ContentEncryptionParams", "GetAdditionalAuthenticationData"); + } + if ((!pByteDataBuffer) && !(pByteDataNeededCount)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IContentEncryptionParams* pIContentEncryptionParams = dynamic_cast(pIBaseClass); + if (!pIContentEncryptionParams) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIContentEncryptionParams->GetAdditionalAuthenticationData(nByteDataBufferSize, pByteDataNeededCount, pByteDataBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_contentencryptionparams_getdescriptor(Lib3MF_ContentEncryptionParams pContentEncryptionParams, Lib3MF_uint64 * pDescriptor) +{ + IBase* pIBaseClass = (IBase *)pContentEncryptionParams; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pContentEncryptionParams, "ContentEncryptionParams", "GetDescriptor"); + } + if (pDescriptor == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IContentEncryptionParams* pIContentEncryptionParams = dynamic_cast(pIBaseClass); + if (!pIContentEncryptionParams) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pDescriptor = pIContentEncryptionParams->GetDescriptor(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt64Result("Descriptor", *pDescriptor); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_contentencryptionparams_getkeyuuid(Lib3MF_ContentEncryptionParams pContentEncryptionParams, const Lib3MF_uint32 nUUIDBufferSize, Lib3MF_uint32* pUUIDNeededChars, char * pUUIDBuffer) +{ + IBase* pIBaseClass = (IBase *)pContentEncryptionParams; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pContentEncryptionParams, "ContentEncryptionParams", "GetKeyUUID"); + } + if ( (!pUUIDBuffer) && !(pUUIDNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sUUID(""); + IContentEncryptionParams* pIContentEncryptionParams = dynamic_cast(pIBaseClass); + if (!pIContentEncryptionParams) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + sUUID = pIContentEncryptionParams->GetKeyUUID(); + + if (pUUIDNeededChars) + *pUUIDNeededChars = (Lib3MF_uint32) (sUUID.size()+1); + if (pUUIDBuffer) { + if (sUUID.size() >= nUUIDBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iUUID = 0; iUUID < sUUID.size(); iUUID++) + pUUIDBuffer[iUUID] = sUUID[iUUID]; + pUUIDBuffer[sUUID.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addStringResult("UUID", sUUID.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for ResourceData +**************************************************************************************************************************/ +Lib3MFResult lib3mf_resourcedata_getpath(Lib3MF_ResourceData pResourceData, Lib3MF_PackagePart * pPath) +{ + IBase* pIBaseClass = (IBase *)pResourceData; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pResourceData, "ResourceData", "GetPath"); + } + if (pPath == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBasePath(nullptr); + IResourceData* pIResourceData = dynamic_cast(pIBaseClass); + if (!pIResourceData) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBasePath = pIResourceData->GetPath(); + + *pPath = (IBase*)(pBasePath); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("Path", *pPath); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_resourcedata_getencryptionalgorithm(Lib3MF_ResourceData pResourceData, eLib3MFEncryptionAlgorithm * pEncryptionAlgorithm) +{ + IBase* pIBaseClass = (IBase *)pResourceData; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pResourceData, "ResourceData", "GetEncryptionAlgorithm"); + } + if (pEncryptionAlgorithm == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IResourceData* pIResourceData = dynamic_cast(pIBaseClass); + if (!pIResourceData) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pEncryptionAlgorithm = pIResourceData->GetEncryptionAlgorithm(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addEnumResult("EncryptionAlgorithm", "EncryptionAlgorithm", (Lib3MF_int32)(*pEncryptionAlgorithm)); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_resourcedata_getcompression(Lib3MF_ResourceData pResourceData, eLib3MFCompression * pCompression) +{ + IBase* pIBaseClass = (IBase *)pResourceData; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pResourceData, "ResourceData", "GetCompression"); + } + if (pCompression == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IResourceData* pIResourceData = dynamic_cast(pIBaseClass); + if (!pIResourceData) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pCompression = pIResourceData->GetCompression(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addEnumResult("Compression", "Compression", (Lib3MF_int32)(*pCompression)); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_resourcedata_getadditionalauthenticationdata(Lib3MF_ResourceData pResourceData, const Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64* pByteDataNeededCount, Lib3MF_uint8 * pByteDataBuffer) +{ + IBase* pIBaseClass = (IBase *)pResourceData; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pResourceData, "ResourceData", "GetAdditionalAuthenticationData"); + } + if ((!pByteDataBuffer) && !(pByteDataNeededCount)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IResourceData* pIResourceData = dynamic_cast(pIBaseClass); + if (!pIResourceData) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIResourceData->GetAdditionalAuthenticationData(nByteDataBufferSize, pByteDataNeededCount, pByteDataBuffer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for ResourceDataGroup +**************************************************************************************************************************/ +Lib3MFResult lib3mf_resourcedatagroup_getkeyuuid(Lib3MF_ResourceDataGroup pResourceDataGroup, const Lib3MF_uint32 nUUIDBufferSize, Lib3MF_uint32* pUUIDNeededChars, char * pUUIDBuffer) +{ + IBase* pIBaseClass = (IBase *)pResourceDataGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pResourceDataGroup, "ResourceDataGroup", "GetKeyUUID"); + } + if ( (!pUUIDBuffer) && !(pUUIDNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sUUID(""); + IResourceDataGroup* pIResourceDataGroup = dynamic_cast(pIBaseClass); + if (!pIResourceDataGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + sUUID = pIResourceDataGroup->GetKeyUUID(); + + if (pUUIDNeededChars) + *pUUIDNeededChars = (Lib3MF_uint32) (sUUID.size()+1); + if (pUUIDBuffer) { + if (sUUID.size() >= nUUIDBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iUUID = 0; iUUID < sUUID.size(); iUUID++) + pUUIDBuffer[iUUID] = sUUID[iUUID]; + pUUIDBuffer[sUUID.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addStringResult("UUID", sUUID.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_resourcedatagroup_addaccessright(Lib3MF_ResourceDataGroup pResourceDataGroup, Lib3MF_Consumer pConsumer, eLib3MFWrappingAlgorithm eWrappingAlgorithm, eLib3MFMgfAlgorithm eMgfAlgorithm, eLib3MFDigestMethod eDigestMethod, Lib3MF_AccessRight * pTheAccessRight) +{ + IBase* pIBaseClass = (IBase *)pResourceDataGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pResourceDataGroup, "ResourceDataGroup", "AddAccessRight"); + pJournalEntry->addHandleParameter("Consumer", pConsumer); + pJournalEntry->addEnumParameter("WrappingAlgorithm", "WrappingAlgorithm", (Lib3MF_int32)(eWrappingAlgorithm)); + pJournalEntry->addEnumParameter("MgfAlgorithm", "MgfAlgorithm", (Lib3MF_int32)(eMgfAlgorithm)); + pJournalEntry->addEnumParameter("DigestMethod", "DigestMethod", (Lib3MF_int32)(eDigestMethod)); + } + if (pTheAccessRight == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pIBaseClassConsumer = (IBase *)pConsumer; + IConsumer* pIConsumer = dynamic_cast(pIBaseClassConsumer); + if (!pIConsumer) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDCAST); + + IBase* pBaseTheAccessRight(nullptr); + IResourceDataGroup* pIResourceDataGroup = dynamic_cast(pIBaseClass); + if (!pIResourceDataGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseTheAccessRight = pIResourceDataGroup->AddAccessRight(pIConsumer, eWrappingAlgorithm, eMgfAlgorithm, eDigestMethod); + + *pTheAccessRight = (IBase*)(pBaseTheAccessRight); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("TheAccessRight", *pTheAccessRight); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_resourcedatagroup_findaccessrightbyconsumer(Lib3MF_ResourceDataGroup pResourceDataGroup, Lib3MF_Consumer pConsumer, Lib3MF_AccessRight * pTheAccessRight) +{ + IBase* pIBaseClass = (IBase *)pResourceDataGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pResourceDataGroup, "ResourceDataGroup", "FindAccessRightByConsumer"); + pJournalEntry->addHandleParameter("Consumer", pConsumer); + } + if (pTheAccessRight == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pIBaseClassConsumer = (IBase *)pConsumer; + IConsumer* pIConsumer = dynamic_cast(pIBaseClassConsumer); + if (!pIConsumer) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDCAST); + + IBase* pBaseTheAccessRight(nullptr); + IResourceDataGroup* pIResourceDataGroup = dynamic_cast(pIBaseClass); + if (!pIResourceDataGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseTheAccessRight = pIResourceDataGroup->FindAccessRightByConsumer(pIConsumer); + + *pTheAccessRight = (IBase*)(pBaseTheAccessRight); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("TheAccessRight", *pTheAccessRight); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_resourcedatagroup_removeaccessright(Lib3MF_ResourceDataGroup pResourceDataGroup, Lib3MF_Consumer pConsumer) +{ + IBase* pIBaseClass = (IBase *)pResourceDataGroup; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pResourceDataGroup, "ResourceDataGroup", "RemoveAccessRight"); + pJournalEntry->addHandleParameter("Consumer", pConsumer); + } + IBase* pIBaseClassConsumer = (IBase *)pConsumer; + IConsumer* pIConsumer = dynamic_cast(pIBaseClassConsumer); + if (!pIConsumer) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDCAST); + + IResourceDataGroup* pIResourceDataGroup = dynamic_cast(pIBaseClass); + if (!pIResourceDataGroup) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIResourceDataGroup->RemoveAccessRight(pIConsumer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for KeyStore +**************************************************************************************************************************/ +Lib3MFResult lib3mf_keystore_addconsumer(Lib3MF_KeyStore pKeyStore, const char * pConsumerID, const char * pKeyID, const char * pKeyValue, Lib3MF_Consumer * pConsumer) +{ + IBase* pIBaseClass = (IBase *)pKeyStore; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pKeyStore, "KeyStore", "AddConsumer"); + pJournalEntry->addStringParameter("ConsumerID", pConsumerID); + pJournalEntry->addStringParameter("KeyID", pKeyID); + pJournalEntry->addStringParameter("KeyValue", pKeyValue); + } + if (pConsumerID == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (pKeyID == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (pKeyValue == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (pConsumer == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sConsumerID(pConsumerID); + std::string sKeyID(pKeyID); + std::string sKeyValue(pKeyValue); + IBase* pBaseConsumer(nullptr); + IKeyStore* pIKeyStore = dynamic_cast(pIBaseClass); + if (!pIKeyStore) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseConsumer = pIKeyStore->AddConsumer(sConsumerID, sKeyID, sKeyValue); + + *pConsumer = (IBase*)(pBaseConsumer); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("Consumer", *pConsumer); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_keystore_getconsumercount(Lib3MF_KeyStore pKeyStore, Lib3MF_uint64 * pCount) +{ + IBase* pIBaseClass = (IBase *)pKeyStore; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pKeyStore, "KeyStore", "GetConsumerCount"); + } + if (pCount == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IKeyStore* pIKeyStore = dynamic_cast(pIBaseClass); + if (!pIKeyStore) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pCount = pIKeyStore->GetConsumerCount(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt64Result("Count", *pCount); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_keystore_getconsumer(Lib3MF_KeyStore pKeyStore, Lib3MF_uint64 nConsumerIndex, Lib3MF_Consumer * pConsumer) +{ + IBase* pIBaseClass = (IBase *)pKeyStore; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pKeyStore, "KeyStore", "GetConsumer"); + pJournalEntry->addUInt64Parameter("ConsumerIndex", nConsumerIndex); + } + if (pConsumer == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseConsumer(nullptr); + IKeyStore* pIKeyStore = dynamic_cast(pIBaseClass); + if (!pIKeyStore) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseConsumer = pIKeyStore->GetConsumer(nConsumerIndex); + + *pConsumer = (IBase*)(pBaseConsumer); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("Consumer", *pConsumer); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_keystore_removeconsumer(Lib3MF_KeyStore pKeyStore, Lib3MF_Consumer pConsumer) +{ + IBase* pIBaseClass = (IBase *)pKeyStore; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pKeyStore, "KeyStore", "RemoveConsumer"); + pJournalEntry->addHandleParameter("Consumer", pConsumer); + } + IBase* pIBaseClassConsumer = (IBase *)pConsumer; + IConsumer* pIConsumer = dynamic_cast(pIBaseClassConsumer); + if (!pIConsumer) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDCAST); + + IKeyStore* pIKeyStore = dynamic_cast(pIBaseClass); + if (!pIKeyStore) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIKeyStore->RemoveConsumer(pIConsumer); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_keystore_findconsumer(Lib3MF_KeyStore pKeyStore, const char * pConsumerID, Lib3MF_Consumer * pConsumer) +{ + IBase* pIBaseClass = (IBase *)pKeyStore; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pKeyStore, "KeyStore", "FindConsumer"); + pJournalEntry->addStringParameter("ConsumerID", pConsumerID); + } + if (pConsumerID == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (pConsumer == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sConsumerID(pConsumerID); + IBase* pBaseConsumer(nullptr); + IKeyStore* pIKeyStore = dynamic_cast(pIBaseClass); + if (!pIKeyStore) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseConsumer = pIKeyStore->FindConsumer(sConsumerID); + + *pConsumer = (IBase*)(pBaseConsumer); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("Consumer", *pConsumer); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_keystore_getresourcedatagroupcount(Lib3MF_KeyStore pKeyStore, Lib3MF_uint64 * pCount) +{ + IBase* pIBaseClass = (IBase *)pKeyStore; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pKeyStore, "KeyStore", "GetResourceDataGroupCount"); + } + if (pCount == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IKeyStore* pIKeyStore = dynamic_cast(pIBaseClass); + if (!pIKeyStore) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pCount = pIKeyStore->GetResourceDataGroupCount(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt64Result("Count", *pCount); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_keystore_addresourcedatagroup(Lib3MF_KeyStore pKeyStore, Lib3MF_ResourceDataGroup * pResourceDataGroup) +{ + IBase* pIBaseClass = (IBase *)pKeyStore; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pKeyStore, "KeyStore", "AddResourceDataGroup"); + } + if (pResourceDataGroup == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseResourceDataGroup(nullptr); + IKeyStore* pIKeyStore = dynamic_cast(pIBaseClass); + if (!pIKeyStore) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseResourceDataGroup = pIKeyStore->AddResourceDataGroup(); + + *pResourceDataGroup = (IBase*)(pBaseResourceDataGroup); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("ResourceDataGroup", *pResourceDataGroup); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_keystore_getresourcedatagroup(Lib3MF_KeyStore pKeyStore, Lib3MF_uint64 nResourceDataIndex, Lib3MF_ResourceDataGroup * pResourceDataGroup) +{ + IBase* pIBaseClass = (IBase *)pKeyStore; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pKeyStore, "KeyStore", "GetResourceDataGroup"); + pJournalEntry->addUInt64Parameter("ResourceDataIndex", nResourceDataIndex); + } + if (pResourceDataGroup == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseResourceDataGroup(nullptr); + IKeyStore* pIKeyStore = dynamic_cast(pIBaseClass); + if (!pIKeyStore) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseResourceDataGroup = pIKeyStore->GetResourceDataGroup(nResourceDataIndex); + + *pResourceDataGroup = (IBase*)(pBaseResourceDataGroup); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("ResourceDataGroup", *pResourceDataGroup); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_keystore_removeresourcedatagroup(Lib3MF_KeyStore pKeyStore, Lib3MF_ResourceDataGroup pResourceDataGroup) +{ + IBase* pIBaseClass = (IBase *)pKeyStore; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pKeyStore, "KeyStore", "RemoveResourceDataGroup"); + pJournalEntry->addHandleParameter("ResourceDataGroup", pResourceDataGroup); + } + IBase* pIBaseClassResourceDataGroup = (IBase *)pResourceDataGroup; + IResourceDataGroup* pIResourceDataGroup = dynamic_cast(pIBaseClassResourceDataGroup); + if (!pIResourceDataGroup) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDCAST); + + IKeyStore* pIKeyStore = dynamic_cast(pIBaseClass); + if (!pIKeyStore) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIKeyStore->RemoveResourceDataGroup(pIResourceDataGroup); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_keystore_findresourcedatagroup(Lib3MF_KeyStore pKeyStore, Lib3MF_PackagePart pPartPath, Lib3MF_ResourceDataGroup * pResourceDataGroup) +{ + IBase* pIBaseClass = (IBase *)pKeyStore; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pKeyStore, "KeyStore", "FindResourceDataGroup"); + pJournalEntry->addHandleParameter("PartPath", pPartPath); + } + if (pResourceDataGroup == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pIBaseClassPartPath = (IBase *)pPartPath; + IPackagePart* pIPartPath = dynamic_cast(pIBaseClassPartPath); + if (!pIPartPath) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDCAST); + + IBase* pBaseResourceDataGroup(nullptr); + IKeyStore* pIKeyStore = dynamic_cast(pIBaseClass); + if (!pIKeyStore) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseResourceDataGroup = pIKeyStore->FindResourceDataGroup(pIPartPath); + + *pResourceDataGroup = (IBase*)(pBaseResourceDataGroup); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("ResourceDataGroup", *pResourceDataGroup); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_keystore_addresourcedata(Lib3MF_KeyStore pKeyStore, Lib3MF_ResourceDataGroup pResourceDataGroup, Lib3MF_PackagePart pPartPath, eLib3MFEncryptionAlgorithm eAlgorithm, eLib3MFCompression eCompression, Lib3MF_uint64 nAdditionalAuthenticationDataBufferSize, const Lib3MF_uint8 * pAdditionalAuthenticationDataBuffer, Lib3MF_ResourceData * pResourceData) +{ + IBase* pIBaseClass = (IBase *)pKeyStore; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pKeyStore, "KeyStore", "AddResourceData"); + pJournalEntry->addHandleParameter("ResourceDataGroup", pResourceDataGroup); + pJournalEntry->addHandleParameter("PartPath", pPartPath); + pJournalEntry->addEnumParameter("Algorithm", "EncryptionAlgorithm", (Lib3MF_int32)(eAlgorithm)); + pJournalEntry->addEnumParameter("Compression", "Compression", (Lib3MF_int32)(eCompression)); + } + if ( (!pAdditionalAuthenticationDataBuffer) && (nAdditionalAuthenticationDataBufferSize>0)) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (pResourceData == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pIBaseClassResourceDataGroup = (IBase *)pResourceDataGroup; + IResourceDataGroup* pIResourceDataGroup = dynamic_cast(pIBaseClassResourceDataGroup); + if (!pIResourceDataGroup) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDCAST); + + IBase* pIBaseClassPartPath = (IBase *)pPartPath; + IPackagePart* pIPartPath = dynamic_cast(pIBaseClassPartPath); + if (!pIPartPath) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDCAST); + + IBase* pBaseResourceData(nullptr); + IKeyStore* pIKeyStore = dynamic_cast(pIBaseClass); + if (!pIKeyStore) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseResourceData = pIKeyStore->AddResourceData(pIResourceDataGroup, pIPartPath, eAlgorithm, eCompression, nAdditionalAuthenticationDataBufferSize, pAdditionalAuthenticationDataBuffer); + + *pResourceData = (IBase*)(pBaseResourceData); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("ResourceData", *pResourceData); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_keystore_removeresourcedata(Lib3MF_KeyStore pKeyStore, Lib3MF_ResourceData pResourceData) +{ + IBase* pIBaseClass = (IBase *)pKeyStore; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pKeyStore, "KeyStore", "RemoveResourceData"); + pJournalEntry->addHandleParameter("ResourceData", pResourceData); + } + IBase* pIBaseClassResourceData = (IBase *)pResourceData; + IResourceData* pIResourceData = dynamic_cast(pIBaseClassResourceData); + if (!pIResourceData) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDCAST); + + IKeyStore* pIKeyStore = dynamic_cast(pIBaseClass); + if (!pIKeyStore) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIKeyStore->RemoveResourceData(pIResourceData); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_keystore_findresourcedata(Lib3MF_KeyStore pKeyStore, Lib3MF_PackagePart pResourcePath, Lib3MF_ResourceData * pResourceData) +{ + IBase* pIBaseClass = (IBase *)pKeyStore; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pKeyStore, "KeyStore", "FindResourceData"); + pJournalEntry->addHandleParameter("ResourcePath", pResourcePath); + } + if (pResourceData == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pIBaseClassResourcePath = (IBase *)pResourcePath; + IPackagePart* pIResourcePath = dynamic_cast(pIBaseClassResourcePath); + if (!pIResourcePath) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDCAST); + + IBase* pBaseResourceData(nullptr); + IKeyStore* pIKeyStore = dynamic_cast(pIBaseClass); + if (!pIKeyStore) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseResourceData = pIKeyStore->FindResourceData(pIResourcePath); + + *pResourceData = (IBase*)(pBaseResourceData); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("ResourceData", *pResourceData); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_keystore_getresourcedatacount(Lib3MF_KeyStore pKeyStore, Lib3MF_uint64 * pCount) +{ + IBase* pIBaseClass = (IBase *)pKeyStore; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pKeyStore, "KeyStore", "GetResourceDataCount"); + } + if (pCount == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IKeyStore* pIKeyStore = dynamic_cast(pIBaseClass); + if (!pIKeyStore) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pCount = pIKeyStore->GetResourceDataCount(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt64Result("Count", *pCount); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_keystore_getresourcedata(Lib3MF_KeyStore pKeyStore, Lib3MF_uint64 nResourceDataIndex, Lib3MF_ResourceData * pResourceData) +{ + IBase* pIBaseClass = (IBase *)pKeyStore; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pKeyStore, "KeyStore", "GetResourceData"); + pJournalEntry->addUInt64Parameter("ResourceDataIndex", nResourceDataIndex); + } + if (pResourceData == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseResourceData(nullptr); + IKeyStore* pIKeyStore = dynamic_cast(pIBaseClass); + if (!pIKeyStore) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseResourceData = pIKeyStore->GetResourceData(nResourceDataIndex); + + *pResourceData = (IBase*)(pBaseResourceData); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("ResourceData", *pResourceData); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_keystore_getuuid(Lib3MF_KeyStore pKeyStore, bool * pHasUUID, const Lib3MF_uint32 nUUIDBufferSize, Lib3MF_uint32* pUUIDNeededChars, char * pUUIDBuffer) +{ + IBase* pIBaseClass = (IBase *)pKeyStore; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pKeyStore, "KeyStore", "GetUUID"); + } + if (!pHasUUID) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if ( (!pUUIDBuffer) && !(pUUIDNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sUUID(""); + IKeyStore* pIKeyStore = dynamic_cast(pIBaseClass); + if (!pIKeyStore) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + sUUID = pIKeyStore->GetUUID(*pHasUUID); + + if (pUUIDNeededChars) + *pUUIDNeededChars = (Lib3MF_uint32) (sUUID.size()+1); + if (pUUIDBuffer) { + if (sUUID.size() >= nUUIDBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iUUID = 0; iUUID < sUUID.size(); iUUID++) + pUUIDBuffer[iUUID] = sUUID[iUUID]; + pUUIDBuffer[sUUID.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addBooleanResult("HasUUID", *pHasUUID); + pJournalEntry->addStringResult("UUID", sUUID.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_keystore_setuuid(Lib3MF_KeyStore pKeyStore, const char * pUUID) +{ + IBase* pIBaseClass = (IBase *)pKeyStore; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pKeyStore, "KeyStore", "SetUUID"); + pJournalEntry->addStringParameter("UUID", pUUID); + } + if (pUUID == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sUUID(pUUID); + IKeyStore* pIKeyStore = dynamic_cast(pIBaseClass); + if (!pIKeyStore) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIKeyStore->SetUUID(sUUID); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + +/************************************************************************************************************************* + Class implementation for Model +**************************************************************************************************************************/ +Lib3MFResult lib3mf_model_rootmodelpart(Lib3MF_Model pModel, Lib3MF_PackagePart * pRootModelPart) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "RootModelPart"); + } + if (pRootModelPart == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseRootModelPart(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseRootModelPart = pIModel->RootModelPart(); + + *pRootModelPart = (IBase*)(pBaseRootModelPart); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("RootModelPart", *pRootModelPart); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_findorcreatepackagepart(Lib3MF_Model pModel, const char * pAbsolutePath, Lib3MF_PackagePart * pModelPart) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "FindOrCreatePackagePart"); + pJournalEntry->addStringParameter("AbsolutePath", pAbsolutePath); + } + if (pAbsolutePath == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (pModelPart == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sAbsolutePath(pAbsolutePath); + IBase* pBaseModelPart(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseModelPart = pIModel->FindOrCreatePackagePart(sAbsolutePath); + + *pModelPart = (IBase*)(pBaseModelPart); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("ModelPart", *pModelPart); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_setunit(Lib3MF_Model pModel, eLib3MFModelUnit eUnit) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "SetUnit"); + pJournalEntry->addEnumParameter("Unit", "ModelUnit", (Lib3MF_int32)(eUnit)); + } + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIModel->SetUnit(eUnit); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_getunit(Lib3MF_Model pModel, eLib3MFModelUnit * pUnit) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetUnit"); + } + if (pUnit == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pUnit = pIModel->GetUnit(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addEnumResult("Unit", "ModelUnit", (Lib3MF_int32)(*pUnit)); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_getlanguage(Lib3MF_Model pModel, const Lib3MF_uint32 nLanguageBufferSize, Lib3MF_uint32* pLanguageNeededChars, char * pLanguageBuffer) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetLanguage"); + } + if ( (!pLanguageBuffer) && !(pLanguageNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sLanguage(""); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + sLanguage = pIModel->GetLanguage(); + + if (pLanguageNeededChars) + *pLanguageNeededChars = (Lib3MF_uint32) (sLanguage.size()+1); + if (pLanguageBuffer) { + if (sLanguage.size() >= nLanguageBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iLanguage = 0; iLanguage < sLanguage.size(); iLanguage++) + pLanguageBuffer[iLanguage] = sLanguage[iLanguage]; + pLanguageBuffer[sLanguage.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addStringResult("Language", sLanguage.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_setlanguage(Lib3MF_Model pModel, const char * pLanguage) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "SetLanguage"); + pJournalEntry->addStringParameter("Language", pLanguage); + } + if (pLanguage == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sLanguage(pLanguage); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIModel->SetLanguage(sLanguage); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_querywriter(Lib3MF_Model pModel, const char * pWriterClass, Lib3MF_Writer * pWriterInstance) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "QueryWriter"); + pJournalEntry->addStringParameter("WriterClass", pWriterClass); + } + if (pWriterClass == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (pWriterInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sWriterClass(pWriterClass); + IBase* pBaseWriterInstance(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseWriterInstance = pIModel->QueryWriter(sWriterClass); + + *pWriterInstance = (IBase*)(pBaseWriterInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("WriterInstance", *pWriterInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_queryreader(Lib3MF_Model pModel, const char * pReaderClass, Lib3MF_Reader * pReaderInstance) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "QueryReader"); + pJournalEntry->addStringParameter("ReaderClass", pReaderClass); + } + if (pReaderClass == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (pReaderInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sReaderClass(pReaderClass); + IBase* pBaseReaderInstance(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseReaderInstance = pIModel->QueryReader(sReaderClass); + + *pReaderInstance = (IBase*)(pBaseReaderInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("ReaderInstance", *pReaderInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_gettexture2dbyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, Lib3MF_Texture2D * pTextureInstance) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetTexture2DByID"); + pJournalEntry->addUInt32Parameter("UniqueResourceID", nUniqueResourceID); + } + if (pTextureInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseTextureInstance(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseTextureInstance = pIModel->GetTexture2DByID(nUniqueResourceID); + + *pTextureInstance = (IBase*)(pBaseTextureInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("TextureInstance", *pTextureInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_getpropertytypebyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, eLib3MFPropertyType * pThePropertyType) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetPropertyTypeByID"); + pJournalEntry->addUInt32Parameter("UniqueResourceID", nUniqueResourceID); + } + if (pThePropertyType == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pThePropertyType = pIModel->GetPropertyTypeByID(nUniqueResourceID); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addEnumResult("ThePropertyType", "PropertyType", (Lib3MF_int32)(*pThePropertyType)); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_getbasematerialgroupbyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, Lib3MF_BaseMaterialGroup * pBaseMaterialGroupInstance) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetBaseMaterialGroupByID"); + pJournalEntry->addUInt32Parameter("UniqueResourceID", nUniqueResourceID); + } + if (pBaseMaterialGroupInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseBaseMaterialGroupInstance(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseBaseMaterialGroupInstance = pIModel->GetBaseMaterialGroupByID(nUniqueResourceID); + + *pBaseMaterialGroupInstance = (IBase*)(pBaseBaseMaterialGroupInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("BaseMaterialGroupInstance", *pBaseMaterialGroupInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_gettexture2dgroupbyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, Lib3MF_Texture2DGroup * pTexture2DGroupInstance) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetTexture2DGroupByID"); + pJournalEntry->addUInt32Parameter("UniqueResourceID", nUniqueResourceID); + } + if (pTexture2DGroupInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseTexture2DGroupInstance(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseTexture2DGroupInstance = pIModel->GetTexture2DGroupByID(nUniqueResourceID); + + *pTexture2DGroupInstance = (IBase*)(pBaseTexture2DGroupInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("Texture2DGroupInstance", *pTexture2DGroupInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_getcompositematerialsbyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, Lib3MF_CompositeMaterials * pCompositeMaterialsInstance) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetCompositeMaterialsByID"); + pJournalEntry->addUInt32Parameter("UniqueResourceID", nUniqueResourceID); + } + if (pCompositeMaterialsInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseCompositeMaterialsInstance(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseCompositeMaterialsInstance = pIModel->GetCompositeMaterialsByID(nUniqueResourceID); + + *pCompositeMaterialsInstance = (IBase*)(pBaseCompositeMaterialsInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("CompositeMaterialsInstance", *pCompositeMaterialsInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_getmultipropertygroupbyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, Lib3MF_MultiPropertyGroup * pMultiPropertyGroupInstance) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetMultiPropertyGroupByID"); + pJournalEntry->addUInt32Parameter("UniqueResourceID", nUniqueResourceID); + } + if (pMultiPropertyGroupInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseMultiPropertyGroupInstance(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseMultiPropertyGroupInstance = pIModel->GetMultiPropertyGroupByID(nUniqueResourceID); + + *pMultiPropertyGroupInstance = (IBase*)(pBaseMultiPropertyGroupInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("MultiPropertyGroupInstance", *pMultiPropertyGroupInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_getmeshobjectbyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, Lib3MF_MeshObject * pMeshObjectInstance) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetMeshObjectByID"); + pJournalEntry->addUInt32Parameter("UniqueResourceID", nUniqueResourceID); + } + if (pMeshObjectInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseMeshObjectInstance(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseMeshObjectInstance = pIModel->GetMeshObjectByID(nUniqueResourceID); + + *pMeshObjectInstance = (IBase*)(pBaseMeshObjectInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("MeshObjectInstance", *pMeshObjectInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_getcomponentsobjectbyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, Lib3MF_ComponentsObject * pComponentsObjectInstance) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetComponentsObjectByID"); + pJournalEntry->addUInt32Parameter("UniqueResourceID", nUniqueResourceID); + } + if (pComponentsObjectInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseComponentsObjectInstance(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseComponentsObjectInstance = pIModel->GetComponentsObjectByID(nUniqueResourceID); + + *pComponentsObjectInstance = (IBase*)(pBaseComponentsObjectInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("ComponentsObjectInstance", *pComponentsObjectInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_getcolorgroupbyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, Lib3MF_ColorGroup * pColorGroupInstance) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetColorGroupByID"); + pJournalEntry->addUInt32Parameter("UniqueResourceID", nUniqueResourceID); + } + if (pColorGroupInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseColorGroupInstance(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseColorGroupInstance = pIModel->GetColorGroupByID(nUniqueResourceID); + + *pColorGroupInstance = (IBase*)(pBaseColorGroupInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("ColorGroupInstance", *pColorGroupInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_getslicestackbyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, Lib3MF_SliceStack * pSliceStacInstance) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetSliceStackByID"); + pJournalEntry->addUInt32Parameter("UniqueResourceID", nUniqueResourceID); + } + if (pSliceStacInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseSliceStacInstance(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseSliceStacInstance = pIModel->GetSliceStackByID(nUniqueResourceID); + + *pSliceStacInstance = (IBase*)(pBaseSliceStacInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("SliceStacInstance", *pSliceStacInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_getbuilduuid(Lib3MF_Model pModel, bool * pHasUUID, const Lib3MF_uint32 nUUIDBufferSize, Lib3MF_uint32* pUUIDNeededChars, char * pUUIDBuffer) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetBuildUUID"); + } + if (!pHasUUID) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if ( (!pUUIDBuffer) && !(pUUIDNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sUUID(""); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + sUUID = pIModel->GetBuildUUID(*pHasUUID); + + if (pUUIDNeededChars) + *pUUIDNeededChars = (Lib3MF_uint32) (sUUID.size()+1); + if (pUUIDBuffer) { + if (sUUID.size() >= nUUIDBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iUUID = 0; iUUID < sUUID.size(); iUUID++) + pUUIDBuffer[iUUID] = sUUID[iUUID]; + pUUIDBuffer[sUUID.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addBooleanResult("HasUUID", *pHasUUID); + pJournalEntry->addStringResult("UUID", sUUID.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_setbuilduuid(Lib3MF_Model pModel, const char * pUUID) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "SetBuildUUID"); + pJournalEntry->addStringParameter("UUID", pUUID); + } + if (pUUID == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sUUID(pUUID); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIModel->SetBuildUUID(sUUID); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_getbuilditems(Lib3MF_Model pModel, Lib3MF_BuildItemIterator * pBuildItemIterator) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetBuildItems"); + } + if (pBuildItemIterator == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseBuildItemIterator(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseBuildItemIterator = pIModel->GetBuildItems(); + + *pBuildItemIterator = (IBase*)(pBaseBuildItemIterator); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("BuildItemIterator", *pBuildItemIterator); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_getoutbox(Lib3MF_Model pModel, sLib3MFBox * pOutbox) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetOutbox"); + } + if (pOutbox == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pOutbox = pIModel->GetOutbox(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_getresources(Lib3MF_Model pModel, Lib3MF_ResourceIterator * pResourceIterator) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetResources"); + } + if (pResourceIterator == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseResourceIterator(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseResourceIterator = pIModel->GetResources(); + + *pResourceIterator = (IBase*)(pBaseResourceIterator); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("ResourceIterator", *pResourceIterator); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_getobjects(Lib3MF_Model pModel, Lib3MF_ObjectIterator * pResourceIterator) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetObjects"); + } + if (pResourceIterator == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseResourceIterator(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseResourceIterator = pIModel->GetObjects(); + + *pResourceIterator = (IBase*)(pBaseResourceIterator); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("ResourceIterator", *pResourceIterator); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_getmeshobjects(Lib3MF_Model pModel, Lib3MF_MeshObjectIterator * pResourceIterator) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetMeshObjects"); + } + if (pResourceIterator == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseResourceIterator(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseResourceIterator = pIModel->GetMeshObjects(); + + *pResourceIterator = (IBase*)(pBaseResourceIterator); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("ResourceIterator", *pResourceIterator); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_getcomponentsobjects(Lib3MF_Model pModel, Lib3MF_ComponentsObjectIterator * pResourceIterator) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetComponentsObjects"); + } + if (pResourceIterator == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseResourceIterator(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseResourceIterator = pIModel->GetComponentsObjects(); + + *pResourceIterator = (IBase*)(pBaseResourceIterator); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("ResourceIterator", *pResourceIterator); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_gettexture2ds(Lib3MF_Model pModel, Lib3MF_Texture2DIterator * pResourceIterator) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetTexture2Ds"); + } + if (pResourceIterator == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseResourceIterator(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseResourceIterator = pIModel->GetTexture2Ds(); + + *pResourceIterator = (IBase*)(pBaseResourceIterator); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("ResourceIterator", *pResourceIterator); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_getbasematerialgroups(Lib3MF_Model pModel, Lib3MF_BaseMaterialGroupIterator * pResourceIterator) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetBaseMaterialGroups"); + } + if (pResourceIterator == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseResourceIterator(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseResourceIterator = pIModel->GetBaseMaterialGroups(); + + *pResourceIterator = (IBase*)(pBaseResourceIterator); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("ResourceIterator", *pResourceIterator); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_getcolorgroups(Lib3MF_Model pModel, Lib3MF_ColorGroupIterator * pResourceIterator) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetColorGroups"); + } + if (pResourceIterator == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseResourceIterator(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseResourceIterator = pIModel->GetColorGroups(); + + *pResourceIterator = (IBase*)(pBaseResourceIterator); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("ResourceIterator", *pResourceIterator); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_gettexture2dgroups(Lib3MF_Model pModel, Lib3MF_Texture2DGroupIterator * pResourceIterator) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetTexture2DGroups"); + } + if (pResourceIterator == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseResourceIterator(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseResourceIterator = pIModel->GetTexture2DGroups(); + + *pResourceIterator = (IBase*)(pBaseResourceIterator); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("ResourceIterator", *pResourceIterator); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_getcompositematerials(Lib3MF_Model pModel, Lib3MF_CompositeMaterialsIterator * pResourceIterator) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetCompositeMaterials"); + } + if (pResourceIterator == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseResourceIterator(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseResourceIterator = pIModel->GetCompositeMaterials(); + + *pResourceIterator = (IBase*)(pBaseResourceIterator); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("ResourceIterator", *pResourceIterator); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_getmultipropertygroups(Lib3MF_Model pModel, Lib3MF_MultiPropertyGroupIterator * pResourceIterator) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetMultiPropertyGroups"); + } + if (pResourceIterator == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseResourceIterator(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseResourceIterator = pIModel->GetMultiPropertyGroups(); + + *pResourceIterator = (IBase*)(pBaseResourceIterator); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("ResourceIterator", *pResourceIterator); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_getslicestacks(Lib3MF_Model pModel, Lib3MF_SliceStackIterator * pResourceIterator) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetSliceStacks"); + } + if (pResourceIterator == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseResourceIterator(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseResourceIterator = pIModel->GetSliceStacks(); + + *pResourceIterator = (IBase*)(pBaseResourceIterator); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("ResourceIterator", *pResourceIterator); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_mergetomodel(Lib3MF_Model pModel, Lib3MF_Model * pMergedModelInstance) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "MergeToModel"); + } + if (pMergedModelInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseMergedModelInstance(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseMergedModelInstance = pIModel->MergeToModel(); + + *pMergedModelInstance = (IBase*)(pBaseMergedModelInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("MergedModelInstance", *pMergedModelInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_addmeshobject(Lib3MF_Model pModel, Lib3MF_MeshObject * pMeshObjectInstance) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "AddMeshObject"); + } + if (pMeshObjectInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseMeshObjectInstance(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseMeshObjectInstance = pIModel->AddMeshObject(); + + *pMeshObjectInstance = (IBase*)(pBaseMeshObjectInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("MeshObjectInstance", *pMeshObjectInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_addcomponentsobject(Lib3MF_Model pModel, Lib3MF_ComponentsObject * pComponentsObjectInstance) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "AddComponentsObject"); + } + if (pComponentsObjectInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseComponentsObjectInstance(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseComponentsObjectInstance = pIModel->AddComponentsObject(); + + *pComponentsObjectInstance = (IBase*)(pBaseComponentsObjectInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("ComponentsObjectInstance", *pComponentsObjectInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_addslicestack(Lib3MF_Model pModel, Lib3MF_double dZBottom, Lib3MF_SliceStack * pSliceStackInstance) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "AddSliceStack"); + pJournalEntry->addDoubleParameter("ZBottom", dZBottom); + } + if (pSliceStackInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseSliceStackInstance(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseSliceStackInstance = pIModel->AddSliceStack(dZBottom); + + *pSliceStackInstance = (IBase*)(pBaseSliceStackInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("SliceStackInstance", *pSliceStackInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_addtexture2dfromattachment(Lib3MF_Model pModel, Lib3MF_Attachment pTextureAttachment, Lib3MF_Texture2D * pTexture2DInstance) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "AddTexture2DFromAttachment"); + pJournalEntry->addHandleParameter("TextureAttachment", pTextureAttachment); + } + if (pTexture2DInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pIBaseClassTextureAttachment = (IBase *)pTextureAttachment; + IAttachment* pITextureAttachment = dynamic_cast(pIBaseClassTextureAttachment); + if (!pITextureAttachment) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDCAST); + + IBase* pBaseTexture2DInstance(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseTexture2DInstance = pIModel->AddTexture2DFromAttachment(pITextureAttachment); + + *pTexture2DInstance = (IBase*)(pBaseTexture2DInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("Texture2DInstance", *pTexture2DInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_addbasematerialgroup(Lib3MF_Model pModel, Lib3MF_BaseMaterialGroup * pBaseMaterialGroupInstance) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "AddBaseMaterialGroup"); + } + if (pBaseMaterialGroupInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseBaseMaterialGroupInstance(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseBaseMaterialGroupInstance = pIModel->AddBaseMaterialGroup(); + + *pBaseMaterialGroupInstance = (IBase*)(pBaseBaseMaterialGroupInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("BaseMaterialGroupInstance", *pBaseMaterialGroupInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_addcolorgroup(Lib3MF_Model pModel, Lib3MF_ColorGroup * pColorGroupInstance) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "AddColorGroup"); + } + if (pColorGroupInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseColorGroupInstance(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseColorGroupInstance = pIModel->AddColorGroup(); + + *pColorGroupInstance = (IBase*)(pBaseColorGroupInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("ColorGroupInstance", *pColorGroupInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_addtexture2dgroup(Lib3MF_Model pModel, Lib3MF_Texture2D pTexture2DInstance, Lib3MF_Texture2DGroup * pTexture2DGroupInstance) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "AddTexture2DGroup"); + pJournalEntry->addHandleParameter("Texture2DInstance", pTexture2DInstance); + } + if (pTexture2DGroupInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pIBaseClassTexture2DInstance = (IBase *)pTexture2DInstance; + ITexture2D* pITexture2DInstance = dynamic_cast(pIBaseClassTexture2DInstance); + if (!pITexture2DInstance) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDCAST); + + IBase* pBaseTexture2DGroupInstance(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseTexture2DGroupInstance = pIModel->AddTexture2DGroup(pITexture2DInstance); + + *pTexture2DGroupInstance = (IBase*)(pBaseTexture2DGroupInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("Texture2DGroupInstance", *pTexture2DGroupInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_addcompositematerials(Lib3MF_Model pModel, Lib3MF_BaseMaterialGroup pBaseMaterialGroupInstance, Lib3MF_CompositeMaterials * pCompositeMaterialsInstance) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "AddCompositeMaterials"); + pJournalEntry->addHandleParameter("BaseMaterialGroupInstance", pBaseMaterialGroupInstance); + } + if (pCompositeMaterialsInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pIBaseClassBaseMaterialGroupInstance = (IBase *)pBaseMaterialGroupInstance; + IBaseMaterialGroup* pIBaseMaterialGroupInstance = dynamic_cast(pIBaseClassBaseMaterialGroupInstance); + if (!pIBaseMaterialGroupInstance) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDCAST); + + IBase* pBaseCompositeMaterialsInstance(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseCompositeMaterialsInstance = pIModel->AddCompositeMaterials(pIBaseMaterialGroupInstance); + + *pCompositeMaterialsInstance = (IBase*)(pBaseCompositeMaterialsInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("CompositeMaterialsInstance", *pCompositeMaterialsInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_addmultipropertygroup(Lib3MF_Model pModel, Lib3MF_MultiPropertyGroup * pMultiPropertyGroupInstance) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "AddMultiPropertyGroup"); + } + if (pMultiPropertyGroupInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseMultiPropertyGroupInstance(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseMultiPropertyGroupInstance = pIModel->AddMultiPropertyGroup(); + + *pMultiPropertyGroupInstance = (IBase*)(pBaseMultiPropertyGroupInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("MultiPropertyGroupInstance", *pMultiPropertyGroupInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_addbuilditem(Lib3MF_Model pModel, Lib3MF_Object pObject, const sLib3MFTransform * pTransform, Lib3MF_BuildItem * pBuildItemInstance) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "AddBuildItem"); + pJournalEntry->addHandleParameter("Object", pObject); + } + if (pBuildItemInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pIBaseClassObject = (IBase *)pObject; + IObject* pIObject = dynamic_cast(pIBaseClassObject); + if (!pIObject) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDCAST); + + IBase* pBaseBuildItemInstance(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseBuildItemInstance = pIModel->AddBuildItem(pIObject, *pTransform); + + *pBuildItemInstance = (IBase*)(pBaseBuildItemInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("BuildItemInstance", *pBuildItemInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_removebuilditem(Lib3MF_Model pModel, Lib3MF_BuildItem pBuildItemInstance) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "RemoveBuildItem"); + pJournalEntry->addHandleParameter("BuildItemInstance", pBuildItemInstance); + } + IBase* pIBaseClassBuildItemInstance = (IBase *)pBuildItemInstance; + IBuildItem* pIBuildItemInstance = dynamic_cast(pIBaseClassBuildItemInstance); + if (!pIBuildItemInstance) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDCAST); + + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIModel->RemoveBuildItem(pIBuildItemInstance); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_getmetadatagroup(Lib3MF_Model pModel, Lib3MF_MetaDataGroup * pTheMetaDataGroup) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetMetaDataGroup"); + } + if (pTheMetaDataGroup == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseTheMetaDataGroup(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseTheMetaDataGroup = pIModel->GetMetaDataGroup(); + + *pTheMetaDataGroup = (IBase*)(pBaseTheMetaDataGroup); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("TheMetaDataGroup", *pTheMetaDataGroup); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_addattachment(Lib3MF_Model pModel, const char * pURI, const char * pRelationShipType, Lib3MF_Attachment * pAttachmentInstance) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "AddAttachment"); + pJournalEntry->addStringParameter("URI", pURI); + pJournalEntry->addStringParameter("RelationShipType", pRelationShipType); + } + if (pURI == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (pRelationShipType == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (pAttachmentInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sURI(pURI); + std::string sRelationShipType(pRelationShipType); + IBase* pBaseAttachmentInstance(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseAttachmentInstance = pIModel->AddAttachment(sURI, sRelationShipType); + + *pAttachmentInstance = (IBase*)(pBaseAttachmentInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("AttachmentInstance", *pAttachmentInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_removeattachment(Lib3MF_Model pModel, Lib3MF_Attachment pAttachmentInstance) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "RemoveAttachment"); + pJournalEntry->addHandleParameter("AttachmentInstance", pAttachmentInstance); + } + IBase* pIBaseClassAttachmentInstance = (IBase *)pAttachmentInstance; + IAttachment* pIAttachmentInstance = dynamic_cast(pIBaseClassAttachmentInstance); + if (!pIAttachmentInstance) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDCAST); + + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIModel->RemoveAttachment(pIAttachmentInstance); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_getattachment(Lib3MF_Model pModel, Lib3MF_uint32 nIndex, Lib3MF_Attachment * pAttachmentInstance) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetAttachment"); + pJournalEntry->addUInt32Parameter("Index", nIndex); + } + if (pAttachmentInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseAttachmentInstance(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseAttachmentInstance = pIModel->GetAttachment(nIndex); + + *pAttachmentInstance = (IBase*)(pBaseAttachmentInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("AttachmentInstance", *pAttachmentInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_findattachment(Lib3MF_Model pModel, const char * pURI, Lib3MF_Attachment * pAttachmentInstance) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "FindAttachment"); + pJournalEntry->addStringParameter("URI", pURI); + } + if (pURI == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (pAttachmentInstance == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sURI(pURI); + IBase* pBaseAttachmentInstance(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseAttachmentInstance = pIModel->FindAttachment(sURI); + + *pAttachmentInstance = (IBase*)(pBaseAttachmentInstance); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("AttachmentInstance", *pAttachmentInstance); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_getattachmentcount(Lib3MF_Model pModel, Lib3MF_uint32 * pAttachmentCount) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetAttachmentCount"); + } + if (pAttachmentCount == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pAttachmentCount = pIModel->GetAttachmentCount(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("AttachmentCount", *pAttachmentCount); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_haspackagethumbnailattachment(Lib3MF_Model pModel, bool * pHasThumbnail) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "HasPackageThumbnailAttachment"); + } + if (pHasThumbnail == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + *pHasThumbnail = pIModel->HasPackageThumbnailAttachment(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addBooleanResult("HasThumbnail", *pHasThumbnail); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_createpackagethumbnailattachment(Lib3MF_Model pModel, Lib3MF_Attachment * pAttachment) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "CreatePackageThumbnailAttachment"); + } + if (pAttachment == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseAttachment(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseAttachment = pIModel->CreatePackageThumbnailAttachment(); + + *pAttachment = (IBase*)(pBaseAttachment); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("Attachment", *pAttachment); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_getpackagethumbnailattachment(Lib3MF_Model pModel, Lib3MF_Attachment * pAttachment) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetPackageThumbnailAttachment"); + } + if (pAttachment == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseAttachment(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseAttachment = pIModel->GetPackageThumbnailAttachment(); + + *pAttachment = (IBase*)(pBaseAttachment); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("Attachment", *pAttachment); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_removepackagethumbnailattachment(Lib3MF_Model pModel) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "RemovePackageThumbnailAttachment"); + } + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIModel->RemovePackageThumbnailAttachment(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_addcustomcontenttype(Lib3MF_Model pModel, const char * pExtension, const char * pContentType) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "AddCustomContentType"); + pJournalEntry->addStringParameter("Extension", pExtension); + pJournalEntry->addStringParameter("ContentType", pContentType); + } + if (pExtension == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (pContentType == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sExtension(pExtension); + std::string sContentType(pContentType); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIModel->AddCustomContentType(sExtension, sContentType); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_removecustomcontenttype(Lib3MF_Model pModel, const char * pExtension) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "RemoveCustomContentType"); + pJournalEntry->addStringParameter("Extension", pExtension); + } + if (pExtension == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sExtension(pExtension); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIModel->RemoveCustomContentType(sExtension); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_setrandomnumbercallback(Lib3MF_Model pModel, Lib3MFRandomNumberCallback pTheCallback, Lib3MF_pvoid pUserData) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "SetRandomNumberCallback"); + pJournalEntry->addPointerParameter("UserData", pUserData); + } + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pIModel->SetRandomNumberCallback(pTheCallback, pUserData); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_model_getkeystore(Lib3MF_Model pModel, Lib3MF_KeyStore * pKeyStore) +{ + IBase* pIBaseClass = (IBase *)pModel; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginClassMethod(pModel, "Model", "GetKeyStore"); + } + if (pKeyStore == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseKeyStore(nullptr); + IModel* pIModel = dynamic_cast(pIBaseClass); + if (!pIModel) + throw ELib3MFInterfaceException(LIB3MF_ERROR_INVALIDCAST); + + pBaseKeyStore = pIModel->GetKeyStore(); + + *pKeyStore = (IBase*)(pBaseKeyStore); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("KeyStore", *pKeyStore); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + + +/************************************************************************************************************************* + Function table lookup implementation +**************************************************************************************************************************/ + +Lib3MFResult _lib3mf_getprocaddress_internal(const char * pProcName, void ** ppProcAddress) +{ + static bool sbProcAddressMapHasBeenInitialized = false; + static std::map sProcAddressMap; + if (!sbProcAddressMapHasBeenInitialized) { + sProcAddressMap["lib3mf_writer_writetofile"] = (void*)&lib3mf_writer_writetofile; + sProcAddressMap["lib3mf_writer_getstreamsize"] = (void*)&lib3mf_writer_getstreamsize; + sProcAddressMap["lib3mf_writer_writetobuffer"] = (void*)&lib3mf_writer_writetobuffer; + sProcAddressMap["lib3mf_writer_writetocallback"] = (void*)&lib3mf_writer_writetocallback; + sProcAddressMap["lib3mf_writer_setprogresscallback"] = (void*)&lib3mf_writer_setprogresscallback; + sProcAddressMap["lib3mf_writer_getdecimalprecision"] = (void*)&lib3mf_writer_getdecimalprecision; + sProcAddressMap["lib3mf_writer_setdecimalprecision"] = (void*)&lib3mf_writer_setdecimalprecision; + sProcAddressMap["lib3mf_writer_setstrictmodeactive"] = (void*)&lib3mf_writer_setstrictmodeactive; + sProcAddressMap["lib3mf_writer_getstrictmodeactive"] = (void*)&lib3mf_writer_getstrictmodeactive; + sProcAddressMap["lib3mf_writer_getwarning"] = (void*)&lib3mf_writer_getwarning; + sProcAddressMap["lib3mf_writer_getwarningcount"] = (void*)&lib3mf_writer_getwarningcount; + sProcAddressMap["lib3mf_writer_addkeywrappingcallback"] = (void*)&lib3mf_writer_addkeywrappingcallback; + sProcAddressMap["lib3mf_writer_setcontentencryptioncallback"] = (void*)&lib3mf_writer_setcontentencryptioncallback; + sProcAddressMap["lib3mf_reader_readfromfile"] = (void*)&lib3mf_reader_readfromfile; + sProcAddressMap["lib3mf_reader_readfrombuffer"] = (void*)&lib3mf_reader_readfrombuffer; + sProcAddressMap["lib3mf_reader_readfromcallback"] = (void*)&lib3mf_reader_readfromcallback; + sProcAddressMap["lib3mf_reader_setprogresscallback"] = (void*)&lib3mf_reader_setprogresscallback; + sProcAddressMap["lib3mf_reader_addrelationtoread"] = (void*)&lib3mf_reader_addrelationtoread; + sProcAddressMap["lib3mf_reader_removerelationtoread"] = (void*)&lib3mf_reader_removerelationtoread; + sProcAddressMap["lib3mf_reader_setstrictmodeactive"] = (void*)&lib3mf_reader_setstrictmodeactive; + sProcAddressMap["lib3mf_reader_getstrictmodeactive"] = (void*)&lib3mf_reader_getstrictmodeactive; + sProcAddressMap["lib3mf_reader_getwarning"] = (void*)&lib3mf_reader_getwarning; + sProcAddressMap["lib3mf_reader_getwarningcount"] = (void*)&lib3mf_reader_getwarningcount; + sProcAddressMap["lib3mf_reader_addkeywrappingcallback"] = (void*)&lib3mf_reader_addkeywrappingcallback; + sProcAddressMap["lib3mf_reader_setcontentencryptioncallback"] = (void*)&lib3mf_reader_setcontentencryptioncallback; + sProcAddressMap["lib3mf_packagepart_getpath"] = (void*)&lib3mf_packagepart_getpath; + sProcAddressMap["lib3mf_packagepart_setpath"] = (void*)&lib3mf_packagepart_setpath; + sProcAddressMap["lib3mf_resource_getresourceid"] = (void*)&lib3mf_resource_getresourceid; + sProcAddressMap["lib3mf_resource_getuniqueresourceid"] = (void*)&lib3mf_resource_getuniqueresourceid; + sProcAddressMap["lib3mf_resource_packagepart"] = (void*)&lib3mf_resource_packagepart; + sProcAddressMap["lib3mf_resource_setpackagepart"] = (void*)&lib3mf_resource_setpackagepart; + sProcAddressMap["lib3mf_resource_getmodelresourceid"] = (void*)&lib3mf_resource_getmodelresourceid; + sProcAddressMap["lib3mf_resourceiterator_movenext"] = (void*)&lib3mf_resourceiterator_movenext; + sProcAddressMap["lib3mf_resourceiterator_moveprevious"] = (void*)&lib3mf_resourceiterator_moveprevious; + sProcAddressMap["lib3mf_resourceiterator_getcurrent"] = (void*)&lib3mf_resourceiterator_getcurrent; + sProcAddressMap["lib3mf_resourceiterator_clone"] = (void*)&lib3mf_resourceiterator_clone; + sProcAddressMap["lib3mf_resourceiterator_count"] = (void*)&lib3mf_resourceiterator_count; + sProcAddressMap["lib3mf_slicestackiterator_getcurrentslicestack"] = (void*)&lib3mf_slicestackiterator_getcurrentslicestack; + sProcAddressMap["lib3mf_objectiterator_getcurrentobject"] = (void*)&lib3mf_objectiterator_getcurrentobject; + sProcAddressMap["lib3mf_meshobjectiterator_getcurrentmeshobject"] = (void*)&lib3mf_meshobjectiterator_getcurrentmeshobject; + sProcAddressMap["lib3mf_componentsobjectiterator_getcurrentcomponentsobject"] = (void*)&lib3mf_componentsobjectiterator_getcurrentcomponentsobject; + sProcAddressMap["lib3mf_texture2diterator_getcurrenttexture2d"] = (void*)&lib3mf_texture2diterator_getcurrenttexture2d; + sProcAddressMap["lib3mf_basematerialgroupiterator_getcurrentbasematerialgroup"] = (void*)&lib3mf_basematerialgroupiterator_getcurrentbasematerialgroup; + sProcAddressMap["lib3mf_colorgroupiterator_getcurrentcolorgroup"] = (void*)&lib3mf_colorgroupiterator_getcurrentcolorgroup; + sProcAddressMap["lib3mf_texture2dgroupiterator_getcurrenttexture2dgroup"] = (void*)&lib3mf_texture2dgroupiterator_getcurrenttexture2dgroup; + sProcAddressMap["lib3mf_compositematerialsiterator_getcurrentcompositematerials"] = (void*)&lib3mf_compositematerialsiterator_getcurrentcompositematerials; + sProcAddressMap["lib3mf_multipropertygroupiterator_getcurrentmultipropertygroup"] = (void*)&lib3mf_multipropertygroupiterator_getcurrentmultipropertygroup; + sProcAddressMap["lib3mf_metadata_getnamespace"] = (void*)&lib3mf_metadata_getnamespace; + sProcAddressMap["lib3mf_metadata_setnamespace"] = (void*)&lib3mf_metadata_setnamespace; + sProcAddressMap["lib3mf_metadata_getname"] = (void*)&lib3mf_metadata_getname; + sProcAddressMap["lib3mf_metadata_setname"] = (void*)&lib3mf_metadata_setname; + sProcAddressMap["lib3mf_metadata_getkey"] = (void*)&lib3mf_metadata_getkey; + sProcAddressMap["lib3mf_metadata_getmustpreserve"] = (void*)&lib3mf_metadata_getmustpreserve; + sProcAddressMap["lib3mf_metadata_setmustpreserve"] = (void*)&lib3mf_metadata_setmustpreserve; + sProcAddressMap["lib3mf_metadata_gettype"] = (void*)&lib3mf_metadata_gettype; + sProcAddressMap["lib3mf_metadata_settype"] = (void*)&lib3mf_metadata_settype; + sProcAddressMap["lib3mf_metadata_getvalue"] = (void*)&lib3mf_metadata_getvalue; + sProcAddressMap["lib3mf_metadata_setvalue"] = (void*)&lib3mf_metadata_setvalue; + sProcAddressMap["lib3mf_metadatagroup_getmetadatacount"] = (void*)&lib3mf_metadatagroup_getmetadatacount; + sProcAddressMap["lib3mf_metadatagroup_getmetadata"] = (void*)&lib3mf_metadatagroup_getmetadata; + sProcAddressMap["lib3mf_metadatagroup_getmetadatabykey"] = (void*)&lib3mf_metadatagroup_getmetadatabykey; + sProcAddressMap["lib3mf_metadatagroup_removemetadatabyindex"] = (void*)&lib3mf_metadatagroup_removemetadatabyindex; + sProcAddressMap["lib3mf_metadatagroup_removemetadata"] = (void*)&lib3mf_metadatagroup_removemetadata; + sProcAddressMap["lib3mf_metadatagroup_addmetadata"] = (void*)&lib3mf_metadatagroup_addmetadata; + sProcAddressMap["lib3mf_object_gettype"] = (void*)&lib3mf_object_gettype; + sProcAddressMap["lib3mf_object_settype"] = (void*)&lib3mf_object_settype; + sProcAddressMap["lib3mf_object_getname"] = (void*)&lib3mf_object_getname; + sProcAddressMap["lib3mf_object_setname"] = (void*)&lib3mf_object_setname; + sProcAddressMap["lib3mf_object_getpartnumber"] = (void*)&lib3mf_object_getpartnumber; + sProcAddressMap["lib3mf_object_setpartnumber"] = (void*)&lib3mf_object_setpartnumber; + sProcAddressMap["lib3mf_object_ismeshobject"] = (void*)&lib3mf_object_ismeshobject; + sProcAddressMap["lib3mf_object_iscomponentsobject"] = (void*)&lib3mf_object_iscomponentsobject; + sProcAddressMap["lib3mf_object_isvalid"] = (void*)&lib3mf_object_isvalid; + sProcAddressMap["lib3mf_object_setattachmentasthumbnail"] = (void*)&lib3mf_object_setattachmentasthumbnail; + sProcAddressMap["lib3mf_object_getthumbnailattachment"] = (void*)&lib3mf_object_getthumbnailattachment; + sProcAddressMap["lib3mf_object_clearthumbnailattachment"] = (void*)&lib3mf_object_clearthumbnailattachment; + sProcAddressMap["lib3mf_object_getoutbox"] = (void*)&lib3mf_object_getoutbox; + sProcAddressMap["lib3mf_object_getuuid"] = (void*)&lib3mf_object_getuuid; + sProcAddressMap["lib3mf_object_setuuid"] = (void*)&lib3mf_object_setuuid; + sProcAddressMap["lib3mf_object_getmetadatagroup"] = (void*)&lib3mf_object_getmetadatagroup; + sProcAddressMap["lib3mf_object_setslicesmeshresolution"] = (void*)&lib3mf_object_setslicesmeshresolution; + sProcAddressMap["lib3mf_object_getslicesmeshresolution"] = (void*)&lib3mf_object_getslicesmeshresolution; + sProcAddressMap["lib3mf_object_hasslices"] = (void*)&lib3mf_object_hasslices; + sProcAddressMap["lib3mf_object_clearslicestack"] = (void*)&lib3mf_object_clearslicestack; + sProcAddressMap["lib3mf_object_getslicestack"] = (void*)&lib3mf_object_getslicestack; + sProcAddressMap["lib3mf_object_assignslicestack"] = (void*)&lib3mf_object_assignslicestack; + sProcAddressMap["lib3mf_meshobject_getvertexcount"] = (void*)&lib3mf_meshobject_getvertexcount; + sProcAddressMap["lib3mf_meshobject_gettrianglecount"] = (void*)&lib3mf_meshobject_gettrianglecount; + sProcAddressMap["lib3mf_meshobject_getvertex"] = (void*)&lib3mf_meshobject_getvertex; + sProcAddressMap["lib3mf_meshobject_setvertex"] = (void*)&lib3mf_meshobject_setvertex; + sProcAddressMap["lib3mf_meshobject_addvertex"] = (void*)&lib3mf_meshobject_addvertex; + sProcAddressMap["lib3mf_meshobject_getvertices"] = (void*)&lib3mf_meshobject_getvertices; + sProcAddressMap["lib3mf_meshobject_gettriangle"] = (void*)&lib3mf_meshobject_gettriangle; + sProcAddressMap["lib3mf_meshobject_settriangle"] = (void*)&lib3mf_meshobject_settriangle; + sProcAddressMap["lib3mf_meshobject_addtriangle"] = (void*)&lib3mf_meshobject_addtriangle; + sProcAddressMap["lib3mf_meshobject_gettriangleindices"] = (void*)&lib3mf_meshobject_gettriangleindices; + sProcAddressMap["lib3mf_meshobject_setobjectlevelproperty"] = (void*)&lib3mf_meshobject_setobjectlevelproperty; + sProcAddressMap["lib3mf_meshobject_getobjectlevelproperty"] = (void*)&lib3mf_meshobject_getobjectlevelproperty; + sProcAddressMap["lib3mf_meshobject_settriangleproperties"] = (void*)&lib3mf_meshobject_settriangleproperties; + sProcAddressMap["lib3mf_meshobject_gettriangleproperties"] = (void*)&lib3mf_meshobject_gettriangleproperties; + sProcAddressMap["lib3mf_meshobject_setalltriangleproperties"] = (void*)&lib3mf_meshobject_setalltriangleproperties; + sProcAddressMap["lib3mf_meshobject_getalltriangleproperties"] = (void*)&lib3mf_meshobject_getalltriangleproperties; + sProcAddressMap["lib3mf_meshobject_clearallproperties"] = (void*)&lib3mf_meshobject_clearallproperties; + sProcAddressMap["lib3mf_meshobject_setgeometry"] = (void*)&lib3mf_meshobject_setgeometry; + sProcAddressMap["lib3mf_meshobject_ismanifoldandoriented"] = (void*)&lib3mf_meshobject_ismanifoldandoriented; + sProcAddressMap["lib3mf_meshobject_beamlattice"] = (void*)&lib3mf_meshobject_beamlattice; + sProcAddressMap["lib3mf_beamlattice_getminlength"] = (void*)&lib3mf_beamlattice_getminlength; + sProcAddressMap["lib3mf_beamlattice_setminlength"] = (void*)&lib3mf_beamlattice_setminlength; + sProcAddressMap["lib3mf_beamlattice_getclipping"] = (void*)&lib3mf_beamlattice_getclipping; + sProcAddressMap["lib3mf_beamlattice_setclipping"] = (void*)&lib3mf_beamlattice_setclipping; + sProcAddressMap["lib3mf_beamlattice_getrepresentation"] = (void*)&lib3mf_beamlattice_getrepresentation; + sProcAddressMap["lib3mf_beamlattice_setrepresentation"] = (void*)&lib3mf_beamlattice_setrepresentation; + sProcAddressMap["lib3mf_beamlattice_getballoptions"] = (void*)&lib3mf_beamlattice_getballoptions; + sProcAddressMap["lib3mf_beamlattice_setballoptions"] = (void*)&lib3mf_beamlattice_setballoptions; + sProcAddressMap["lib3mf_beamlattice_getbeamcount"] = (void*)&lib3mf_beamlattice_getbeamcount; + sProcAddressMap["lib3mf_beamlattice_getbeam"] = (void*)&lib3mf_beamlattice_getbeam; + sProcAddressMap["lib3mf_beamlattice_addbeam"] = (void*)&lib3mf_beamlattice_addbeam; + sProcAddressMap["lib3mf_beamlattice_setbeam"] = (void*)&lib3mf_beamlattice_setbeam; + sProcAddressMap["lib3mf_beamlattice_setbeams"] = (void*)&lib3mf_beamlattice_setbeams; + sProcAddressMap["lib3mf_beamlattice_getbeams"] = (void*)&lib3mf_beamlattice_getbeams; + sProcAddressMap["lib3mf_beamlattice_getballcount"] = (void*)&lib3mf_beamlattice_getballcount; + sProcAddressMap["lib3mf_beamlattice_getball"] = (void*)&lib3mf_beamlattice_getball; + sProcAddressMap["lib3mf_beamlattice_addball"] = (void*)&lib3mf_beamlattice_addball; + sProcAddressMap["lib3mf_beamlattice_setball"] = (void*)&lib3mf_beamlattice_setball; + sProcAddressMap["lib3mf_beamlattice_setballs"] = (void*)&lib3mf_beamlattice_setballs; + sProcAddressMap["lib3mf_beamlattice_getballs"] = (void*)&lib3mf_beamlattice_getballs; + sProcAddressMap["lib3mf_beamlattice_getbeamsetcount"] = (void*)&lib3mf_beamlattice_getbeamsetcount; + sProcAddressMap["lib3mf_beamlattice_addbeamset"] = (void*)&lib3mf_beamlattice_addbeamset; + sProcAddressMap["lib3mf_beamlattice_getbeamset"] = (void*)&lib3mf_beamlattice_getbeamset; + sProcAddressMap["lib3mf_component_getobjectresource"] = (void*)&lib3mf_component_getobjectresource; + sProcAddressMap["lib3mf_component_getobjectresourceid"] = (void*)&lib3mf_component_getobjectresourceid; + sProcAddressMap["lib3mf_component_getuuid"] = (void*)&lib3mf_component_getuuid; + sProcAddressMap["lib3mf_component_setuuid"] = (void*)&lib3mf_component_setuuid; + sProcAddressMap["lib3mf_component_hastransform"] = (void*)&lib3mf_component_hastransform; + sProcAddressMap["lib3mf_component_gettransform"] = (void*)&lib3mf_component_gettransform; + sProcAddressMap["lib3mf_component_settransform"] = (void*)&lib3mf_component_settransform; + sProcAddressMap["lib3mf_componentsobject_addcomponent"] = (void*)&lib3mf_componentsobject_addcomponent; + sProcAddressMap["lib3mf_componentsobject_getcomponent"] = (void*)&lib3mf_componentsobject_getcomponent; + sProcAddressMap["lib3mf_componentsobject_getcomponentcount"] = (void*)&lib3mf_componentsobject_getcomponentcount; + sProcAddressMap["lib3mf_beamset_setname"] = (void*)&lib3mf_beamset_setname; + sProcAddressMap["lib3mf_beamset_getname"] = (void*)&lib3mf_beamset_getname; + sProcAddressMap["lib3mf_beamset_setidentifier"] = (void*)&lib3mf_beamset_setidentifier; + sProcAddressMap["lib3mf_beamset_getidentifier"] = (void*)&lib3mf_beamset_getidentifier; + sProcAddressMap["lib3mf_beamset_getreferencecount"] = (void*)&lib3mf_beamset_getreferencecount; + sProcAddressMap["lib3mf_beamset_setreferences"] = (void*)&lib3mf_beamset_setreferences; + sProcAddressMap["lib3mf_beamset_getreferences"] = (void*)&lib3mf_beamset_getreferences; + sProcAddressMap["lib3mf_beamset_getballreferencecount"] = (void*)&lib3mf_beamset_getballreferencecount; + sProcAddressMap["lib3mf_beamset_setballreferences"] = (void*)&lib3mf_beamset_setballreferences; + sProcAddressMap["lib3mf_beamset_getballreferences"] = (void*)&lib3mf_beamset_getballreferences; + sProcAddressMap["lib3mf_basematerialgroup_getcount"] = (void*)&lib3mf_basematerialgroup_getcount; + sProcAddressMap["lib3mf_basematerialgroup_getallpropertyids"] = (void*)&lib3mf_basematerialgroup_getallpropertyids; + sProcAddressMap["lib3mf_basematerialgroup_addmaterial"] = (void*)&lib3mf_basematerialgroup_addmaterial; + sProcAddressMap["lib3mf_basematerialgroup_removematerial"] = (void*)&lib3mf_basematerialgroup_removematerial; + sProcAddressMap["lib3mf_basematerialgroup_getname"] = (void*)&lib3mf_basematerialgroup_getname; + sProcAddressMap["lib3mf_basematerialgroup_setname"] = (void*)&lib3mf_basematerialgroup_setname; + sProcAddressMap["lib3mf_basematerialgroup_setdisplaycolor"] = (void*)&lib3mf_basematerialgroup_setdisplaycolor; + sProcAddressMap["lib3mf_basematerialgroup_getdisplaycolor"] = (void*)&lib3mf_basematerialgroup_getdisplaycolor; + sProcAddressMap["lib3mf_colorgroup_getcount"] = (void*)&lib3mf_colorgroup_getcount; + sProcAddressMap["lib3mf_colorgroup_getallpropertyids"] = (void*)&lib3mf_colorgroup_getallpropertyids; + sProcAddressMap["lib3mf_colorgroup_addcolor"] = (void*)&lib3mf_colorgroup_addcolor; + sProcAddressMap["lib3mf_colorgroup_removecolor"] = (void*)&lib3mf_colorgroup_removecolor; + sProcAddressMap["lib3mf_colorgroup_setcolor"] = (void*)&lib3mf_colorgroup_setcolor; + sProcAddressMap["lib3mf_colorgroup_getcolor"] = (void*)&lib3mf_colorgroup_getcolor; + sProcAddressMap["lib3mf_texture2dgroup_getcount"] = (void*)&lib3mf_texture2dgroup_getcount; + sProcAddressMap["lib3mf_texture2dgroup_getallpropertyids"] = (void*)&lib3mf_texture2dgroup_getallpropertyids; + sProcAddressMap["lib3mf_texture2dgroup_addtex2coord"] = (void*)&lib3mf_texture2dgroup_addtex2coord; + sProcAddressMap["lib3mf_texture2dgroup_gettex2coord"] = (void*)&lib3mf_texture2dgroup_gettex2coord; + sProcAddressMap["lib3mf_texture2dgroup_removetex2coord"] = (void*)&lib3mf_texture2dgroup_removetex2coord; + sProcAddressMap["lib3mf_texture2dgroup_gettexture2d"] = (void*)&lib3mf_texture2dgroup_gettexture2d; + sProcAddressMap["lib3mf_compositematerials_getcount"] = (void*)&lib3mf_compositematerials_getcount; + sProcAddressMap["lib3mf_compositematerials_getallpropertyids"] = (void*)&lib3mf_compositematerials_getallpropertyids; + sProcAddressMap["lib3mf_compositematerials_getbasematerialgroup"] = (void*)&lib3mf_compositematerials_getbasematerialgroup; + sProcAddressMap["lib3mf_compositematerials_addcomposite"] = (void*)&lib3mf_compositematerials_addcomposite; + sProcAddressMap["lib3mf_compositematerials_removecomposite"] = (void*)&lib3mf_compositematerials_removecomposite; + sProcAddressMap["lib3mf_compositematerials_getcomposite"] = (void*)&lib3mf_compositematerials_getcomposite; + sProcAddressMap["lib3mf_multipropertygroup_getcount"] = (void*)&lib3mf_multipropertygroup_getcount; + sProcAddressMap["lib3mf_multipropertygroup_getallpropertyids"] = (void*)&lib3mf_multipropertygroup_getallpropertyids; + sProcAddressMap["lib3mf_multipropertygroup_addmultiproperty"] = (void*)&lib3mf_multipropertygroup_addmultiproperty; + sProcAddressMap["lib3mf_multipropertygroup_setmultiproperty"] = (void*)&lib3mf_multipropertygroup_setmultiproperty; + sProcAddressMap["lib3mf_multipropertygroup_getmultiproperty"] = (void*)&lib3mf_multipropertygroup_getmultiproperty; + sProcAddressMap["lib3mf_multipropertygroup_removemultiproperty"] = (void*)&lib3mf_multipropertygroup_removemultiproperty; + sProcAddressMap["lib3mf_multipropertygroup_getlayercount"] = (void*)&lib3mf_multipropertygroup_getlayercount; + sProcAddressMap["lib3mf_multipropertygroup_addlayer"] = (void*)&lib3mf_multipropertygroup_addlayer; + sProcAddressMap["lib3mf_multipropertygroup_getlayer"] = (void*)&lib3mf_multipropertygroup_getlayer; + sProcAddressMap["lib3mf_multipropertygroup_removelayer"] = (void*)&lib3mf_multipropertygroup_removelayer; + sProcAddressMap["lib3mf_attachment_getpath"] = (void*)&lib3mf_attachment_getpath; + sProcAddressMap["lib3mf_attachment_setpath"] = (void*)&lib3mf_attachment_setpath; + sProcAddressMap["lib3mf_attachment_packagepart"] = (void*)&lib3mf_attachment_packagepart; + sProcAddressMap["lib3mf_attachment_getrelationshiptype"] = (void*)&lib3mf_attachment_getrelationshiptype; + sProcAddressMap["lib3mf_attachment_setrelationshiptype"] = (void*)&lib3mf_attachment_setrelationshiptype; + sProcAddressMap["lib3mf_attachment_writetofile"] = (void*)&lib3mf_attachment_writetofile; + sProcAddressMap["lib3mf_attachment_readfromfile"] = (void*)&lib3mf_attachment_readfromfile; + sProcAddressMap["lib3mf_attachment_readfromcallback"] = (void*)&lib3mf_attachment_readfromcallback; + sProcAddressMap["lib3mf_attachment_getstreamsize"] = (void*)&lib3mf_attachment_getstreamsize; + sProcAddressMap["lib3mf_attachment_writetobuffer"] = (void*)&lib3mf_attachment_writetobuffer; + sProcAddressMap["lib3mf_attachment_readfrombuffer"] = (void*)&lib3mf_attachment_readfrombuffer; + sProcAddressMap["lib3mf_texture2d_getattachment"] = (void*)&lib3mf_texture2d_getattachment; + sProcAddressMap["lib3mf_texture2d_setattachment"] = (void*)&lib3mf_texture2d_setattachment; + sProcAddressMap["lib3mf_texture2d_getcontenttype"] = (void*)&lib3mf_texture2d_getcontenttype; + sProcAddressMap["lib3mf_texture2d_setcontenttype"] = (void*)&lib3mf_texture2d_setcontenttype; + sProcAddressMap["lib3mf_texture2d_gettilestyleuv"] = (void*)&lib3mf_texture2d_gettilestyleuv; + sProcAddressMap["lib3mf_texture2d_settilestyleuv"] = (void*)&lib3mf_texture2d_settilestyleuv; + sProcAddressMap["lib3mf_texture2d_getfilter"] = (void*)&lib3mf_texture2d_getfilter; + sProcAddressMap["lib3mf_texture2d_setfilter"] = (void*)&lib3mf_texture2d_setfilter; + sProcAddressMap["lib3mf_builditem_getobjectresource"] = (void*)&lib3mf_builditem_getobjectresource; + sProcAddressMap["lib3mf_builditem_getuuid"] = (void*)&lib3mf_builditem_getuuid; + sProcAddressMap["lib3mf_builditem_setuuid"] = (void*)&lib3mf_builditem_setuuid; + sProcAddressMap["lib3mf_builditem_getobjectresourceid"] = (void*)&lib3mf_builditem_getobjectresourceid; + sProcAddressMap["lib3mf_builditem_hasobjecttransform"] = (void*)&lib3mf_builditem_hasobjecttransform; + sProcAddressMap["lib3mf_builditem_getobjecttransform"] = (void*)&lib3mf_builditem_getobjecttransform; + sProcAddressMap["lib3mf_builditem_setobjecttransform"] = (void*)&lib3mf_builditem_setobjecttransform; + sProcAddressMap["lib3mf_builditem_getpartnumber"] = (void*)&lib3mf_builditem_getpartnumber; + sProcAddressMap["lib3mf_builditem_setpartnumber"] = (void*)&lib3mf_builditem_setpartnumber; + sProcAddressMap["lib3mf_builditem_getmetadatagroup"] = (void*)&lib3mf_builditem_getmetadatagroup; + sProcAddressMap["lib3mf_builditem_getoutbox"] = (void*)&lib3mf_builditem_getoutbox; + sProcAddressMap["lib3mf_builditemiterator_movenext"] = (void*)&lib3mf_builditemiterator_movenext; + sProcAddressMap["lib3mf_builditemiterator_moveprevious"] = (void*)&lib3mf_builditemiterator_moveprevious; + sProcAddressMap["lib3mf_builditemiterator_getcurrent"] = (void*)&lib3mf_builditemiterator_getcurrent; + sProcAddressMap["lib3mf_builditemiterator_clone"] = (void*)&lib3mf_builditemiterator_clone; + sProcAddressMap["lib3mf_builditemiterator_count"] = (void*)&lib3mf_builditemiterator_count; + sProcAddressMap["lib3mf_slice_setvertices"] = (void*)&lib3mf_slice_setvertices; + sProcAddressMap["lib3mf_slice_getvertices"] = (void*)&lib3mf_slice_getvertices; + sProcAddressMap["lib3mf_slice_getvertexcount"] = (void*)&lib3mf_slice_getvertexcount; + sProcAddressMap["lib3mf_slice_addpolygon"] = (void*)&lib3mf_slice_addpolygon; + sProcAddressMap["lib3mf_slice_getpolygoncount"] = (void*)&lib3mf_slice_getpolygoncount; + sProcAddressMap["lib3mf_slice_setpolygonindices"] = (void*)&lib3mf_slice_setpolygonindices; + sProcAddressMap["lib3mf_slice_getpolygonindices"] = (void*)&lib3mf_slice_getpolygonindices; + sProcAddressMap["lib3mf_slice_getpolygonindexcount"] = (void*)&lib3mf_slice_getpolygonindexcount; + sProcAddressMap["lib3mf_slice_getztop"] = (void*)&lib3mf_slice_getztop; + sProcAddressMap["lib3mf_slicestack_getbottomz"] = (void*)&lib3mf_slicestack_getbottomz; + sProcAddressMap["lib3mf_slicestack_getslicecount"] = (void*)&lib3mf_slicestack_getslicecount; + sProcAddressMap["lib3mf_slicestack_getslice"] = (void*)&lib3mf_slicestack_getslice; + sProcAddressMap["lib3mf_slicestack_addslice"] = (void*)&lib3mf_slicestack_addslice; + sProcAddressMap["lib3mf_slicestack_getslicerefcount"] = (void*)&lib3mf_slicestack_getslicerefcount; + sProcAddressMap["lib3mf_slicestack_addslicestackreference"] = (void*)&lib3mf_slicestack_addslicestackreference; + sProcAddressMap["lib3mf_slicestack_getslicestackreference"] = (void*)&lib3mf_slicestack_getslicestackreference; + sProcAddressMap["lib3mf_slicestack_collapseslicereferences"] = (void*)&lib3mf_slicestack_collapseslicereferences; + sProcAddressMap["lib3mf_slicestack_setownpath"] = (void*)&lib3mf_slicestack_setownpath; + sProcAddressMap["lib3mf_slicestack_getownpath"] = (void*)&lib3mf_slicestack_getownpath; + sProcAddressMap["lib3mf_consumer_getconsumerid"] = (void*)&lib3mf_consumer_getconsumerid; + sProcAddressMap["lib3mf_consumer_getkeyid"] = (void*)&lib3mf_consumer_getkeyid; + sProcAddressMap["lib3mf_consumer_getkeyvalue"] = (void*)&lib3mf_consumer_getkeyvalue; + sProcAddressMap["lib3mf_accessright_getconsumer"] = (void*)&lib3mf_accessright_getconsumer; + sProcAddressMap["lib3mf_accessright_getwrappingalgorithm"] = (void*)&lib3mf_accessright_getwrappingalgorithm; + sProcAddressMap["lib3mf_accessright_getmgfalgorithm"] = (void*)&lib3mf_accessright_getmgfalgorithm; + sProcAddressMap["lib3mf_accessright_getdigestmethod"] = (void*)&lib3mf_accessright_getdigestmethod; + sProcAddressMap["lib3mf_contentencryptionparams_getencryptionalgorithm"] = (void*)&lib3mf_contentencryptionparams_getencryptionalgorithm; + sProcAddressMap["lib3mf_contentencryptionparams_getkey"] = (void*)&lib3mf_contentencryptionparams_getkey; + sProcAddressMap["lib3mf_contentencryptionparams_getinitializationvector"] = (void*)&lib3mf_contentencryptionparams_getinitializationvector; + sProcAddressMap["lib3mf_contentencryptionparams_getauthenticationtag"] = (void*)&lib3mf_contentencryptionparams_getauthenticationtag; + sProcAddressMap["lib3mf_contentencryptionparams_setauthenticationtag"] = (void*)&lib3mf_contentencryptionparams_setauthenticationtag; + sProcAddressMap["lib3mf_contentencryptionparams_getadditionalauthenticationdata"] = (void*)&lib3mf_contentencryptionparams_getadditionalauthenticationdata; + sProcAddressMap["lib3mf_contentencryptionparams_getdescriptor"] = (void*)&lib3mf_contentencryptionparams_getdescriptor; + sProcAddressMap["lib3mf_contentencryptionparams_getkeyuuid"] = (void*)&lib3mf_contentencryptionparams_getkeyuuid; + sProcAddressMap["lib3mf_resourcedata_getpath"] = (void*)&lib3mf_resourcedata_getpath; + sProcAddressMap["lib3mf_resourcedata_getencryptionalgorithm"] = (void*)&lib3mf_resourcedata_getencryptionalgorithm; + sProcAddressMap["lib3mf_resourcedata_getcompression"] = (void*)&lib3mf_resourcedata_getcompression; + sProcAddressMap["lib3mf_resourcedata_getadditionalauthenticationdata"] = (void*)&lib3mf_resourcedata_getadditionalauthenticationdata; + sProcAddressMap["lib3mf_resourcedatagroup_getkeyuuid"] = (void*)&lib3mf_resourcedatagroup_getkeyuuid; + sProcAddressMap["lib3mf_resourcedatagroup_addaccessright"] = (void*)&lib3mf_resourcedatagroup_addaccessright; + sProcAddressMap["lib3mf_resourcedatagroup_findaccessrightbyconsumer"] = (void*)&lib3mf_resourcedatagroup_findaccessrightbyconsumer; + sProcAddressMap["lib3mf_resourcedatagroup_removeaccessright"] = (void*)&lib3mf_resourcedatagroup_removeaccessright; + sProcAddressMap["lib3mf_keystore_addconsumer"] = (void*)&lib3mf_keystore_addconsumer; + sProcAddressMap["lib3mf_keystore_getconsumercount"] = (void*)&lib3mf_keystore_getconsumercount; + sProcAddressMap["lib3mf_keystore_getconsumer"] = (void*)&lib3mf_keystore_getconsumer; + sProcAddressMap["lib3mf_keystore_removeconsumer"] = (void*)&lib3mf_keystore_removeconsumer; + sProcAddressMap["lib3mf_keystore_findconsumer"] = (void*)&lib3mf_keystore_findconsumer; + sProcAddressMap["lib3mf_keystore_getresourcedatagroupcount"] = (void*)&lib3mf_keystore_getresourcedatagroupcount; + sProcAddressMap["lib3mf_keystore_addresourcedatagroup"] = (void*)&lib3mf_keystore_addresourcedatagroup; + sProcAddressMap["lib3mf_keystore_getresourcedatagroup"] = (void*)&lib3mf_keystore_getresourcedatagroup; + sProcAddressMap["lib3mf_keystore_removeresourcedatagroup"] = (void*)&lib3mf_keystore_removeresourcedatagroup; + sProcAddressMap["lib3mf_keystore_findresourcedatagroup"] = (void*)&lib3mf_keystore_findresourcedatagroup; + sProcAddressMap["lib3mf_keystore_addresourcedata"] = (void*)&lib3mf_keystore_addresourcedata; + sProcAddressMap["lib3mf_keystore_removeresourcedata"] = (void*)&lib3mf_keystore_removeresourcedata; + sProcAddressMap["lib3mf_keystore_findresourcedata"] = (void*)&lib3mf_keystore_findresourcedata; + sProcAddressMap["lib3mf_keystore_getresourcedatacount"] = (void*)&lib3mf_keystore_getresourcedatacount; + sProcAddressMap["lib3mf_keystore_getresourcedata"] = (void*)&lib3mf_keystore_getresourcedata; + sProcAddressMap["lib3mf_keystore_getuuid"] = (void*)&lib3mf_keystore_getuuid; + sProcAddressMap["lib3mf_keystore_setuuid"] = (void*)&lib3mf_keystore_setuuid; + sProcAddressMap["lib3mf_model_rootmodelpart"] = (void*)&lib3mf_model_rootmodelpart; + sProcAddressMap["lib3mf_model_findorcreatepackagepart"] = (void*)&lib3mf_model_findorcreatepackagepart; + sProcAddressMap["lib3mf_model_setunit"] = (void*)&lib3mf_model_setunit; + sProcAddressMap["lib3mf_model_getunit"] = (void*)&lib3mf_model_getunit; + sProcAddressMap["lib3mf_model_getlanguage"] = (void*)&lib3mf_model_getlanguage; + sProcAddressMap["lib3mf_model_setlanguage"] = (void*)&lib3mf_model_setlanguage; + sProcAddressMap["lib3mf_model_querywriter"] = (void*)&lib3mf_model_querywriter; + sProcAddressMap["lib3mf_model_queryreader"] = (void*)&lib3mf_model_queryreader; + sProcAddressMap["lib3mf_model_gettexture2dbyid"] = (void*)&lib3mf_model_gettexture2dbyid; + sProcAddressMap["lib3mf_model_getpropertytypebyid"] = (void*)&lib3mf_model_getpropertytypebyid; + sProcAddressMap["lib3mf_model_getbasematerialgroupbyid"] = (void*)&lib3mf_model_getbasematerialgroupbyid; + sProcAddressMap["lib3mf_model_gettexture2dgroupbyid"] = (void*)&lib3mf_model_gettexture2dgroupbyid; + sProcAddressMap["lib3mf_model_getcompositematerialsbyid"] = (void*)&lib3mf_model_getcompositematerialsbyid; + sProcAddressMap["lib3mf_model_getmultipropertygroupbyid"] = (void*)&lib3mf_model_getmultipropertygroupbyid; + sProcAddressMap["lib3mf_model_getmeshobjectbyid"] = (void*)&lib3mf_model_getmeshobjectbyid; + sProcAddressMap["lib3mf_model_getcomponentsobjectbyid"] = (void*)&lib3mf_model_getcomponentsobjectbyid; + sProcAddressMap["lib3mf_model_getcolorgroupbyid"] = (void*)&lib3mf_model_getcolorgroupbyid; + sProcAddressMap["lib3mf_model_getslicestackbyid"] = (void*)&lib3mf_model_getslicestackbyid; + sProcAddressMap["lib3mf_model_getbuilduuid"] = (void*)&lib3mf_model_getbuilduuid; + sProcAddressMap["lib3mf_model_setbuilduuid"] = (void*)&lib3mf_model_setbuilduuid; + sProcAddressMap["lib3mf_model_getbuilditems"] = (void*)&lib3mf_model_getbuilditems; + sProcAddressMap["lib3mf_model_getoutbox"] = (void*)&lib3mf_model_getoutbox; + sProcAddressMap["lib3mf_model_getresources"] = (void*)&lib3mf_model_getresources; + sProcAddressMap["lib3mf_model_getobjects"] = (void*)&lib3mf_model_getobjects; + sProcAddressMap["lib3mf_model_getmeshobjects"] = (void*)&lib3mf_model_getmeshobjects; + sProcAddressMap["lib3mf_model_getcomponentsobjects"] = (void*)&lib3mf_model_getcomponentsobjects; + sProcAddressMap["lib3mf_model_gettexture2ds"] = (void*)&lib3mf_model_gettexture2ds; + sProcAddressMap["lib3mf_model_getbasematerialgroups"] = (void*)&lib3mf_model_getbasematerialgroups; + sProcAddressMap["lib3mf_model_getcolorgroups"] = (void*)&lib3mf_model_getcolorgroups; + sProcAddressMap["lib3mf_model_gettexture2dgroups"] = (void*)&lib3mf_model_gettexture2dgroups; + sProcAddressMap["lib3mf_model_getcompositematerials"] = (void*)&lib3mf_model_getcompositematerials; + sProcAddressMap["lib3mf_model_getmultipropertygroups"] = (void*)&lib3mf_model_getmultipropertygroups; + sProcAddressMap["lib3mf_model_getslicestacks"] = (void*)&lib3mf_model_getslicestacks; + sProcAddressMap["lib3mf_model_mergetomodel"] = (void*)&lib3mf_model_mergetomodel; + sProcAddressMap["lib3mf_model_addmeshobject"] = (void*)&lib3mf_model_addmeshobject; + sProcAddressMap["lib3mf_model_addcomponentsobject"] = (void*)&lib3mf_model_addcomponentsobject; + sProcAddressMap["lib3mf_model_addslicestack"] = (void*)&lib3mf_model_addslicestack; + sProcAddressMap["lib3mf_model_addtexture2dfromattachment"] = (void*)&lib3mf_model_addtexture2dfromattachment; + sProcAddressMap["lib3mf_model_addbasematerialgroup"] = (void*)&lib3mf_model_addbasematerialgroup; + sProcAddressMap["lib3mf_model_addcolorgroup"] = (void*)&lib3mf_model_addcolorgroup; + sProcAddressMap["lib3mf_model_addtexture2dgroup"] = (void*)&lib3mf_model_addtexture2dgroup; + sProcAddressMap["lib3mf_model_addcompositematerials"] = (void*)&lib3mf_model_addcompositematerials; + sProcAddressMap["lib3mf_model_addmultipropertygroup"] = (void*)&lib3mf_model_addmultipropertygroup; + sProcAddressMap["lib3mf_model_addbuilditem"] = (void*)&lib3mf_model_addbuilditem; + sProcAddressMap["lib3mf_model_removebuilditem"] = (void*)&lib3mf_model_removebuilditem; + sProcAddressMap["lib3mf_model_getmetadatagroup"] = (void*)&lib3mf_model_getmetadatagroup; + sProcAddressMap["lib3mf_model_addattachment"] = (void*)&lib3mf_model_addattachment; + sProcAddressMap["lib3mf_model_removeattachment"] = (void*)&lib3mf_model_removeattachment; + sProcAddressMap["lib3mf_model_getattachment"] = (void*)&lib3mf_model_getattachment; + sProcAddressMap["lib3mf_model_findattachment"] = (void*)&lib3mf_model_findattachment; + sProcAddressMap["lib3mf_model_getattachmentcount"] = (void*)&lib3mf_model_getattachmentcount; + sProcAddressMap["lib3mf_model_haspackagethumbnailattachment"] = (void*)&lib3mf_model_haspackagethumbnailattachment; + sProcAddressMap["lib3mf_model_createpackagethumbnailattachment"] = (void*)&lib3mf_model_createpackagethumbnailattachment; + sProcAddressMap["lib3mf_model_getpackagethumbnailattachment"] = (void*)&lib3mf_model_getpackagethumbnailattachment; + sProcAddressMap["lib3mf_model_removepackagethumbnailattachment"] = (void*)&lib3mf_model_removepackagethumbnailattachment; + sProcAddressMap["lib3mf_model_addcustomcontenttype"] = (void*)&lib3mf_model_addcustomcontenttype; + sProcAddressMap["lib3mf_model_removecustomcontenttype"] = (void*)&lib3mf_model_removecustomcontenttype; + sProcAddressMap["lib3mf_model_setrandomnumbercallback"] = (void*)&lib3mf_model_setrandomnumbercallback; + sProcAddressMap["lib3mf_model_getkeystore"] = (void*)&lib3mf_model_getkeystore; + sProcAddressMap["lib3mf_getlibraryversion"] = (void*)&lib3mf_getlibraryversion; + sProcAddressMap["lib3mf_getprereleaseinformation"] = (void*)&lib3mf_getprereleaseinformation; + sProcAddressMap["lib3mf_getbuildinformation"] = (void*)&lib3mf_getbuildinformation; + sProcAddressMap["lib3mf_getspecificationversion"] = (void*)&lib3mf_getspecificationversion; + sProcAddressMap["lib3mf_createmodel"] = (void*)&lib3mf_createmodel; + sProcAddressMap["lib3mf_release"] = (void*)&lib3mf_release; + sProcAddressMap["lib3mf_acquire"] = (void*)&lib3mf_acquire; + sProcAddressMap["lib3mf_setjournal"] = (void*)&lib3mf_setjournal; + sProcAddressMap["lib3mf_getlasterror"] = (void*)&lib3mf_getlasterror; + sProcAddressMap["lib3mf_getsymbollookupmethod"] = (void*)&lib3mf_getsymbollookupmethod; + sProcAddressMap["lib3mf_retrieveprogressmessage"] = (void*)&lib3mf_retrieveprogressmessage; + sProcAddressMap["lib3mf_rgbatocolor"] = (void*)&lib3mf_rgbatocolor; + sProcAddressMap["lib3mf_floatrgbatocolor"] = (void*)&lib3mf_floatrgbatocolor; + sProcAddressMap["lib3mf_colortorgba"] = (void*)&lib3mf_colortorgba; + sProcAddressMap["lib3mf_colortofloatrgba"] = (void*)&lib3mf_colortofloatrgba; + sProcAddressMap["lib3mf_getidentitytransform"] = (void*)&lib3mf_getidentitytransform; + sProcAddressMap["lib3mf_getuniformscaletransform"] = (void*)&lib3mf_getuniformscaletransform; + sProcAddressMap["lib3mf_getscaletransform"] = (void*)&lib3mf_getscaletransform; + sProcAddressMap["lib3mf_gettranslationtransform"] = (void*)&lib3mf_gettranslationtransform; + + sbProcAddressMapHasBeenInitialized = true; + } + if (pProcName == nullptr) + return LIB3MF_ERROR_INVALIDPARAM; + if (ppProcAddress == nullptr) + return LIB3MF_ERROR_INVALIDPARAM; + *ppProcAddress = nullptr; + std::string sProcName (pProcName); + + auto procPair = sProcAddressMap.find(sProcName); + if (procPair == sProcAddressMap.end()) { + return LIB3MF_ERROR_COULDNOTFINDLIBRARYEXPORT; + } + else { + *ppProcAddress = procPair->second; + return LIB3MF_SUCCESS; + } + +} + +/************************************************************************************************************************* + Global functions implementation +**************************************************************************************************************************/ +Lib3MFResult lib3mf_getlibraryversion(Lib3MF_uint32 * pMajor, Lib3MF_uint32 * pMinor, Lib3MF_uint32 * pMicro) +{ + IBase* pIBaseClass = nullptr; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginStaticFunction("GetLibraryVersion"); + } + if (!pMajor) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (!pMinor) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (!pMicro) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + CWrapper::GetLibraryVersion(*pMajor, *pMinor, *pMicro); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt32Result("Major", *pMajor); + pJournalEntry->addUInt32Result("Minor", *pMinor); + pJournalEntry->addUInt32Result("Micro", *pMicro); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_getprereleaseinformation(bool * pHasPrereleaseInfo, const Lib3MF_uint32 nPrereleaseInfoBufferSize, Lib3MF_uint32* pPrereleaseInfoNeededChars, char * pPrereleaseInfoBuffer) +{ + IBase* pIBaseClass = nullptr; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginStaticFunction("GetPrereleaseInformation"); + } + if (pHasPrereleaseInfo == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if ( (!pPrereleaseInfoBuffer) && !(pPrereleaseInfoNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sPrereleaseInfo(""); + *pHasPrereleaseInfo = CWrapper::GetPrereleaseInformation(sPrereleaseInfo); + + if (pPrereleaseInfoNeededChars) + *pPrereleaseInfoNeededChars = (Lib3MF_uint32) (sPrereleaseInfo.size()+1); + if (pPrereleaseInfoBuffer) { + if (sPrereleaseInfo.size() >= nPrereleaseInfoBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iPrereleaseInfo = 0; iPrereleaseInfo < sPrereleaseInfo.size(); iPrereleaseInfo++) + pPrereleaseInfoBuffer[iPrereleaseInfo] = sPrereleaseInfo[iPrereleaseInfo]; + pPrereleaseInfoBuffer[sPrereleaseInfo.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addBooleanResult("HasPrereleaseInfo", *pHasPrereleaseInfo); + pJournalEntry->addStringResult("PrereleaseInfo", sPrereleaseInfo.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_getbuildinformation(bool * pHasBuildInfo, const Lib3MF_uint32 nBuildInformationBufferSize, Lib3MF_uint32* pBuildInformationNeededChars, char * pBuildInformationBuffer) +{ + IBase* pIBaseClass = nullptr; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginStaticFunction("GetBuildInformation"); + } + if (pHasBuildInfo == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if ( (!pBuildInformationBuffer) && !(pBuildInformationNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sBuildInformation(""); + *pHasBuildInfo = CWrapper::GetBuildInformation(sBuildInformation); + + if (pBuildInformationNeededChars) + *pBuildInformationNeededChars = (Lib3MF_uint32) (sBuildInformation.size()+1); + if (pBuildInformationBuffer) { + if (sBuildInformation.size() >= nBuildInformationBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iBuildInformation = 0; iBuildInformation < sBuildInformation.size(); iBuildInformation++) + pBuildInformationBuffer[iBuildInformation] = sBuildInformation[iBuildInformation]; + pBuildInformationBuffer[sBuildInformation.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addBooleanResult("HasBuildInfo", *pHasBuildInfo); + pJournalEntry->addStringResult("BuildInformation", sBuildInformation.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_getspecificationversion(const char * pSpecificationURL, bool * pIsSupported, Lib3MF_uint32 * pMajor, Lib3MF_uint32 * pMinor, Lib3MF_uint32 * pMicro) +{ + IBase* pIBaseClass = nullptr; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginStaticFunction("GetSpecificationVersion"); + pJournalEntry->addStringParameter("SpecificationURL", pSpecificationURL); + } + if (pSpecificationURL == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (!pIsSupported) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (!pMajor) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (!pMinor) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (!pMicro) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sSpecificationURL(pSpecificationURL); + CWrapper::GetSpecificationVersion(sSpecificationURL, *pIsSupported, *pMajor, *pMinor, *pMicro); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addBooleanResult("IsSupported", *pIsSupported); + pJournalEntry->addUInt32Result("Major", *pMajor); + pJournalEntry->addUInt32Result("Minor", *pMinor); + pJournalEntry->addUInt32Result("Micro", *pMicro); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_createmodel(Lib3MF_Model * pModel) +{ + IBase* pIBaseClass = nullptr; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginStaticFunction("CreateModel"); + } + if (pModel == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pBaseModel(nullptr); + pBaseModel = CWrapper::CreateModel(); + + *pModel = (IBase*)(pBaseModel); + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addHandleResult("Model", *pModel); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_release(Lib3MF_Base pInstance) +{ + IBase* pIBaseClass = nullptr; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginStaticFunction("Release"); + pJournalEntry->addHandleParameter("Instance", pInstance); + } + IBase* pIBaseClassInstance = (IBase *)pInstance; + IBase* pIInstance = dynamic_cast(pIBaseClassInstance); + if (!pIInstance) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDCAST); + + CWrapper::Release(pIInstance); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_acquire(Lib3MF_Base pInstance) +{ + IBase* pIBaseClass = nullptr; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginStaticFunction("Acquire"); + pJournalEntry->addHandleParameter("Instance", pInstance); + } + IBase* pIBaseClassInstance = (IBase *)pInstance; + IBase* pIInstance = dynamic_cast(pIBaseClassInstance); + if (!pIInstance) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDCAST); + + CWrapper::Acquire(pIInstance); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_setjournal(const char * pJournalPath) +{ + IBase* pIBaseClass = nullptr; + + try { + if (pJournalPath == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sJournalPath(pJournalPath); + m_GlobalJournal = nullptr; + if (sJournalPath != "") { + m_GlobalJournal = std::make_shared (sJournalPath); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException); + } + catch (...) { + return handleUnhandledException(pIBaseClass); + } +} + +Lib3MFResult lib3mf_getlasterror(Lib3MF_Base pInstance, const Lib3MF_uint32 nLastErrorStringBufferSize, Lib3MF_uint32* pLastErrorStringNeededChars, char * pLastErrorStringBuffer, bool * pHasLastError) +{ + IBase* pIBaseClass = nullptr; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginStaticFunction("GetLastError"); + pJournalEntry->addHandleParameter("Instance", pInstance); + } + if ( (!pLastErrorStringBuffer) && !(pLastErrorStringNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (pHasLastError == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + IBase* pIBaseClassInstance = (IBase *)pInstance; + IBase* pIInstance = dynamic_cast(pIBaseClassInstance); + if (!pIInstance) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDCAST); + + std::string sLastErrorString(""); + *pHasLastError = CWrapper::GetLastError(pIInstance, sLastErrorString); + + if (pLastErrorStringNeededChars) + *pLastErrorStringNeededChars = (Lib3MF_uint32) (sLastErrorString.size()+1); + if (pLastErrorStringBuffer) { + if (sLastErrorString.size() >= nLastErrorStringBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iLastErrorString = 0; iLastErrorString < sLastErrorString.size(); iLastErrorString++) + pLastErrorStringBuffer[iLastErrorString] = sLastErrorString[iLastErrorString]; + pLastErrorStringBuffer[sLastErrorString.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addStringResult("LastErrorString", sLastErrorString.c_str()); + pJournalEntry->addBooleanResult("HasLastError", *pHasLastError); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_getsymbollookupmethod(Lib3MF_pvoid * pSymbolLookupMethod) +{ + IBase* pIBaseClass = nullptr; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginStaticFunction("GetSymbolLookupMethod"); + } + if (pSymbolLookupMethod == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + *pSymbolLookupMethod = (void*)&_lib3mf_getprocaddress_internal; + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addPointerResult("SymbolLookupMethod", *pSymbolLookupMethod); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_retrieveprogressmessage(eLib3MFProgressIdentifier eTheProgressIdentifier, const Lib3MF_uint32 nProgressMessageBufferSize, Lib3MF_uint32* pProgressMessageNeededChars, char * pProgressMessageBuffer) +{ + IBase* pIBaseClass = nullptr; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginStaticFunction("RetrieveProgressMessage"); + pJournalEntry->addEnumParameter("TheProgressIdentifier", "ProgressIdentifier", (Lib3MF_int32)(eTheProgressIdentifier)); + } + if ( (!pProgressMessageBuffer) && !(pProgressMessageNeededChars) ) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + std::string sProgressMessage(""); + CWrapper::RetrieveProgressMessage(eTheProgressIdentifier, sProgressMessage); + + if (pProgressMessageNeededChars) + *pProgressMessageNeededChars = (Lib3MF_uint32) (sProgressMessage.size()+1); + if (pProgressMessageBuffer) { + if (sProgressMessage.size() >= nProgressMessageBufferSize) + throw ELib3MFInterfaceException (LIB3MF_ERROR_BUFFERTOOSMALL); + for (size_t iProgressMessage = 0; iProgressMessage < sProgressMessage.size(); iProgressMessage++) + pProgressMessageBuffer[iProgressMessage] = sProgressMessage[iProgressMessage]; + pProgressMessageBuffer[sProgressMessage.size()] = 0; + } + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addStringResult("ProgressMessage", sProgressMessage.c_str()); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_rgbatocolor(Lib3MF_uint8 nRed, Lib3MF_uint8 nGreen, Lib3MF_uint8 nBlue, Lib3MF_uint8 nAlpha, sLib3MFColor * pTheColor) +{ + IBase* pIBaseClass = nullptr; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginStaticFunction("RGBAToColor"); + pJournalEntry->addUInt8Parameter("Red", nRed); + pJournalEntry->addUInt8Parameter("Green", nGreen); + pJournalEntry->addUInt8Parameter("Blue", nBlue); + pJournalEntry->addUInt8Parameter("Alpha", nAlpha); + } + if (pTheColor == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + *pTheColor = CWrapper::RGBAToColor(nRed, nGreen, nBlue, nAlpha); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_floatrgbatocolor(Lib3MF_single fRed, Lib3MF_single fGreen, Lib3MF_single fBlue, Lib3MF_single fAlpha, sLib3MFColor * pTheColor) +{ + IBase* pIBaseClass = nullptr; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginStaticFunction("FloatRGBAToColor"); + pJournalEntry->addSingleParameter("Red", fRed); + pJournalEntry->addSingleParameter("Green", fGreen); + pJournalEntry->addSingleParameter("Blue", fBlue); + pJournalEntry->addSingleParameter("Alpha", fAlpha); + } + if (pTheColor == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + *pTheColor = CWrapper::FloatRGBAToColor(fRed, fGreen, fBlue, fAlpha); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_colortorgba(const sLib3MFColor * pTheColor, Lib3MF_uint8 * pRed, Lib3MF_uint8 * pGreen, Lib3MF_uint8 * pBlue, Lib3MF_uint8 * pAlpha) +{ + IBase* pIBaseClass = nullptr; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginStaticFunction("ColorToRGBA"); + } + if (!pRed) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (!pGreen) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (!pBlue) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (!pAlpha) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + CWrapper::ColorToRGBA(*pTheColor, *pRed, *pGreen, *pBlue, *pAlpha); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addUInt8Result("Red", *pRed); + pJournalEntry->addUInt8Result("Green", *pGreen); + pJournalEntry->addUInt8Result("Blue", *pBlue); + pJournalEntry->addUInt8Result("Alpha", *pAlpha); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_colortofloatrgba(const sLib3MFColor * pTheColor, Lib3MF_single * pRed, Lib3MF_single * pGreen, Lib3MF_single * pBlue, Lib3MF_single * pAlpha) +{ + IBase* pIBaseClass = nullptr; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginStaticFunction("ColorToFloatRGBA"); + } + if (!pRed) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (!pGreen) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (!pBlue) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + if (!pAlpha) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + CWrapper::ColorToFloatRGBA(*pTheColor, *pRed, *pGreen, *pBlue, *pAlpha); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->addSingleResult("Red", *pRed); + pJournalEntry->addSingleResult("Green", *pGreen); + pJournalEntry->addSingleResult("Blue", *pBlue); + pJournalEntry->addSingleResult("Alpha", *pAlpha); + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_getidentitytransform(sLib3MFTransform * pTransform) +{ + IBase* pIBaseClass = nullptr; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginStaticFunction("GetIdentityTransform"); + } + if (pTransform == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + *pTransform = CWrapper::GetIdentityTransform(); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_getuniformscaletransform(Lib3MF_single fFactor, sLib3MFTransform * pTransform) +{ + IBase* pIBaseClass = nullptr; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginStaticFunction("GetUniformScaleTransform"); + pJournalEntry->addSingleParameter("Factor", fFactor); + } + if (pTransform == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + *pTransform = CWrapper::GetUniformScaleTransform(fFactor); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_getscaletransform(Lib3MF_single fFactorX, Lib3MF_single fFactorY, Lib3MF_single fFactorZ, sLib3MFTransform * pTransform) +{ + IBase* pIBaseClass = nullptr; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginStaticFunction("GetScaleTransform"); + pJournalEntry->addSingleParameter("FactorX", fFactorX); + pJournalEntry->addSingleParameter("FactorY", fFactorY); + pJournalEntry->addSingleParameter("FactorZ", fFactorZ); + } + if (pTransform == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + *pTransform = CWrapper::GetScaleTransform(fFactorX, fFactorY, fFactorZ); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + +Lib3MFResult lib3mf_gettranslationtransform(Lib3MF_single fVectorX, Lib3MF_single fVectorY, Lib3MF_single fVectorZ, sLib3MFTransform * pTransform) +{ + IBase* pIBaseClass = nullptr; + + PLib3MFInterfaceJournalEntry pJournalEntry; + try { + if (m_GlobalJournal.get() != nullptr) { + pJournalEntry = m_GlobalJournal->beginStaticFunction("GetTranslationTransform"); + pJournalEntry->addSingleParameter("VectorX", fVectorX); + pJournalEntry->addSingleParameter("VectorY", fVectorY); + pJournalEntry->addSingleParameter("VectorZ", fVectorZ); + } + if (pTransform == nullptr) + throw ELib3MFInterfaceException (LIB3MF_ERROR_INVALIDPARAM); + *pTransform = CWrapper::GetTranslationTransform(fVectorX, fVectorY, fVectorZ); + + if (pJournalEntry.get() != nullptr) { + pJournalEntry->writeSuccess(); + } + return LIB3MF_SUCCESS; + } + catch (ELib3MFInterfaceException & Exception) { + return handleLib3MFException(pIBaseClass, Exception, pJournalEntry.get()); + } + catch (std::exception & StdException) { + return handleStdException(pIBaseClass, StdException, pJournalEntry.get()); + } + catch (...) { + return handleUnhandledException(pIBaseClass, pJournalEntry.get()); + } +} + + diff --git a/resource2.h b/resource2.h new file mode 100644 index 0000000..0aa0c3c --- /dev/null +++ b/resource2.h @@ -0,0 +1,15 @@ +//{{NO_DEPENDENCIES}} +// File di inclusione generato con Microsoft Visual C++. +// Utilizzato da Resource.rc +// + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 105 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif