<commit_before>/*
 * Copyright (C) 2015 by Emmanuel Pescosta <emmanuelpescosta099@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License (LGPL) as published by the Free Software Foundation;
 * either version 2 of the License, or (at your option) any later
 * version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "kio_adb.h"

#include "kio_adb_debug.h"

#include <QUrl>
#include <QString>
#include <QDateTime>
#include <QByteArray>
#include <QProcess>
#include <QRegularExpression>

using namespace KIO;

extern "C" Q_DECL_EXPORT int kdemain(int argc, char **argv)
{
    if (argc != 4) {
        fprintf(stderr, "Usage: kio_adb protocol domain-socket1 domain-socket2\n");
        exit(-1);
    }

    AdbProtocol slave(argv[2], argv[3]);
    slave.dispatchLoop();

    return 0;
}

AdbProtocol::AdbProtocol(const QByteArray &pool, const QByteArray &app) :
    KIO::SlaveBase(QByteArrayLiteral("adb"), pool, app)
{

}

AdbProtocol::~AdbProtocol()
{

}

void AdbProtocol::stat(const QUrl &url)
{
    qCDebug(KIO_ADB) << "stat:" << url;

    finished();
}

void AdbProtocol::get(const QUrl &url)
{
    qCDebug(KIO_ADB) << "get:" << url;

    finished();
}

void AdbProtocol::put(const QUrl &url, int mode, KIO::JobFlags flags)
{
    qCDebug(KIO_ADB) << "put:" << url << mode << flags;

    finished();
}

void AdbProtocol::copy(const QUrl &src, const QUrl &dest, int mode, KIO::JobFlags flags)
{
    qCDebug(KIO_ADB) << "copy:" << src << dest << mode << flags;

    finished();
}

void AdbProtocol::rename(const QUrl &src, const QUrl &dest, KIO::JobFlags flags)
{
    qCDebug(KIO_ADB) << "rename:" << src << dest << flags;

    finished();
}

void AdbProtocol::symlink(const QString &target, const QUrl &dest, KIO::JobFlags flags)
{
    qCDebug(KIO_ADB) << "symlink:" << target << dest << flags;

    finished();
}

void AdbProtocol::chmod(const QUrl &url, int permissions)
{
    qCDebug(KIO_ADB) << "chmod:" << url << permissions;

    finished();
}

void AdbProtocol::chown(const QUrl &url, const QString &owner, const QString &group)
{
    qCDebug(KIO_ADB) << "chown:" << url << owner << group;

    finished();
}

void AdbProtocol::setModificationTime(const QUrl &url, const QDateTime &mtime)
{
    qCDebug(KIO_ADB) << "setModificationTime:" << url << mtime;

    finished();
}

void AdbProtocol::del(const QUrl &url, bool isfile)
{
    qCDebug(KIO_ADB) << "del:" << url << isfile;

    finished();
}

void AdbProtocol::listDir(const QUrl &url)
{
    qCDebug(KIO_ADB) << "listDir:" << url;

    const QString device = url.authority();
    const QString path = url.path();

    if (device.isEmpty()) {
        listDevices();
    } else if (path.isEmpty()) {
        QUrl targetUrl = url;
        targetUrl.setPath("/");
        redirection(targetUrl);

        finished();
    } else {
        QProcess process;
        process.setProgram(QLatin1String("adb"));
        process.setArguments({"-s", device, "shell", "ls", "-l", "-a", path});
        process.setProcessChannelMode(QProcess::MergedChannels);
        process.start();

        process.waitForFinished();
        const QString data = process.readAll();
        const QStringList lines = data.split(QLatin1Char('\n'), QString::SkipEmptyParts);

        static QRegularExpression re("^(?<type>[\\-dlcbps])"
                                     "(?<permission>[\\-rwxsStT]{9})\\s+"
                                     "(?<owner>\\w+)\\s+"
                                     "(?<group>\\w+)\\s+"
                                     "((?<size>\\d+)\\s+)?"
                                     "(?<datetime>\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2})\\s+"
                                     "(?<name>.+)\\s$",
                                     QRegularExpression::OptimizeOnFirstUsageOption);

        foreach (const QString &line, lines) {
            const auto match = re.match(line); // TODO try to use globalMatch instead
            if (!match.hasMatch()) {
                continue;
            }

            const auto parsePermission = [](const QString &permissionStr) -> int {
                if (permissionStr.size() != 9) {
                    return 0;
                }

                const auto parsePermissionChar = [](char c, int r, int w, int x, int s) -> int {
                    switch (c) {
                        case 'r':
                            return r;
                        case 'w':
                            return w;
                        case 'x':
                            return x;
                        case 't':
                            return x | S_ISVTX;
                        case 'T':
                            return S_ISVTX;
                        case 's':
                            return x | s;
                        case 'S':
                            return s;
                        case '-':
                        default:
                            return 0;
                    }
                };

                int permissions = 0;

                permissions |= parsePermissionChar(permissionStr[0].toLatin1(), S_IRUSR, S_IWUSR, S_IXUSR, S_ISUID);
                permissions |= parsePermissionChar(permissionStr[1].toLatin1(), S_IRUSR, S_IWUSR, S_IXUSR, S_ISUID);
                permissions |= parsePermissionChar(permissionStr[2].toLatin1(), S_IRUSR, S_IWUSR, S_IXUSR, S_ISUID);

                permissions |= parsePermissionChar(permissionStr[3].toLatin1(), S_IRGRP, S_IWGRP, S_IXGRP, S_ISGID);
                permissions |= parsePermissionChar(permissionStr[4].toLatin1(), S_IRGRP, S_IWGRP, S_IXGRP, S_ISGID);
                permissions |= parsePermissionChar(permissionStr[5].toLatin1(), S_IRGRP, S_IWGRP, S_IXGRP, S_ISGID);

                permissions |= parsePermissionChar(permissionStr[6].toLatin1(), S_IROTH, S_IWOTH, S_IXOTH, 0);
                permissions |= parsePermissionChar(permissionStr[7].toLatin1(), S_IROTH, S_IWOTH, S_IXOTH, 0);
                permissions |= parsePermissionChar(permissionStr[8].toLatin1(), S_IROTH, S_IWOTH, S_IXOTH, 0);

                return permissions;
            };

            UDSEntry entry;

            const QDateTime modificationTime = QDateTime::fromString(match.captured("datetime"), "yyyy-MM-dd HH:mm");
            entry.insert(UDSEntry::UDS_MODIFICATION_TIME, modificationTime.toTime_t());

            entry.insert(UDSEntry::UDS_USER, match.captured("owner"));
            entry.insert(UDSEntry::UDS_GROUP, match.captured("group"));
            entry.insert(UDSEntry::UDS_SIZE, match.captured("size").toULongLong());
            entry.insert(UDSEntry::UDS_ACCESS, parsePermission(match.captured("permission")));
            entry.insert(UDSEntry::UDS_NAME, match.captured("name"));

            const QChar type = match.captured("type")[0];
            if (type == QLatin1Char('-')) {
                entry.insert(UDSEntry::UDS_FILE_TYPE, S_IFREG);
            } else if (type == QLatin1Char('d')) {
                entry.insert(UDSEntry::UDS_FILE_TYPE, S_IFDIR);
                entry.insert(UDSEntry::UDS_MIME_TYPE, QLatin1String("inode/directory"));
            } else if (type == QLatin1Char('l')) {
                const QStringList nameParts = match.captured("name").split(QLatin1String(" -> "));
                const auto name = nameParts[0];
                const auto linkDest = nameParts[1];

                QUrl targetUrl = url;
                targetUrl.setPath(linkDest);

                entry.insert(UDSEntry::UDS_FILE_TYPE, S_IFDIR); // S_IFLNK
                entry.insert(UDSEntry::UDS_URL, targetUrl.url());
                entry.insert(UDSEntry::UDS_LINK_DEST, linkDest);
                entry.insert(UDSEntry::UDS_NAME, name);
            } else if (type == QLatin1Char('c')) {
                entry.insert(UDSEntry::UDS_FILE_TYPE, S_IFCHR);
            } else if (type == QLatin1Char('b')) {
                entry.insert(UDSEntry::UDS_FILE_TYPE, S_IFBLK);
            } else if (type == QLatin1Char('p')) {
                entry.insert(UDSEntry::UDS_FILE_TYPE, S_IFIFO);
            } else if (type == QLatin1Char('s')) {
                entry.insert(UDSEntry::UDS_FILE_TYPE, S_IFSOCK);
            }

            listEntry(entry);
        }

        finished();
    }
}

void AdbProtocol::mkdir(const QUrl &url, int permissions)
{
    qCDebug(KIO_ADB) << "mkdir:" << url << permissions;

    finished();
}

void AdbProtocol::virtual_hook(int id, void *data)
{
    switch(id) {
        case SlaveBase::GetFileSystemFreeSpace: {
            QUrl *url = static_cast<QUrl *>(data);
            fileSystemFreeSpace(*url);
        }   break;
        default:
            SlaveBase::virtual_hook(id, data);
    }
}

void AdbProtocol::fileSystemFreeSpace(const QUrl &url)
{
    qCDebug(KIO_ADB) << "fileSystemFreeSpace:" << url;

    finished();
}

void AdbProtocol::listDevices()
{
    qCDebug(KIO_ADB) << "listDevices";

    QProcess process;
    process.setProgram(QLatin1String("adb"));
    process.setArguments({"devices", "-l"});
    process.setProcessChannelMode(QProcess::MergedChannels);
    process.start();

    process.waitForFinished();
    const QString data = process.readAll();
    const QStringList lines = data.split(QLatin1Char('\n'), QString::SkipEmptyParts);

    static QRegularExpression re("^(?<id>\\S+)\\s+"
                                 "device\\s+"
                                 "(usb:(?<usb>\\S+)\\s+)?"
                                 "product:(?<product>\\w+)\\s+"
                                 "model:(?<model>\\w+)\\s+"
                                 "device:(?<device>\\w+)$",
                                 QRegularExpression::OptimizeOnFirstUsageOption);

    foreach (const QString &line, lines) {
        const auto match = re.match(line); // TODO try to use globalMatch instead
        if (!match.hasMatch()) {
            continue;
        }

        QUrl url;
        url.setScheme(QLatin1String("adb"));
        url.setAuthority(match.captured("id"));
        url.setPath("/");

        UDSEntry entry;
        entry.insert(UDSEntry::UDS_URL, url.url());
        entry.insert(UDSEntry::UDS_NAME, match.captured("model"));
        entry.insert(UDSEntry::UDS_ICON_NAME, QLatin1String("smartphone"));
        entry.insert(UDSEntry::UDS_FILE_TYPE, S_IFDIR);
        entry.insert(UDSEntry::UDS_ACCESS, S_IRUSR | S_IRGRP | S_IROTH);
        entry.insert(UDSEntry::UDS_MIME_TYPE, QLatin1String("inode/directory"));

        listEntry(entry);
    }

    finished();
}
<commit_msg>Better name link splitting<commit_after>/*
 * Copyright (C) 2015 by Emmanuel Pescosta <emmanuelpescosta099@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License (LGPL) as published by the Free Software Foundation;
 * either version 2 of the License, or (at your option) any later
 * version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "kio_adb.h"

#include "kio_adb_debug.h"

#include <QUrl>
#include <QString>
#include <QDateTime>
#include <QByteArray>
#include <QProcess>
#include <QRegularExpression>

using namespace KIO;

extern "C" Q_DECL_EXPORT int kdemain(int argc, char **argv)
{
    if (argc != 4) {
        fprintf(stderr, "Usage: kio_adb protocol domain-socket1 domain-socket2\n");
        exit(-1);
    }

    AdbProtocol slave(argv[2], argv[3]);
    slave.dispatchLoop();

    return 0;
}

AdbProtocol::AdbProtocol(const QByteArray &pool, const QByteArray &app) :
    KIO::SlaveBase(QByteArrayLiteral("adb"), pool, app)
{

}

AdbProtocol::~AdbProtocol()
{

}

void AdbProtocol::stat(const QUrl &url)
{
    qCDebug(KIO_ADB) << "stat:" << url;

    finished();
}

void AdbProtocol::get(const QUrl &url)
{
    qCDebug(KIO_ADB) << "get:" << url;

    finished();
}

void AdbProtocol::put(const QUrl &url, int mode, KIO::JobFlags flags)
{
    qCDebug(KIO_ADB) << "put:" << url << mode << flags;

    finished();
}

void AdbProtocol::copy(const QUrl &src, const QUrl &dest, int mode, KIO::JobFlags flags)
{
    qCDebug(KIO_ADB) << "copy:" << src << dest << mode << flags;

    finished();
}

void AdbProtocol::rename(const QUrl &src, const QUrl &dest, KIO::JobFlags flags)
{
    qCDebug(KIO_ADB) << "rename:" << src << dest << flags;

    finished();
}

void AdbProtocol::symlink(const QString &target, const QUrl &dest, KIO::JobFlags flags)
{
    qCDebug(KIO_ADB) << "symlink:" << target << dest << flags;

    finished();
}

void AdbProtocol::chmod(const QUrl &url, int permissions)
{
    qCDebug(KIO_ADB) << "chmod:" << url << permissions;

    finished();
}

void AdbProtocol::chown(const QUrl &url, const QString &owner, const QString &group)
{
    qCDebug(KIO_ADB) << "chown:" << url << owner << group;

    finished();
}

void AdbProtocol::setModificationTime(const QUrl &url, const QDateTime &mtime)
{
    qCDebug(KIO_ADB) << "setModificationTime:" << url << mtime;

    finished();
}

void AdbProtocol::del(const QUrl &url, bool isfile)
{
    qCDebug(KIO_ADB) << "del:" << url << isfile;

    finished();
}

void AdbProtocol::listDir(const QUrl &url)
{
    qCDebug(KIO_ADB) << "listDir:" << url;

    const QString device = url.authority();
    const QString path = url.path();

    if (device.isEmpty()) {
        listDevices();
    } else if (path.isEmpty()) {
        QUrl targetUrl = url;
        targetUrl.setPath("/");
        redirection(targetUrl);

        finished();
    } else {
        QProcess process;
        process.setProgram(QLatin1String("adb"));
        process.setArguments({"-s", device, "shell", "ls", "-l", "-a", path});
        process.setProcessChannelMode(QProcess::MergedChannels);
        process.start();

        process.waitForFinished();
        const QString data = process.readAll();
        const QStringList lines = data.split(QLatin1Char('\n'), QString::SkipEmptyParts);

        static QRegularExpression re("^(?<type>[\\-dlcbps])"
                                     "(?<permission>[\\-rwxsStT]{9})\\s+"
                                     "(?<owner>\\w+)\\s+"
                                     "(?<group>\\w+)\\s+"
                                     "((?<size>\\d+)\\s+)?"
                                     "(?<datetime>\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2})\\s+"
                                     "(?<name>.+)\\s$",
                                     QRegularExpression::OptimizeOnFirstUsageOption);

        foreach (const QString &line, lines) {
            const auto match = re.match(line); // TODO try to use globalMatch instead
            if (!match.hasMatch()) {
                continue;
            }

            const auto parsePermission = [](const QString &permissionStr) -> int {
                if (permissionStr.size() != 9) {
                    return 0;
                }

                const auto parsePermissionChar = [](char c, int r, int w, int x, int s) -> int {
                    switch (c) {
                        case 'r':
                            return r;
                        case 'w':
                            return w;
                        case 'x':
                            return x;
                        case 't':
                            return x | S_ISVTX;
                        case 'T':
                            return S_ISVTX;
                        case 's':
                            return x | s;
                        case 'S':
                            return s;
                        case '-':
                        default:
                            return 0;
                    }
                };

                int permissions = 0;

                permissions |= parsePermissionChar(permissionStr[0].toLatin1(), S_IRUSR, S_IWUSR, S_IXUSR, S_ISUID);
                permissions |= parsePermissionChar(permissionStr[1].toLatin1(), S_IRUSR, S_IWUSR, S_IXUSR, S_ISUID);
                permissions |= parsePermissionChar(permissionStr[2].toLatin1(), S_IRUSR, S_IWUSR, S_IXUSR, S_ISUID);

                permissions |= parsePermissionChar(permissionStr[3].toLatin1(), S_IRGRP, S_IWGRP, S_IXGRP, S_ISGID);
                permissions |= parsePermissionChar(permissionStr[4].toLatin1(), S_IRGRP, S_IWGRP, S_IXGRP, S_ISGID);
                permissions |= parsePermissionChar(permissionStr[5].toLatin1(), S_IRGRP, S_IWGRP, S_IXGRP, S_ISGID);

                permissions |= parsePermissionChar(permissionStr[6].toLatin1(), S_IROTH, S_IWOTH, S_IXOTH, 0);
                permissions |= parsePermissionChar(permissionStr[7].toLatin1(), S_IROTH, S_IWOTH, S_IXOTH, 0);
                permissions |= parsePermissionChar(permissionStr[8].toLatin1(), S_IROTH, S_IWOTH, S_IXOTH, 0);

                return permissions;
            };

            UDSEntry entry;

            const QDateTime modificationTime = QDateTime::fromString(match.captured("datetime"), "yyyy-MM-dd HH:mm");
            entry.insert(UDSEntry::UDS_MODIFICATION_TIME, modificationTime.toTime_t());

            entry.insert(UDSEntry::UDS_USER, match.captured("owner"));
            entry.insert(UDSEntry::UDS_GROUP, match.captured("group"));
            entry.insert(UDSEntry::UDS_SIZE, match.captured("size").toULongLong());
            entry.insert(UDSEntry::UDS_ACCESS, parsePermission(match.captured("permission")));
            entry.insert(UDSEntry::UDS_NAME, match.captured("name"));

            const QChar type = match.captured("type")[0];
            if (type == QLatin1Char('-')) {
                entry.insert(UDSEntry::UDS_FILE_TYPE, S_IFREG);
            } else if (type == QLatin1Char('d')) {
                entry.insert(UDSEntry::UDS_FILE_TYPE, S_IFDIR);
                entry.insert(UDSEntry::UDS_MIME_TYPE, QLatin1String("inode/directory"));
            } else if (type == QLatin1Char('l')) {
                const auto nameLink = match.captured("name");
                const auto name = nameLink.section(" -> ", 0, -2);
                const auto linkDest = nameLink.section(" -> ", -1);

                QUrl targetUrl = url;
                targetUrl.setPath(linkDest);

                entry.insert(UDSEntry::UDS_FILE_TYPE, S_IFDIR); // S_IFLNK
                entry.insert(UDSEntry::UDS_URL, targetUrl.url());
                entry.insert(UDSEntry::UDS_LINK_DEST, linkDest);
                entry.insert(UDSEntry::UDS_NAME, name);
            } else if (type == QLatin1Char('c')) {
                entry.insert(UDSEntry::UDS_FILE_TYPE, S_IFCHR);
            } else if (type == QLatin1Char('b')) {
                entry.insert(UDSEntry::UDS_FILE_TYPE, S_IFBLK);
            } else if (type == QLatin1Char('p')) {
                entry.insert(UDSEntry::UDS_FILE_TYPE, S_IFIFO);
            } else if (type == QLatin1Char('s')) {
                entry.insert(UDSEntry::UDS_FILE_TYPE, S_IFSOCK);
            }

            listEntry(entry);
        }

        finished();
    }
}

void AdbProtocol::mkdir(const QUrl &url, int permissions)
{
    qCDebug(KIO_ADB) << "mkdir:" << url << permissions;

    finished();
}

void AdbProtocol::virtual_hook(int id, void *data)
{
    switch(id) {
        case SlaveBase::GetFileSystemFreeSpace: {
            QUrl *url = static_cast<QUrl *>(data);
            fileSystemFreeSpace(*url);
        }   break;
        default:
            SlaveBase::virtual_hook(id, data);
    }
}

void AdbProtocol::fileSystemFreeSpace(const QUrl &url)
{
    qCDebug(KIO_ADB) << "fileSystemFreeSpace:" << url;

    finished();
}

void AdbProtocol::listDevices()
{
    qCDebug(KIO_ADB) << "listDevices";

    QProcess process;
    process.setProgram(QLatin1String("adb"));
    process.setArguments({"devices", "-l"});
    process.setProcessChannelMode(QProcess::MergedChannels);
    process.start();

    process.waitForFinished();
    const QString data = process.readAll();
    const QStringList lines = data.split(QLatin1Char('\n'), QString::SkipEmptyParts);

    static QRegularExpression re("^(?<id>\\S+)\\s+"
                                 "device\\s+"
                                 "(usb:(?<usb>\\S+)\\s+)?"
                                 "product:(?<product>\\w+)\\s+"
                                 "model:(?<model>\\w+)\\s+"
                                 "device:(?<device>\\w+)$",
                                 QRegularExpression::OptimizeOnFirstUsageOption);

    foreach (const QString &line, lines) {
        const auto match = re.match(line); // TODO try to use globalMatch instead
        if (!match.hasMatch()) {
            continue;
        }

        QUrl url;
        url.setScheme(QLatin1String("adb"));
        url.setAuthority(match.captured("id"));
        url.setPath("/");

        UDSEntry entry;
        entry.insert(UDSEntry::UDS_URL, url.url());
        entry.insert(UDSEntry::UDS_NAME, match.captured("model"));
        entry.insert(UDSEntry::UDS_ICON_NAME, QLatin1String("smartphone"));
        entry.insert(UDSEntry::UDS_FILE_TYPE, S_IFDIR);
        entry.insert(UDSEntry::UDS_ACCESS, S_IRUSR | S_IRGRP | S_IROTH);
        entry.insert(UDSEntry::UDS_MIME_TYPE, QLatin1String("inode/directory"));

        listEntry(entry);
    }

    finished();
}
<|endoftext|>


<commit_before>#ifndef MJOLNIR_CORE_SPATIAL_PARTITION_FOR_MU
#define MJOLNIR_CORE_SPATIAL_PARTITION_FOR_MU
#include "System.hpp"
#include <algorithm>
#include <limits>

namespace mjolnir
{

template<typename traitsT>
class SpatialPartitionForMU
{
  public:
    typedef traitsT traits_type;
    typedef System<traits_type> system_type;
    typedef typename traits_type::real_type       real_type;
    typedef typename traits_type::coordinate_type coordinate_type;
    typedef std::vector<std::size_t> index_array;

  public:

    SpatialPartitionForMU();
    ~SpatialPartitionForMU();

};

}//end namespace mjolnir
#endif// MJOLNIR_CORE_SPATIAL_PARTITION_FOR_MU
<commit_msg>add = default<commit_after>#ifndef MJOLNIR_CORE_SPATIAL_PARTITION_FOR_MU
#define MJOLNIR_CORE_SPATIAL_PARTITION_FOR_MU
#include "System.hpp"
#include <algorithm>
#include <limits>

namespace mjolnir
{

template<typename traitsT>
class SpatialPartitionForMU
{
  public:
    typedef traitsT traits_type;
    typedef System<traits_type> system_type;
    typedef typename traits_type::real_type       real_type;
    typedef typename traits_type::coordinate_type coordinate_type;
    typedef std::vector<std::size_t> index_array;

  public:

    SpatialPartitionForMU() = default;
    ~SpatialPartitionForMU() = default;

};

}//end namespace mjolnir
#endif// MJOLNIR_CORE_SPATIAL_PARTITION_FOR_MU
<|endoftext|>


<commit_before>/*************************************************************************/
/*  noise.cpp                                                            */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "noise.h"

Ref<Image> Noise::get_seamless_image(int p_width, int p_height, bool p_invert, bool p_in_3d_space, real_t p_blend_skirt) const {
	int skirt_width = p_width * p_blend_skirt;
	int skirt_height = p_height * p_blend_skirt;
	int src_width = p_width + skirt_width;
	int src_height = p_height + skirt_height;

	Ref<Image> src = get_image(src_width, src_height, p_invert, p_in_3d_space);
	bool grayscale = (src->get_format() == Image::FORMAT_L8);
	if (grayscale) {
		return _generate_seamless_image<uint8_t>(src, p_width, p_height, p_invert, p_blend_skirt);
	} else {
		return _generate_seamless_image<uint32_t>(src, p_width, p_height, p_invert, p_blend_skirt);
	}
}

// Template specialization for faster grayscale blending.
template <>
uint8_t Noise::_alpha_blend<uint8_t>(uint8_t p_bg, uint8_t p_fg, int p_alpha) const {
	uint16_t alpha = p_alpha + 1;
	uint16_t inv_alpha = 256 - p_alpha;

	return (uint8_t)((alpha * p_fg + inv_alpha * p_bg) >> 8);
}

Ref<Image> Noise::get_image(int p_width, int p_height, bool p_invert, bool p_in_3d_space) const {
	Vector<uint8_t> data;
	data.resize(p_width * p_height);

	uint8_t *wd8 = data.ptrw();

	// Get all values and identify min/max values.
	Vector<real_t> values;
	values.resize(p_width * p_height);
	real_t min_val = 1000;
	real_t max_val = -1000;

	for (int y = 0, i = 0; y < p_height; y++) {
		for (int x = 0; x < p_width; x++, i++) {
			values.set(i, p_in_3d_space ? get_noise_3d(x, y, 0.0) : get_noise_2d(x, y));
			if (values[i] > max_val) {
				max_val = values[i];
			}
			if (values[i] < min_val) {
				min_val = values[i];
			}
		}
	}

	// Normalize values and write to texture.
	uint8_t value;
	for (int i = 0, x = 0; i < p_height; i++) {
		for (int j = 0; j < p_width; j++, x++) {
			if (max_val == min_val) {
				value = 0;
			} else {
				value = uint8_t(CLAMP((values[x] - min_val) / (max_val - min_val) * 255.f, 0, 255));
			}
			if (p_invert) {
				value = 255 - value;
			}

			wd8[x] = value;
		}
	}

	return memnew(Image(p_width, p_height, false, Image::FORMAT_L8, data));
}

void Noise::_bind_methods() {
	// Noise functions.
	ClassDB::bind_method(D_METHOD("get_noise_1d", "x"), &Noise::get_noise_1d);
	ClassDB::bind_method(D_METHOD("get_noise_2d", "x", "y"), &Noise::get_noise_2d);
	ClassDB::bind_method(D_METHOD("get_noise_2dv", "v"), &Noise::get_noise_2dv);
	ClassDB::bind_method(D_METHOD("get_noise_3d", "x", "y", "z"), &Noise::get_noise_3d);
	ClassDB::bind_method(D_METHOD("get_noise_3dv", "v"), &Noise::get_noise_3dv);

	// Textures.
	ClassDB::bind_method(D_METHOD("get_image", "width", "height", "invert", "in_3d_space"), &Noise::get_image, DEFVAL(false), DEFVAL(false));
	ClassDB::bind_method(D_METHOD("get_seamless_image", "width", "height", "invert", "in_3d_space", "skirt"), &Noise::get_seamless_image, DEFVAL(false), DEFVAL(false), DEFVAL(0.1));
}
<commit_msg>Validate image size for Noise get image methods<commit_after>/*************************************************************************/
/*  noise.cpp                                                            */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "noise.h"

Ref<Image> Noise::get_seamless_image(int p_width, int p_height, bool p_invert, bool p_in_3d_space, real_t p_blend_skirt) const {
	ERR_FAIL_COND_V(p_width <= 0 || p_height <= 0, Ref<Image>());

	int skirt_width = p_width * p_blend_skirt;
	int skirt_height = p_height * p_blend_skirt;
	int src_width = p_width + skirt_width;
	int src_height = p_height + skirt_height;

	Ref<Image> src = get_image(src_width, src_height, p_invert, p_in_3d_space);
	bool grayscale = (src->get_format() == Image::FORMAT_L8);
	if (grayscale) {
		return _generate_seamless_image<uint8_t>(src, p_width, p_height, p_invert, p_blend_skirt);
	} else {
		return _generate_seamless_image<uint32_t>(src, p_width, p_height, p_invert, p_blend_skirt);
	}
}

// Template specialization for faster grayscale blending.
template <>
uint8_t Noise::_alpha_blend<uint8_t>(uint8_t p_bg, uint8_t p_fg, int p_alpha) const {
	uint16_t alpha = p_alpha + 1;
	uint16_t inv_alpha = 256 - p_alpha;

	return (uint8_t)((alpha * p_fg + inv_alpha * p_bg) >> 8);
}

Ref<Image> Noise::get_image(int p_width, int p_height, bool p_invert, bool p_in_3d_space) const {
	ERR_FAIL_COND_V(p_width <= 0 || p_height <= 0, Ref<Image>());

	Vector<uint8_t> data;
	data.resize(p_width * p_height);

	uint8_t *wd8 = data.ptrw();

	// Get all values and identify min/max values.
	Vector<real_t> values;
	values.resize(p_width * p_height);
	real_t min_val = 1000;
	real_t max_val = -1000;

	for (int y = 0, i = 0; y < p_height; y++) {
		for (int x = 0; x < p_width; x++, i++) {
			values.set(i, p_in_3d_space ? get_noise_3d(x, y, 0.0) : get_noise_2d(x, y));
			if (values[i] > max_val) {
				max_val = values[i];
			}
			if (values[i] < min_val) {
				min_val = values[i];
			}
		}
	}

	// Normalize values and write to texture.
	uint8_t value;
	for (int i = 0, x = 0; i < p_height; i++) {
		for (int j = 0; j < p_width; j++, x++) {
			if (max_val == min_val) {
				value = 0;
			} else {
				value = uint8_t(CLAMP((values[x] - min_val) / (max_val - min_val) * 255.f, 0, 255));
			}
			if (p_invert) {
				value = 255 - value;
			}

			wd8[x] = value;
		}
	}

	return memnew(Image(p_width, p_height, false, Image::FORMAT_L8, data));
}

void Noise::_bind_methods() {
	// Noise functions.
	ClassDB::bind_method(D_METHOD("get_noise_1d", "x"), &Noise::get_noise_1d);
	ClassDB::bind_method(D_METHOD("get_noise_2d", "x", "y"), &Noise::get_noise_2d);
	ClassDB::bind_method(D_METHOD("get_noise_2dv", "v"), &Noise::get_noise_2dv);
	ClassDB::bind_method(D_METHOD("get_noise_3d", "x", "y", "z"), &Noise::get_noise_3d);
	ClassDB::bind_method(D_METHOD("get_noise_3dv", "v"), &Noise::get_noise_3dv);

	// Textures.
	ClassDB::bind_method(D_METHOD("get_image", "width", "height", "invert", "in_3d_space"), &Noise::get_image, DEFVAL(false), DEFVAL(false));
	ClassDB::bind_method(D_METHOD("get_seamless_image", "width", "height", "invert", "in_3d_space", "skirt"), &Noise::get_seamless_image, DEFVAL(false), DEFVAL(false), DEFVAL(0.1));
}
<|endoftext|>


<commit_before>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#include "util.h"
#include "common/vec.h"
// #include <ospray/common/OSPCommon.h>

#ifdef __APPLE__
#include <OpenGL/gl.h>
#else
#include <GL/gl.h>
#endif
#include <math.h>

namespace ospray {
  typedef ospcommon::vec2i vec2i;
  typedef ospcommon::vec3f vec3f;

  namespace opengl {

    OSPTexture2D getOSPDepthTextureFromOpenGLPerspective()
    {
      // compute fovy, aspect, zNear, zFar from OpenGL projection matrix
      GLdouble glProjectionMatrix[16];
      glGetDoublev(GL_PROJECTION_MATRIX, glProjectionMatrix);

      const double m0  = glProjectionMatrix[0];
      const double m5  = glProjectionMatrix[5];
      const double m10 = glProjectionMatrix[10];
      const double m14 = glProjectionMatrix[14];
      const double k = (m10 - 1.0f) / (m10 + 1.0f);

      const double fovy = 2. * atanf(1.0f / m5) * 180./M_PI;
      const double aspect = m5 / m0;
      const double zNear = (m14 * (1.0f - k)) / (2.0f * k);
      const double zFar = k * zNear;

      // get camera direction and up vectors from model view matrix
      GLdouble glModelViewMatrix[16];
      glGetDoublev(GL_MODELVIEW_MATRIX, glModelViewMatrix);

      const ospray::vec3f  cameraUp( glModelViewMatrix[1],  glModelViewMatrix[5],  glModelViewMatrix[9]);
      const ospray::vec3f cameraDir(-glModelViewMatrix[2], -glModelViewMatrix[6], -glModelViewMatrix[10]);

      // get window dimensions from OpenGL viewport
      GLint glViewport[4];
      glGetIntegerv(GL_VIEWPORT, glViewport);

      const size_t width = glViewport[2];
      const size_t height = glViewport[3];

      // read OpenGL depth buffer
      float *glDepthBuffer = new float[width * height];
      glReadPixels(0, 0, width, height, GL_DEPTH_COMPONENT, GL_FLOAT, (GLvoid *)glDepthBuffer);

      // get an OSPRay depth texture from the OpenGL depth buffer
      OSPTexture2D depthTexture
        = getOSPDepthTextureFromOpenGLPerspective(fovy, aspect, zNear, zFar,
                                                  (osp::vec3f&)cameraDir, (osp::vec3f&)cameraUp,
                                                  glDepthBuffer, width, height);

      // free allocated depth buffer
      delete[] glDepthBuffer;

      // return OSPRay depth texture
      return depthTexture;
    }

    OSPTexture2D getOSPDepthTextureFromOpenGLPerspective(const double &fovy,
                                                         const double &aspect,
                                                         const double &zNear,
                                                         const double &zFar,
                                                         const osp::vec3f &_cameraDir,
                                                         const osp::vec3f &_cameraUp,
                                                         const float *glDepthBuffer,
                                                         const size_t &glDepthBufferWidth,
                                                         const size_t &glDepthBufferHeight)
    {
      ospray::vec3f cameraDir = (ospray::vec3f&)_cameraDir;
      ospray::vec3f cameraUp = (ospray::vec3f&)_cameraUp;
      // this should later be done in ISPC...

      float *ospDepth = new float[glDepthBufferWidth * glDepthBufferHeight];

      // transform OpenGL depth to linear depth
      for (size_t i=0; i<glDepthBufferWidth*glDepthBufferHeight; i++) {
        const double z_n = 2.0 * glDepthBuffer[i] - 1.0;
        ospDepth[i] = 2.0 * zNear * zFar / (zFar + zNear - z_n * (zFar - zNear));
      }

      // transform from orthogonal Z depth to ray distance t
      ospray::vec3f dir_du = normalize(cross(cameraDir, cameraUp));
      ospray::vec3f dir_dv = normalize(cross(dir_du, cameraDir));

      const float imagePlaneSizeY = 2.f * tanf(fovy/2.f * M_PI/180.f);
      const float imagePlaneSizeX = imagePlaneSizeY * aspect;

      dir_du *= imagePlaneSizeX;
      dir_dv *= imagePlaneSizeY;

      const ospray::vec3f dir_00 = cameraDir - .5f * dir_du - .5f * dir_dv;

      for (size_t j=0; j<glDepthBufferHeight; j++)
        for (size_t i=0; i<glDepthBufferWidth; i++) {
          const ospray::vec3f dir_ij = normalize(dir_00 + float(i)/float(glDepthBufferWidth-1) * dir_du + float(j)/float(glDepthBufferHeight-1) * dir_dv);

          const float t = ospDepth[j*glDepthBufferWidth+i] / dot(cameraDir, dir_ij);
          ospDepth[j*glDepthBufferWidth+i] = t;
        }

      // nearest texture filtering required for depth textures -- we don't want interpolation of depth values...
      vec2i texSize(glDepthBufferWidth, glDepthBufferHeight);
      OSPTexture2D depthTexture = ospNewTexture2D((osp::vec2i&)texSize, OSP_TEXTURE_R32F, ospDepth, OSP_TEXTURE_FILTER_NEAREST);

      delete[] ospDepth;

      return depthTexture;
    }

    float * getOpenGLDepthFromOSPPerspective(OSPFrameBuffer frameBuffer,
                                             const osp::vec2i &frameBufferSize)
    {
      // compute fovy, aspect, zNear, zFar from OpenGL projection matrix
      // this assumes fovy, aspect match the values set on the OSPRay perspective camera!
      GLdouble glProjectionMatrix[16];
      glGetDoublev(GL_PROJECTION_MATRIX, glProjectionMatrix);

      const double m0  = glProjectionMatrix[0];
      const double m5  = glProjectionMatrix[5];
      const double m10 = glProjectionMatrix[10];
      const double m14 = glProjectionMatrix[14];
      const double k = (m10 - 1.0f) / (m10 + 1.0f);

      const double fovy = 2. * atan(1.0f / m5) * 180./M_PI;
      const double aspect = m5 / m0;
      const double zNear = (m14 * (1.0f - k)) / (2.0f * k);
      const double zFar = k * zNear;

      // get camera direction and up vectors from model view matrix
      // again, this assumes these values match those set on the OSPRay camera!
      GLdouble glModelViewMatrix[16];
      glGetDoublev(GL_MODELVIEW_MATRIX, glModelViewMatrix);

      const ospray::vec3f  cameraUp( glModelViewMatrix[1],  glModelViewMatrix[5],  glModelViewMatrix[9]);
      const ospray::vec3f cameraDir(-glModelViewMatrix[2], -glModelViewMatrix[6], -glModelViewMatrix[10]);

      // map OSPRay depth buffer from provided frame buffer
      const float *ospDepthBuffer = (const float *)ospMapFrameBuffer(frameBuffer, OSP_FB_DEPTH);

      // get OpenGL depth from OSPRay depth
      float *glDepth
        = getOpenGLDepthFromOSPPerspective(fovy, aspect, zNear, zFar,
                                           (osp::vec3f&)cameraDir, (osp::vec3f&)cameraUp,
                                           ospDepthBuffer, frameBufferSize);

      // unmap OSPRay depth buffer
      ospUnmapFrameBuffer(ospDepthBuffer, frameBuffer);

      return glDepth;
    }

    float * getOpenGLDepthFromOSPPerspective(const double &fovy,
                                             const double &aspect,
                                             const double &zNear,
                                             const double &zFar,
                                             const osp::vec3f &_cameraDir,
                                             const osp::vec3f &_cameraUp,
                                             const float *ospDepthBuffer,
                                             const osp::vec2i &frameBufferSize)
    {
      ospray::vec3f cameraDir = (ospray::vec3f&)cameraDir;
      ospray::vec3f cameraUp = (ospray::vec3f&)cameraUp;
      // this should later be done in ISPC...

      const size_t ospDepthBufferWidth =  (size_t)frameBufferSize.x;
      const size_t ospDepthBufferHeight = (size_t)frameBufferSize.y;

      float *glDepth = new float[ospDepthBufferWidth * ospDepthBufferHeight];

      // transform from ray distance t to orthogonal Z depth
      ospray::vec3f dir_du = normalize(cross(cameraDir, cameraUp));
      ospray::vec3f dir_dv = normalize(cross(dir_du, cameraDir));

      const float imagePlaneSizeY = 2.f * tanf(fovy/2.f * M_PI/180.f);
      const float imagePlaneSizeX = imagePlaneSizeY * aspect;

      dir_du *= imagePlaneSizeX;
      dir_dv *= imagePlaneSizeY;

      const ospray::vec3f dir_00 = cameraDir - .5f * dir_du - .5f * dir_dv;

      for (size_t j=0; j<ospDepthBufferHeight; j++)
        for (size_t i=0; i<ospDepthBufferWidth; i++) {
          const ospray::vec3f dir_ij = normalize(dir_00 + float(i)/float(ospDepthBufferWidth-1) * dir_du + float(j)/float(ospDepthBufferHeight-1) * dir_dv);

          glDepth[j*ospDepthBufferWidth+i] = ospDepthBuffer[j*ospDepthBufferWidth+i] * dot(cameraDir, dir_ij);
        }

      // transform from linear to nonlinear OpenGL depth
      const double A = -(zFar + zNear) / (zFar - zNear);
      const double B = -2. * zFar*zNear / (zFar - zNear);

      for (size_t i=0; i<ospDepthBufferWidth*ospDepthBufferHeight; i++)
        glDepth[i] = 0.5*(-A*glDepth[i] + B) / glDepth[i] + 0.5;

      return glDepth;
    }

  }
}
<commit_msg>Fix OpenGL utils module on Windows<commit_after>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#include "util.h"
#include "common/vec.h"
// #include <ospray/common/OSPCommon.h>

#ifdef _WIN32
#  ifndef WIN32_LEAN_AND_MEAN
#    define WIN32_LEAN_AND_MEAN
#  endif
#  include <windows.h>
#endif

#ifdef __APPLE__
#include <OpenGL/gl.h>
#else
#include <GL/gl.h>
#endif
#include <math.h>

namespace ospray {
  typedef ospcommon::vec2i vec2i;
  typedef ospcommon::vec3f vec3f;

  namespace opengl {

    OSPTexture2D getOSPDepthTextureFromOpenGLPerspective()
    {
      // compute fovy, aspect, zNear, zFar from OpenGL projection matrix
      GLdouble glProjectionMatrix[16];
      glGetDoublev(GL_PROJECTION_MATRIX, glProjectionMatrix);

      const double m0  = glProjectionMatrix[0];
      const double m5  = glProjectionMatrix[5];
      const double m10 = glProjectionMatrix[10];
      const double m14 = glProjectionMatrix[14];
      const double k = (m10 - 1.0f) / (m10 + 1.0f);

      const double fovy = 2. * atanf(1.0f / m5) * 180./M_PI;
      const double aspect = m5 / m0;
      const double zNear = (m14 * (1.0f - k)) / (2.0f * k);
      const double zFar = k * zNear;

      // get camera direction and up vectors from model view matrix
      GLdouble glModelViewMatrix[16];
      glGetDoublev(GL_MODELVIEW_MATRIX, glModelViewMatrix);

      const ospray::vec3f  cameraUp( glModelViewMatrix[1],  glModelViewMatrix[5],  glModelViewMatrix[9]);
      const ospray::vec3f cameraDir(-glModelViewMatrix[2], -glModelViewMatrix[6], -glModelViewMatrix[10]);

      // get window dimensions from OpenGL viewport
      GLint glViewport[4];
      glGetIntegerv(GL_VIEWPORT, glViewport);

      const size_t width = glViewport[2];
      const size_t height = glViewport[3];

      // read OpenGL depth buffer
      float *glDepthBuffer = new float[width * height];
      glReadPixels(0, 0, width, height, GL_DEPTH_COMPONENT, GL_FLOAT, (GLvoid *)glDepthBuffer);

      // get an OSPRay depth texture from the OpenGL depth buffer
      OSPTexture2D depthTexture
        = getOSPDepthTextureFromOpenGLPerspective(fovy, aspect, zNear, zFar,
                                                  (osp::vec3f&)cameraDir, (osp::vec3f&)cameraUp,
                                                  glDepthBuffer, width, height);

      // free allocated depth buffer
      delete[] glDepthBuffer;

      // return OSPRay depth texture
      return depthTexture;
    }

    OSPTexture2D getOSPDepthTextureFromOpenGLPerspective(const double &fovy,
                                                         const double &aspect,
                                                         const double &zNear,
                                                         const double &zFar,
                                                         const osp::vec3f &_cameraDir,
                                                         const osp::vec3f &_cameraUp,
                                                         const float *glDepthBuffer,
                                                         const size_t &glDepthBufferWidth,
                                                         const size_t &glDepthBufferHeight)
    {
      ospray::vec3f cameraDir = (ospray::vec3f&)_cameraDir;
      ospray::vec3f cameraUp = (ospray::vec3f&)_cameraUp;
      // this should later be done in ISPC...

      float *ospDepth = new float[glDepthBufferWidth * glDepthBufferHeight];

      // transform OpenGL depth to linear depth
      for (size_t i=0; i<glDepthBufferWidth*glDepthBufferHeight; i++) {
        const double z_n = 2.0 * glDepthBuffer[i] - 1.0;
        ospDepth[i] = 2.0 * zNear * zFar / (zFar + zNear - z_n * (zFar - zNear));
      }

      // transform from orthogonal Z depth to ray distance t
      ospray::vec3f dir_du = normalize(cross(cameraDir, cameraUp));
      ospray::vec3f dir_dv = normalize(cross(dir_du, cameraDir));

      const float imagePlaneSizeY = 2.f * tanf(fovy/2.f * M_PI/180.f);
      const float imagePlaneSizeX = imagePlaneSizeY * aspect;

      dir_du *= imagePlaneSizeX;
      dir_dv *= imagePlaneSizeY;

      const ospray::vec3f dir_00 = cameraDir - .5f * dir_du - .5f * dir_dv;

      for (size_t j=0; j<glDepthBufferHeight; j++)
        for (size_t i=0; i<glDepthBufferWidth; i++) {
          const ospray::vec3f dir_ij = normalize(dir_00 + float(i)/float(glDepthBufferWidth-1) * dir_du + float(j)/float(glDepthBufferHeight-1) * dir_dv);

          const float t = ospDepth[j*glDepthBufferWidth+i] / dot(cameraDir, dir_ij);
          ospDepth[j*glDepthBufferWidth+i] = t;
        }

      // nearest texture filtering required for depth textures -- we don't want interpolation of depth values...
      vec2i texSize(glDepthBufferWidth, glDepthBufferHeight);
      OSPTexture2D depthTexture = ospNewTexture2D((osp::vec2i&)texSize, OSP_TEXTURE_R32F, ospDepth, OSP_TEXTURE_FILTER_NEAREST);

      delete[] ospDepth;

      return depthTexture;
    }

    float * getOpenGLDepthFromOSPPerspective(OSPFrameBuffer frameBuffer,
                                             const osp::vec2i &frameBufferSize)
    {
      // compute fovy, aspect, zNear, zFar from OpenGL projection matrix
      // this assumes fovy, aspect match the values set on the OSPRay perspective camera!
      GLdouble glProjectionMatrix[16];
      glGetDoublev(GL_PROJECTION_MATRIX, glProjectionMatrix);

      const double m0  = glProjectionMatrix[0];
      const double m5  = glProjectionMatrix[5];
      const double m10 = glProjectionMatrix[10];
      const double m14 = glProjectionMatrix[14];
      const double k = (m10 - 1.0f) / (m10 + 1.0f);

      const double fovy = 2. * atan(1.0f / m5) * 180./M_PI;
      const double aspect = m5 / m0;
      const double zNear = (m14 * (1.0f - k)) / (2.0f * k);
      const double zFar = k * zNear;

      // get camera direction and up vectors from model view matrix
      // again, this assumes these values match those set on the OSPRay camera!
      GLdouble glModelViewMatrix[16];
      glGetDoublev(GL_MODELVIEW_MATRIX, glModelViewMatrix);

      const ospray::vec3f  cameraUp( glModelViewMatrix[1],  glModelViewMatrix[5],  glModelViewMatrix[9]);
      const ospray::vec3f cameraDir(-glModelViewMatrix[2], -glModelViewMatrix[6], -glModelViewMatrix[10]);

      // map OSPRay depth buffer from provided frame buffer
      const float *ospDepthBuffer = (const float *)ospMapFrameBuffer(frameBuffer, OSP_FB_DEPTH);

      // get OpenGL depth from OSPRay depth
      float *glDepth
        = getOpenGLDepthFromOSPPerspective(fovy, aspect, zNear, zFar,
                                           (osp::vec3f&)cameraDir, (osp::vec3f&)cameraUp,
                                           ospDepthBuffer, frameBufferSize);

      // unmap OSPRay depth buffer
      ospUnmapFrameBuffer(ospDepthBuffer, frameBuffer);

      return glDepth;
    }

    float * getOpenGLDepthFromOSPPerspective(const double &fovy,
                                             const double &aspect,
                                             const double &zNear,
                                             const double &zFar,
                                             const osp::vec3f &_cameraDir,
                                             const osp::vec3f &_cameraUp,
                                             const float *ospDepthBuffer,
                                             const osp::vec2i &frameBufferSize)
    {
      ospray::vec3f cameraDir = (ospray::vec3f&)cameraDir;
      ospray::vec3f cameraUp = (ospray::vec3f&)cameraUp;
      // this should later be done in ISPC...

      const size_t ospDepthBufferWidth =  (size_t)frameBufferSize.x;
      const size_t ospDepthBufferHeight = (size_t)frameBufferSize.y;

      float *glDepth = new float[ospDepthBufferWidth * ospDepthBufferHeight];

      // transform from ray distance t to orthogonal Z depth
      ospray::vec3f dir_du = normalize(cross(cameraDir, cameraUp));
      ospray::vec3f dir_dv = normalize(cross(dir_du, cameraDir));

      const float imagePlaneSizeY = 2.f * tanf(fovy/2.f * M_PI/180.f);
      const float imagePlaneSizeX = imagePlaneSizeY * aspect;

      dir_du *= imagePlaneSizeX;
      dir_dv *= imagePlaneSizeY;

      const ospray::vec3f dir_00 = cameraDir - .5f * dir_du - .5f * dir_dv;

      for (size_t j=0; j<ospDepthBufferHeight; j++)
        for (size_t i=0; i<ospDepthBufferWidth; i++) {
          const ospray::vec3f dir_ij = normalize(dir_00 + float(i)/float(ospDepthBufferWidth-1) * dir_du + float(j)/float(ospDepthBufferHeight-1) * dir_dv);

          glDepth[j*ospDepthBufferWidth+i] = ospDepthBuffer[j*ospDepthBufferWidth+i] * dot(cameraDir, dir_ij);
        }

      // transform from linear to nonlinear OpenGL depth
      const double A = -(zFar + zNear) / (zFar - zNear);
      const double B = -2. * zFar*zNear / (zFar - zNear);

      for (size_t i=0; i<ospDepthBufferWidth*ospDepthBufferHeight; i++)
        glDepth[i] = 0.5*(-A*glDepth[i] + B) / glDepth[i] + 0.5;

      return glDepth;
    }

  }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: datman.hxx,v $
 * $Revision: 1.16 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _BIB_DATMAN_HXX
#define _BIB_DATMAN_HXX

#include <com/sun/star/awt/XControlModel.hpp>
#include <com/sun/star/form/XForm.hpp>
#include <com/sun/star/sdbc/XResultSet.hpp>
#include <com/sun/star/sdb/XSingleSelectQueryComposer.hpp>
#include <com/sun/star/form/XFormController.hpp>
#include <cppuhelper/compbase2.hxx>
#include <cppuhelper/interfacecontainer.h>
#include <com/sun/star/form/XLoadable.hpp>
#include <comphelper/broadcasthelper.hxx>
// #100312# --------------------
#include <com/sun/star/frame/XDispatchProviderInterceptor.hpp>
#include <com/sun/star/frame/XDispatchProviderInterception.hpp>
#include <cppuhelper/implbase1.hxx>

class Window;

//-----------------------------------------------------------------------------
namespace bib
{
    class BibView;
    // #100312# -----------
    class BibBeamer;
}

class BibToolBar;
struct BibDBDescriptor;

// #100312# ---------------------
class BibInterceptorHelper
    :public cppu::WeakImplHelper1< ::com::sun::star::frame::XDispatchProviderInterceptor >
{
private:
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > xMasterDispatchProvider;
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > xSlaveDispatchProvider;
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xFormDispatch;
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProviderInterception > xInterception;

protected:
    ~BibInterceptorHelper( );

public:
    BibInterceptorHelper( ::bib::BibBeamer* pBibBeamer, ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xDispatch);

    void ReleaseInterceptor();

    // XDispatchProvider
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > SAL_CALL queryDispatch( const ::com::sun::star::util::URL& aURL, const ::rtl::OUString& aTargetFrameName, sal_Int32 nSearchFlags ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > > SAL_CALL queryDispatches( const ::com::sun::star::uno::Sequence< ::com::sun::star::frame::DispatchDescriptor >& aDescripts ) throw (::com::sun::star::uno::RuntimeException);
    // XDispatchProviderInterceptor
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL getSlaveDispatchProvider(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setSlaveDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& xNewSlaveDispatchProvider ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL getMasterDispatchProvider(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setMasterDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& xNewMasterDispatchProvider ) throw (::com::sun::star::uno::RuntimeException);
};

typedef cppu::WeakComponentImplHelper2  <   ::com::sun::star::beans::XPropertyChangeListener
                                        ,   ::com::sun::star::form::XLoadable
                                        >   BibDataManager_Base;
class BibDataManager
            :public ::comphelper::OMutexAndBroadcastHelper
            ,public BibDataManager_Base
{
private:
        ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm >                       m_xForm;
        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >                m_xGridModel;
        ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >               m_xSourceProps;
        ::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSingleSelectQueryComposer >   m_xParser;
        ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormController >             m_xFormCtrl;
        // #100312# -------------------
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch >      m_xFormDispatch;
        BibInterceptorHelper* m_pInterceptorHelper;

        ::rtl::OUString                     aActiveDataTable;
        ::rtl::OUString                     aDataSourceURL;
        ::rtl::OUString                     aQuoteChar;
        ::com::sun::star::uno::Any                      aUID;
        ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet >              xBibCursor;

        ::cppu::OInterfaceContainerHelper   m_aLoadListeners;

        ::bib::BibView*             pBibView;
        BibToolBar*                 pToolbar;

        rtl::OUString               sIdentifierMapping;
protected:

        void                        InsertFields(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormComponent > & xGrid);
        void                        SetMeAsUidListener();
        void                        RemoveMeAsUidListener();

        void                        UpdateAddressbookCursor(::rtl::OUString aSourceName);

        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >
                                    updateGridModel(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm > & xDbForm);
        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >
                                    createGridModel( const ::rtl::OUString& rName );

        // XLoadable
        virtual void SAL_CALL load(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL unload(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL reload(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isLoaded(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL addLoadListener( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XLoadListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL removeLoadListener( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XLoadListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);

        virtual void SAL_CALL disposing();

public:

        BibDataManager();
        ~BibDataManager();

        virtual void                SAL_CALL propertyChange(const ::com::sun::star::beans::PropertyChangeEvent& evt)
                                                                throw( ::com::sun::star::uno::RuntimeException );
        virtual void                SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source )
                                                                throw( ::com::sun::star::uno::RuntimeException );

        ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm >                   createDatabaseForm( BibDBDescriptor&    aDesc);

        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >            updateGridModel();

        ::com::sun::star::uno::Sequence< ::rtl::OUString>           getDataSources();

        ::rtl::OUString             getActiveDataSource() {return aDataSourceURL;}
        void                        setActiveDataSource(const ::rtl::OUString& rURL);

        ::rtl::OUString             getActiveDataTable();
        void                        setActiveDataTable(const ::rtl::OUString& rTable);

        void                        setFilter(const ::rtl::OUString& rQuery);
        ::rtl::OUString                     getFilter();

        ::com::sun::star::uno::Sequence< ::rtl::OUString>           getQueryFields();
        ::rtl::OUString                     getQueryField();
        void                        startQueryWith(const ::rtl::OUString& rQuery);

        const ::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSingleSelectQueryComposer >&    getParser() { return m_xParser; }
        const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm >&                        getForm()   { return m_xForm; }

        ::rtl::OUString                     getControlName(sal_Int32 nFormatKey );

        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >            loadControlModel(const ::rtl::OUString& rName,
                                                        sal_Bool bForceListBox = sal_False);
        void                        saveCtrModel(const ::rtl::OUString& rName,
                                                    const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > & rCtrModel);

        sal_Bool                        moveRelative(sal_Int32 nMove);

        void                        CreateMappingDialog(Window* pParent);
        ::rtl::OUString             CreateDBChangeDialog(Window* pParent);

        void                        DispatchDBChangeDialog();
        sal_Bool                    HasActiveConnection() const;

        void                        SetView( ::bib::BibView* pView ) { pBibView = pView; }

        void                        SetToolbar(BibToolBar* pSet);

        const rtl::OUString&        GetIdentifierMapping();
        void                        ResetIdentifierMapping() {sIdentifierMapping = rtl::OUString();}

        ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormController > GetFormController();
        // #100312# ----------
        void RegisterInterceptor( ::bib::BibBeamer* pBibBeamer);

        sal_Bool                    HasActiveConnection();
};

#endif
<commit_msg>INTEGRATION: CWS mba30patches01 (1.15.40); FILE MERGED 2008/04/23 10:48:20 mba 1.15.40.2: RESYNC: (1.15-1.16); FILE MERGED 2008/03/18 15:40:52 mba 1.15.40.1: #i86365#: remove unused code<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: datman.hxx,v $
 * $Revision: 1.17 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _BIB_DATMAN_HXX
#define _BIB_DATMAN_HXX

#include <com/sun/star/awt/XControlModel.hpp>
#include <com/sun/star/form/XForm.hpp>
#include <com/sun/star/sdbc/XResultSet.hpp>
#include <com/sun/star/sdb/XSingleSelectQueryComposer.hpp>
#include <com/sun/star/form/XFormController.hpp>
#include <cppuhelper/compbase2.hxx>
#include <cppuhelper/interfacecontainer.h>
#include <com/sun/star/form/XLoadable.hpp>
#include <comphelper/broadcasthelper.hxx>
// #100312# --------------------
#include <com/sun/star/frame/XDispatchProviderInterceptor.hpp>
#include <com/sun/star/frame/XDispatchProviderInterception.hpp>
#include <cppuhelper/implbase1.hxx>

class Window;

//-----------------------------------------------------------------------------
namespace bib
{
    class BibView;
    // #100312# -----------
    class BibBeamer;
}

class BibToolBar;
struct BibDBDescriptor;

// #100312# ---------------------
class BibInterceptorHelper
    :public cppu::WeakImplHelper1< ::com::sun::star::frame::XDispatchProviderInterceptor >
{
private:
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > xMasterDispatchProvider;
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > xSlaveDispatchProvider;
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xFormDispatch;
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProviderInterception > xInterception;

protected:
    ~BibInterceptorHelper( );

public:
    BibInterceptorHelper( ::bib::BibBeamer* pBibBeamer, ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xDispatch);

    void ReleaseInterceptor();

    // XDispatchProvider
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > SAL_CALL queryDispatch( const ::com::sun::star::util::URL& aURL, const ::rtl::OUString& aTargetFrameName, sal_Int32 nSearchFlags ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > > SAL_CALL queryDispatches( const ::com::sun::star::uno::Sequence< ::com::sun::star::frame::DispatchDescriptor >& aDescripts ) throw (::com::sun::star::uno::RuntimeException);
    // XDispatchProviderInterceptor
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL getSlaveDispatchProvider(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setSlaveDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& xNewSlaveDispatchProvider ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL getMasterDispatchProvider(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setMasterDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& xNewMasterDispatchProvider ) throw (::com::sun::star::uno::RuntimeException);
};

typedef cppu::WeakComponentImplHelper2  <   ::com::sun::star::beans::XPropertyChangeListener
                                        ,   ::com::sun::star::form::XLoadable
                                        >   BibDataManager_Base;
class BibDataManager
            :public ::comphelper::OMutexAndBroadcastHelper
            ,public BibDataManager_Base
{
private:
        ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm >                       m_xForm;
        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >                m_xGridModel;
        ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >               m_xSourceProps;
        ::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSingleSelectQueryComposer >   m_xParser;
        ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormController >             m_xFormCtrl;
        // #100312# -------------------
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch >      m_xFormDispatch;
        BibInterceptorHelper* m_pInterceptorHelper;

        ::rtl::OUString                     aActiveDataTable;
        ::rtl::OUString                     aDataSourceURL;
        ::rtl::OUString                     aQuoteChar;
        ::com::sun::star::uno::Any                      aUID;
        ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet >              xBibCursor;

        ::cppu::OInterfaceContainerHelper   m_aLoadListeners;

        ::bib::BibView*             pBibView;
        BibToolBar*                 pToolbar;

        rtl::OUString               sIdentifierMapping;
protected:

        void                        InsertFields(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormComponent > & xGrid);
        void                        SetMeAsUidListener();
        void                        RemoveMeAsUidListener();

        void                        UpdateAddressbookCursor(::rtl::OUString aSourceName);

        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >
                                    updateGridModel(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm > & xDbForm);
        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >
                                    createGridModel( const ::rtl::OUString& rName );

        // XLoadable
        virtual void SAL_CALL load(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL unload(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL reload(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isLoaded(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL addLoadListener( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XLoadListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL removeLoadListener( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XLoadListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);

        virtual void SAL_CALL disposing();

public:

        BibDataManager();
        ~BibDataManager();

        virtual void                SAL_CALL propertyChange(const ::com::sun::star::beans::PropertyChangeEvent& evt)
                                                                throw( ::com::sun::star::uno::RuntimeException );
        virtual void                SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source )
                                                                throw( ::com::sun::star::uno::RuntimeException );

        ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm >                   createDatabaseForm( BibDBDescriptor&    aDesc);

        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >            updateGridModel();

        ::com::sun::star::uno::Sequence< ::rtl::OUString>           getDataSources();

        ::rtl::OUString             getActiveDataSource() {return aDataSourceURL;}
        void                        setActiveDataSource(const ::rtl::OUString& rURL);

        ::rtl::OUString             getActiveDataTable();
        void                        setActiveDataTable(const ::rtl::OUString& rTable);

        void                        setFilter(const ::rtl::OUString& rQuery);
        ::rtl::OUString                     getFilter();

        ::com::sun::star::uno::Sequence< ::rtl::OUString>           getQueryFields();
        ::rtl::OUString                     getQueryField();
        void                        startQueryWith(const ::rtl::OUString& rQuery);

        const ::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSingleSelectQueryComposer >&    getParser() { return m_xParser; }
        const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm >&                        getForm()   { return m_xForm; }

        ::rtl::OUString                     getControlName(sal_Int32 nFormatKey );

        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >            loadControlModel(const ::rtl::OUString& rName,
                                                        sal_Bool bForceListBox = sal_False);

        void                        CreateMappingDialog(Window* pParent);
        ::rtl::OUString             CreateDBChangeDialog(Window* pParent);

        void                        DispatchDBChangeDialog();
        sal_Bool                    HasActiveConnection() const;

        void                        SetView( ::bib::BibView* pView ) { pBibView = pView; }

        void                        SetToolbar(BibToolBar* pSet);

        const rtl::OUString&        GetIdentifierMapping();
        void                        ResetIdentifierMapping() {sIdentifierMapping = rtl::OUString();}

        ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormController > GetFormController();
        // #100312# ----------
        void RegisterInterceptor( ::bib::BibBeamer* pBibBeamer);

        sal_Bool                    HasActiveConnection();
};

#endif
<|endoftext|>


<commit_before>#pragma once

#include <stdint.h>

/** @file bts/blockchain/config.hpp
 *  @brief Defines global constants that determine blockchain behavior
 */
#define BTS_BLOCKCHAIN_VERSION                      (103)
#define BTS_WALLET_VERSION                          (100)
#define BTS_BLOCKCHAIN_DATABASE_VERSION             (105)

#define BTS_NETWORK_DEFAULT_P2P_PORT                8763

/**
 *  The address prepended to string representation of
 *  addresses.
 *
 *  Changing these parameters will result in a hard fork.
 */
#define BTS_ADDRESS_PREFIX                              "XTS"
#define BTS_BLOCKCHAIN_SYMBOL                           "XTS"
#define BTS_BLOCKCHAIN_NAME                             "BitShares XTS"
#define BTS_BLOCKCHAIN_DESCRIPTION                      "Stake in future BitShares X chains"
#define BTS_BLOCKCHAIN_PRECISION                        (10000)

/**
 * The number of delegates that the blockchain is designed to support
 */
#define BTS_BLOCKCHAIN_NUM_DELEGATES                (101)
#define BTS_BLOCKCHAIN_MAX_SLATE_SIZE               (BTS_BLOCKCHAIN_NUM_DELEGATES/3)

/**
 * To prevent a delegate from producing blocks on split network,
 * we check the connection count.  This means no blocks get produced
 * until at least a minimum number of clients are on line.
 */
#define BTS_MIN_DELEGATE_CONNECTION_COUNT               (5)

/**
 * Defines the number of seconds that should elapse between blocks
 */
#define BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC           int64_t(30)

/**
 *  The maximum size of the raw data contained in the blockchain, this size is
 *  notional based upon the serilized size of all user-generated transactions in
 *  all blocks for one year.
 *
 *  Actual size on disk will likely be 2 or 3x this size due to indexes and other
 *  storeage overhead.
 *
 *  Adjusting this value will change the effective fee charged on transactions
 */
#define BTS_BLOCKCHAIN_MAX_SIZE                         (1024*1024*1024*100ll) // 100 GB
#define BTS_BLOCKCHAIN_MIN_NAME_SIZE                    (1)
#define BTS_BLOCKCHAIN_MAX_NAME_SIZE                    (63)
#define BTS_BLOCKCHAIN_MAX_NAME_DATA_SIZE               (1024*64)
#define BTS_BLOCKCHAIN_MAX_MEMO_SIZE                    (19) // bytes
#define BTS_BLOCKCHAIN_MAX_SYMBOL_SIZE                  (5) // characters
#define BTS_BLOCKCHAIN_MIN_SYMBOL_SIZE                  (3) // characters
#define BTS_BLOCKCHAIN_PROPOSAL_VOTE_MESSAGE_MAX_SIZE   (1024) // bytes

/**
 *  The maximum amount that can be issued for user assets.
 *
 *  10^18 / 2^63 < 1
 */
#define BTS_BLOCKCHAIN_MAX_SHARES                       (1000*1000*1000ll*1000*1000ll)

/**
 * Initial shares read from the genesis block are scaled to this number. It is divided
 * by 100 so that new shares may be issued without exceeding BTS_BLOCKCHAIN_MAX_SHARES
 */
#define BTS_BLOCKCHAIN_INITIAL_SHARES                   (BTS_BLOCKCHAIN_MAX_SHARES / 5)

/**
 *  The number of blocks expected per hour based upon the BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC
 */
#define BTS_BLOCKCHAIN_BLOCKS_PER_HOUR                  ((60*60)/BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC)

/**
 *  The number of blocks expected per day based upon the BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC
 */
#define BTS_BLOCKCHAIN_BLOCKS_PER_DAY                   (BTS_BLOCKCHAIN_BLOCKS_PER_HOUR*24ll)

/**
 * The number of blocks expected per year based upon the BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC
 */
#define BTS_BLOCKCHAIN_BLOCKS_PER_YEAR                  (BTS_BLOCKCHAIN_BLOCKS_PER_DAY*365ll)

/** defines the maximum block size allowed, 24 MB per hour */
#define BTS_BLOCKCHAIN_MAX_BLOCK_SIZE                   (24 * 1024*1024 / BTS_BLOCKCHAIN_BLOCKS_PER_HOUR)

/** defines the target block size, fees will be adjusted to maintain this target */
#define BTS_BLOCKCHAIN_TARGET_BLOCK_SIZE                (BTS_BLOCKCHAIN_MAX_BLOCK_SIZE/2)

#define BTS_BLOCKCHAIN_BLOCK_REWARD                     (BTS_BLOCKCHAIN_MAX_BLOCK_SIZE) //10000 // (BTS_BLOCKCHAIN_INITIAL_SHARES/BTS_BLOCKCHAIN_BLOCKS_PER_YEAR)
#define BTS_BLOCKCHAIN_INACTIVE_FEE_APR                 (10)  // 10% per year

/**
 *  defines the min fee in milli-shares per byte
 */
#define BTS_BLOCKCHAIN_MIN_FEE                          (1000)

/**
 *  Defined so that a delegate must produce 100 blocks to break even.
 */
#define BTS_BLOCKCHAIN_DELEGATE_REGISTRATION_FEE        (BTS_BLOCKCHAIN_BLOCK_REWARD*100)

/**
 *  Defines the fee required to register a asset, this fee is set to discourage anyone from
 *  registering all of the symbols.  If the asset is not worth at least 100 blocks worth
 *  of mining fees then it really isn't worth the networks time.
 */
#define BTS_BLOCKCHAIN_ASSET_REGISTRATION_FEE           (BTS_BLOCKCHAIN_BLOCK_REWARD*100)
<commit_msg>reduce asset creation and delegate registration costs by 99%<commit_after>#pragma once

#include <stdint.h>

/** @file bts/blockchain/config.hpp
 *  @brief Defines global constants that determine blockchain behavior
 */
#define BTS_BLOCKCHAIN_VERSION                      (103)
#define BTS_WALLET_VERSION                          (100)
#define BTS_BLOCKCHAIN_DATABASE_VERSION             (105)

#define BTS_NETWORK_DEFAULT_P2P_PORT                8763

/**
 *  The address prepended to string representation of
 *  addresses.
 *
 *  Changing these parameters will result in a hard fork.
 */
#define BTS_ADDRESS_PREFIX                              "XTS"
#define BTS_BLOCKCHAIN_SYMBOL                           "XTS"
#define BTS_BLOCKCHAIN_NAME                             "BitShares XTS"
#define BTS_BLOCKCHAIN_DESCRIPTION                      "Stake in future BitShares X chains"
#define BTS_BLOCKCHAIN_PRECISION                        (10000)

/**
 * The number of delegates that the blockchain is designed to support
 */
#define BTS_BLOCKCHAIN_NUM_DELEGATES                (101)
#define BTS_BLOCKCHAIN_MAX_SLATE_SIZE               (BTS_BLOCKCHAIN_NUM_DELEGATES/3)

/**
 * To prevent a delegate from producing blocks on split network,
 * we check the connection count.  This means no blocks get produced
 * until at least a minimum number of clients are on line.
 */
#define BTS_MIN_DELEGATE_CONNECTION_COUNT               (5)

/**
 * Defines the number of seconds that should elapse between blocks
 */
#define BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC           int64_t(30)

/**
 *  The maximum size of the raw data contained in the blockchain, this size is
 *  notional based upon the serilized size of all user-generated transactions in
 *  all blocks for one year.
 *
 *  Actual size on disk will likely be 2 or 3x this size due to indexes and other
 *  storeage overhead.
 *
 *  Adjusting this value will change the effective fee charged on transactions
 */
#define BTS_BLOCKCHAIN_MAX_SIZE                         (1024*1024*1024*100ll) // 100 GB
#define BTS_BLOCKCHAIN_MIN_NAME_SIZE                    (1)
#define BTS_BLOCKCHAIN_MAX_NAME_SIZE                    (63)
#define BTS_BLOCKCHAIN_MAX_NAME_DATA_SIZE               (1024*64)
#define BTS_BLOCKCHAIN_MAX_MEMO_SIZE                    (19) // bytes
#define BTS_BLOCKCHAIN_MAX_SYMBOL_SIZE                  (5) // characters
#define BTS_BLOCKCHAIN_MIN_SYMBOL_SIZE                  (3) // characters
#define BTS_BLOCKCHAIN_PROPOSAL_VOTE_MESSAGE_MAX_SIZE   (1024) // bytes

/**
 *  The maximum amount that can be issued for user assets.
 *
 *  10^18 / 2^63 < 1
 */
#define BTS_BLOCKCHAIN_MAX_SHARES                       (1000*1000*1000ll*1000*1000ll)

/**
 * Initial shares read from the genesis block are scaled to this number. It is divided
 * by 100 so that new shares may be issued without exceeding BTS_BLOCKCHAIN_MAX_SHARES
 */
#define BTS_BLOCKCHAIN_INITIAL_SHARES                   (BTS_BLOCKCHAIN_MAX_SHARES / 5)

/**
 *  The number of blocks expected per hour based upon the BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC
 */
#define BTS_BLOCKCHAIN_BLOCKS_PER_HOUR                  ((60*60)/BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC)

/**
 *  The number of blocks expected per day based upon the BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC
 */
#define BTS_BLOCKCHAIN_BLOCKS_PER_DAY                   (BTS_BLOCKCHAIN_BLOCKS_PER_HOUR*24ll)

/**
 * The number of blocks expected per year based upon the BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC
 */
#define BTS_BLOCKCHAIN_BLOCKS_PER_YEAR                  (BTS_BLOCKCHAIN_BLOCKS_PER_DAY*365ll)

/** defines the maximum block size allowed, 24 MB per hour */
#define BTS_BLOCKCHAIN_MAX_BLOCK_SIZE                   (24 * 1024*1024 / BTS_BLOCKCHAIN_BLOCKS_PER_HOUR)

/** defines the target block size, fees will be adjusted to maintain this target */
#define BTS_BLOCKCHAIN_TARGET_BLOCK_SIZE                (BTS_BLOCKCHAIN_MAX_BLOCK_SIZE/2)

#define BTS_BLOCKCHAIN_BLOCK_REWARD                     (BTS_BLOCKCHAIN_MAX_BLOCK_SIZE) //10000 // (BTS_BLOCKCHAIN_INITIAL_SHARES/BTS_BLOCKCHAIN_BLOCKS_PER_YEAR)
#define BTS_BLOCKCHAIN_INACTIVE_FEE_APR                 (10)  // 10% per year

/**
 *  defines the min fee in milli-shares per byte
 */
#define BTS_BLOCKCHAIN_MIN_FEE                          (1000)

/**
 *  Defined so that a delegate must produce 100 blocks to break even.
 */
#define BTS_BLOCKCHAIN_DELEGATE_REGISTRATION_FEE        (BTS_BLOCKCHAIN_BLOCK_REWARD)

/**
 *  Defines the fee required to register a asset, this fee is set to discourage anyone from
 *  registering all of the symbols.  If the asset is not worth at least 100 blocks worth
 *  of mining fees then it really isn't worth the networks time.
 */
#define BTS_BLOCKCHAIN_ASSET_REGISTRATION_FEE           (BTS_BLOCKCHAIN_BLOCK_REWARD)
<|endoftext|>