summaryrefslogtreecommitdiff
path: root/avmedia/source/framework/modeltools.cxx
blob: 66a95b31e9d29b5d54c006fe1b017650a56d23c9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <avmedia/modeltools.hxx>
#include <avmedia/mediaitem.hxx>
#include "mediamisc.hxx"

#include <com/sun/star/embed/ElementModes.hpp>
#include <com/sun/star/embed/XTransactedObject.hpp>
#include <com/sun/star/document/XStorageBasedDocument.hpp>
#include <com/sun/star/embed/XStorage.hpp>
#include <osl/file.hxx>
#include <comphelper/processfactory.hxx>
#include <tools/urlobj.hxx>
#include <ucbhelper/content.hxx>
#include <unotools/localfilehelper.hxx>
#include <unotools/tempfile.hxx>

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>
#include <boost/optional.hpp>

#ifdef ENABLE_COLLADA2GLTF
#include <COLLADA2GLTFWriter.h>
#include <GLTFAsset.h>
#include <KMZ2Collada.h>
#endif

#include <string>
#include <vector>

using namespace ::com::sun::star;
using namespace boost::property_tree;

namespace avmedia {

static void lcl_EmbedExternals(const OUString& rSourceURL, uno::Reference<embed::XStorage> xSubStorage, ::ucbhelper::Content& rContent)
{
    // Create a temp file with which json parser can work.
    OUString sTempFileURL;
    const ::osl::FileBase::RC  aErr =
        ::osl::FileBase::createTempFile(0, 0, &sTempFileURL);
    if (::osl::FileBase::E_None != aErr)
    {
        SAL_WARN("avmedia.opengl", "Cannot create temp file");
        return;
    }
    try
    {
        // Write json content to the temp file
        ::ucbhelper::Content aTempContent(sTempFileURL,
            uno::Reference<ucb::XCommandEnvironment>(),
            comphelper::getProcessComponentContext());
        aTempContent.writeStream(rContent.openStream(), true);
    }
    catch (uno::Exception const& e)
    {
        SAL_WARN("avmedia.opengl", "Exception: '" << e.Message << "'");
        return;
    }

    // Convert URL to a file path for loading
    const INetURLObject aURLObj(sTempFileURL);
    std::string sUrl = OUStringToOString( aURLObj.getFSysPath(INetURLObject::FSYS_DETECT), RTL_TEXTENCODING_UTF8 ).getStr();

    // Parse json, read externals' URI and modify this relative URI's so they remain valid in the new context.
    std::vector<std::string> vExternals;
    ptree aTree;
    try
    {
        json_parser::read_json( sUrl, aTree );

        // Buffers for geometry and animations
        BOOST_FOREACH(ptree::value_type &rVal,aTree.get_child("buffers"))
        {
            const std::string sBufferUri(rVal.second.get<std::string>("path"));
            vExternals.push_back(sBufferUri);
            // Change path: make it contain only a file name
            aTree.put("buffers." + rVal.first + ".path.",sBufferUri.substr(sBufferUri.find_last_of('/')+1));
        }
        // Images for textures
        boost::optional< ptree& > aImages = aTree.get_child_optional("images");
        if( aImages )
        {
            BOOST_FOREACH(ptree::value_type &rVal,aImages.get())
            {
                const std::string sImageUri(rVal.second.get<std::string>("path"));
                if( !sImageUri.empty() )
                {
                    vExternals.push_back(sImageUri);
                    // Change path: make it contain only a file name
                    aTree.put("images." + rVal.first + ".path.",sImageUri.substr(sImageUri.find_last_of('/')+1));
                }
            }
        }
        // Shaders (contains names only)
        BOOST_FOREACH(ptree::value_type &rVal,aTree.get_child("programs"))
        {
            vExternals.push_back(rVal.second.get<std::string>("fragmentShader") + ".glsl");
            vExternals.push_back(rVal.second.get<std::string>("vertexShader") + ".glsl");
        }

        // Write out modified json
        json_parser::write_json( sUrl, aTree );
    }
    catch ( boost::exception const& )
    {
        SAL_WARN("avmedia.opengl", "Exception while parsing *.json file");
        return;
    }

    // Reload json with modified path to external resources
    rContent = ::ucbhelper::Content(sTempFileURL,
        uno::Reference<ucb::XCommandEnvironment>(),
        comphelper::getProcessComponentContext());

    // Store all external files next to the json file
    for( std::vector<std::string>::iterator aCIter = vExternals.begin(); aCIter != vExternals.end(); ++aCIter )
    {
        const OUString sAbsURL = INetURLObject::GetAbsURL(rSourceURL,OUString::createFromAscii(aCIter->c_str()));

        ::ucbhelper::Content aContent(sAbsURL,
                uno::Reference<ucb::XCommandEnvironment>(),
                comphelper::getProcessComponentContext());

        uno::Reference<io::XStream> const xStream(
            CreateStream(xSubStorage, GetFilename(sAbsURL)), uno::UNO_SET_THROW);
        uno::Reference<io::XOutputStream> const xOutStream(
            xStream->getOutputStream(), uno::UNO_SET_THROW);

        if (!aContent.openStream(xOutStream))
        {
            SAL_WARN("avmedia.opengl", "openStream to storage failed");
            return;
        }
    }
}

bool Embed3DModel( const uno::Reference<frame::XModel>& xModel,
        const OUString& rSourceURL, OUString& o_rEmbeddedURL)
{
    OUString sSource = rSourceURL;
#ifdef ENABLE_COLLADA2GLTF
    if (rSourceURL.endsWith(".dae") || rSourceURL.endsWith(".kmz"))
    {
        OUString sName;
        ::utl::LocalFileHelper::ConvertPhysicalNameToURL(::utl::TempFile::CreateTempName(), sName);
        // remove .tmp extension
        sName = sName.copy(0, sName.getLength() - 4);
        const INetURLObject aSourceURLObj(rSourceURL);
        std::string sSourcePath = OUStringToOString( aSourceURLObj.getFSysPath(INetURLObject::FSYS_DETECT), RTL_TEXTENCODING_UTF8 ).getStr();

        std::shared_ptr <GLTF::GLTFAsset> asset(new GLTF::GLTFAsset());
        asset->setInputFilePath(sSourcePath);

        if (rSourceURL.endsWith(".kmz"))
        {
            std::string strDaeFilePath = GLTF::Kmz2Collada()(asset->getInputFilePath());
            if (strDaeFilePath == "")
                return false;
            asset->setInputFilePath(strDaeFilePath);
        }
        asset->setBundleOutputPath(OUStringToOString( sName, RTL_TEXTENCODING_UTF8 ).getStr());
        GLTF::COLLADA2GLTFWriter writer(asset);
        writer.write();
        // Path to the .json file created by COLLADA2GLTFWriter
        sSource = sName + "/" + GetFilename(sName) + ".json";
    }
#endif

    try
    {
        ::ucbhelper::Content aSourceContent(sSource,
                uno::Reference<ucb::XCommandEnvironment>(),
                comphelper::getProcessComponentContext());

        // Base storage
        uno::Reference<document::XStorageBasedDocument> const xSBD(xModel,
                uno::UNO_QUERY_THROW);
        uno::Reference<embed::XStorage> const xStorage(
                xSBD->getDocumentStorage(), uno::UNO_QUERY_THROW);

        // Model storage
        const OUString sModel("Model");
        uno::Reference<embed::XStorage> const xModelStorage(
            xStorage->openStorageElement(sModel, embed::ElementModes::WRITE));

        // Own storage of the corresponding model
        const OUString sFilename(GetFilename(sSource));
        const OUString sGLTFDir(sFilename.copy(0,sFilename.lastIndexOf('.')));
        uno::Reference<embed::XStorage> const xSubStorage(
            xModelStorage->openStorageElement(sGLTFDir, embed::ElementModes::WRITE));

        // Embed external resources
        lcl_EmbedExternals(sSource, xSubStorage, aSourceContent);

        // Save model file (.json)
        uno::Reference<io::XStream> const xStream(
            CreateStream(xSubStorage, sFilename), uno::UNO_SET_THROW);
        uno::Reference<io::XOutputStream> const xOutStream(
            xStream->getOutputStream(), uno::UNO_SET_THROW);

        if (!aSourceContent.openStream(xOutStream))
        {
            SAL_WARN("avmedia.opengl", "openStream to storage failed");
            return false;
        }

        const uno::Reference<embed::XTransactedObject> xSubTransaction(xSubStorage, uno::UNO_QUERY);
        if (xSubTransaction.is())
        {
            xSubTransaction->commit();
        }
        const uno::Reference<embed::XTransactedObject> xModelTransaction(xModelStorage, uno::UNO_QUERY);
        if (xModelTransaction.is())
        {
            xModelTransaction->commit();
        }
        const uno::Reference<embed::XTransactedObject> xTransaction(xStorage, uno::UNO_QUERY);
        if (xTransaction.is())
        {
            xTransaction->commit();
        }

        o_rEmbeddedURL = "vnd.sun.star.Package:" + sModel + "/" + sGLTFDir + "/" + sFilename;
        return true;
    }
    catch (uno::Exception const&)
    {
        SAL_WARN("avmedia.opengl", "Exception while trying to embed model");
    }
    return false;
}

bool IsModel(const OUString& rMimeType)
{
    return rMimeType == AVMEDIA_MIMETYPE_JSON;
}

} // namespace avemdia

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */