<commit_before>#include "progress-bar.hh"
#include "util.hh"
#include "sync.hh"
#include "store-api.hh"

#include <atomic>
#include <map>
#include <thread>

namespace nix {

static std::string getS(const std::vector<Logger::Field> & fields, size_t n)
{
    assert(n < fields.size());
    assert(fields[n].type == Logger::Field::tString);
    return fields[n].s;
}

static uint64_t getI(const std::vector<Logger::Field> & fields, size_t n)
{
    assert(n < fields.size());
    assert(fields[n].type == Logger::Field::tInt);
    return fields[n].i;
}

class ProgressBar : public Logger
{
private:

    struct ActInfo
    {
        std::string s, lastLine, phase;
        ActivityType type = actUnknown;
        uint64_t done = 0;
        uint64_t expected = 0;
        uint64_t running = 0;
        uint64_t failed = 0;
        std::map<ActivityType, uint64_t> expectedByType;
        bool visible = true;
        ActivityId parent;
    };

    struct ActivitiesByType
    {
        std::map<ActivityId, std::list<ActInfo>::iterator> its;
        uint64_t done = 0;
        uint64_t expected = 0;
        uint64_t failed = 0;
    };

    struct State
    {
        std::list<ActInfo> activities;
        std::map<ActivityId, std::list<ActInfo>::iterator> its;

        std::map<ActivityType, ActivitiesByType> activitiesByType;

        uint64_t filesLinked = 0, bytesLinked = 0;

        uint64_t corruptedPaths = 0, untrustedPaths = 0;

        bool active = true;
    };

    Sync<State> state_;

    std::thread updateThread;

    std::condition_variable quitCV, updateCV;

public:

    ProgressBar()
    {
        updateThread = std::thread([&]() {
            auto state(state_.lock());
            while (state->active) {
                state.wait(updateCV);
                draw(*state);
                state.wait_for(quitCV, std::chrono::milliseconds(50));
            }
        });
    }

    ~ProgressBar()
    {
        stop();
        updateThread.join();
    }

    void stop()
    {
        auto state(state_.lock());
        if (!state->active) return;
        state->active = false;
        std::string status = getStatus(*state);
        writeToStderr("\r\e[K");
        if (status != "")
            writeToStderr("[" + status + "]\n");
        updateCV.notify_one();
        quitCV.notify_one();
    }

    void log(Verbosity lvl, const FormatOrString & fs) override
    {
        auto state(state_.lock());
        log(*state, lvl, fs.s);
    }

    void log(State & state, Verbosity lvl, const std::string & s)
    {
        writeToStderr("\r\e[K" + s + ANSI_NORMAL "\n");
        draw(state);
    }

    void startActivity(ActivityId act, Verbosity lvl, ActivityType type,
        const std::string & s, const Fields & fields, ActivityId parent) override
    {
        auto state(state_.lock());

        if (lvl <= verbosity && !s.empty())
            log(*state, lvl, s + "...");

        state->activities.emplace_back(ActInfo());
        auto i = std::prev(state->activities.end());
        i->s = s;
        i->type = type;
        i->parent = parent;
        state->its.emplace(act, i);
        state->activitiesByType[type].its.emplace(act, i);

        if (type == actBuild) {
            auto name = storePathToName(getS(fields, 0));
            if (hasSuffix(name, ".drv"))
                name.resize(name.size() - 4);
            i->s = fmt("building " ANSI_BOLD "%s" ANSI_NORMAL, name);
            auto machineName = getS(fields, 1);
            if (machineName != "")
                i->s += fmt(" on " ANSI_BOLD "%s" ANSI_NORMAL, machineName);
            auto curRound = getI(fields, 2);
            auto nrRounds = getI(fields, 3);
            if (nrRounds != 1)
                i->s += fmt(" (round %d/%d)", curRound, nrRounds);
        }

        if (type == actSubstitute) {
            auto name = storePathToName(getS(fields, 0));
            auto sub = getS(fields, 1);
            i->s = fmt(
                hasPrefix(sub, "local")
                ? "copying " ANSI_BOLD "%s" ANSI_NORMAL " from %s"
                : "fetching " ANSI_BOLD "%s" ANSI_NORMAL " from %s",
                name, sub);
        }

        if (type == actQueryPathInfo) {
            auto name = storePathToName(getS(fields, 0));
            i->s = fmt("querying " ANSI_BOLD "%s" ANSI_NORMAL " on %s", name, getS(fields, 1));
        }

        if ((type == actDownload && hasAncestor(*state, actCopyPath, parent))
            || (type == actDownload && hasAncestor(*state, actQueryPathInfo, parent))
            || (type == actCopyPath && hasAncestor(*state, actSubstitute, parent)))
            i->visible = false;

        update();
    }

    /* Check whether an activity has an ancestore with the specified
       type. */
    bool hasAncestor(State & state, ActivityType type, ActivityId act)
    {
        while (act != 0) {
            auto i = state.its.find(act);
            if (i == state.its.end()) break;
            if (i->second->type == type) return true;
            act = i->second->parent;
        }
        return false;
    }

    void stopActivity(ActivityId act) override
    {
        auto state(state_.lock());

        auto i = state->its.find(act);
        if (i != state->its.end()) {

            auto & actByType = state->activitiesByType[i->second->type];
            actByType.done += i->second->done;
            actByType.failed += i->second->failed;

            for (auto & j : i->second->expectedByType)
                state->activitiesByType[j.first].expected -= j.second;

            actByType.its.erase(act);
            state->activities.erase(i->second);
            state->its.erase(i);
        }

        update();
    }

    void result(ActivityId act, ResultType type, const std::vector<Field> & fields) override
    {
        auto state(state_.lock());

        if (type == resFileLinked) {
            state->filesLinked++;
            state->bytesLinked += getI(fields, 0);
            update();
        }

        else if (type == resBuildLogLine) {
            auto lastLine = trim(getS(fields, 0));
            if (!lastLine.empty()) {
                auto i = state->its.find(act);
                assert(i != state->its.end());
                ActInfo info = *i->second;
                state->activities.erase(i->second);
                info.lastLine = lastLine;
                state->activities.emplace_back(info);
                i->second = std::prev(state->activities.end());
                update();
            }
        }

        else if (type == resUntrustedPath) {
            state->untrustedPaths++;
            update();
        }

        else if (type == resCorruptedPath) {
            state->corruptedPaths++;
            update();
        }

        else if (type == resSetPhase) {
            auto i = state->its.find(act);
            assert(i != state->its.end());
            i->second->phase = getS(fields, 0);
            update();
        }

        else if (type == resProgress) {
            auto i = state->its.find(act);
            assert(i != state->its.end());
            ActInfo & actInfo = *i->second;
            actInfo.done = getI(fields, 0);
            actInfo.expected = getI(fields, 1);
            actInfo.running = getI(fields, 2);
            actInfo.failed = getI(fields, 3);
            update();
        }

        else if (type == resSetExpected) {
            auto i = state->its.find(act);
            assert(i != state->its.end());
            ActInfo & actInfo = *i->second;
            auto type = (ActivityType) getI(fields, 0);
            auto & j = actInfo.expectedByType[type];
            state->activitiesByType[type].expected -= j;
            j = getI(fields, 1);
            state->activitiesByType[type].expected += j;
            update();
        }
    }

    void update()
    {
        updateCV.notify_one();
    }

    void draw(State & state)
    {
        if (!state.active) return;

        std::string line;

        std::string status = getStatus(state);
        if (!status.empty()) {
            line += '[';
            line += status;
            line += "]";
        }

        if (!state.activities.empty()) {
            if (!status.empty()) line += " ";
            auto i = state.activities.rbegin();

            while (i != state.activities.rend() && (!i->visible || (i->s.empty() && i->lastLine.empty())))
                ++i;

            if (i != state.activities.rend()) {
                line += i->s;
                if (!i->phase.empty()) {
                    line += " (";
                    line += i->phase;
                    line += ")";
                }
                if (!i->lastLine.empty()) {
                    if (!i->s.empty()) line += ": ";
                    line += i->lastLine;
                }
            }
        }

        auto width = getWindowSize().second;
        if (width <= 0) std::numeric_limits<decltype(width)>::max();

        writeToStderr("\r" + filterANSIEscapes(line, false, width) + "\e[K");
    }

    std::string getStatus(State & state)
    {
        auto MiB = 1024.0 * 1024.0;

        std::string res;

        auto renderActivity = [&](ActivityType type, const std::string & itemFmt, const std::string & numberFmt = "%d", double unit = 1) {
            auto & act = state.activitiesByType[type];
            uint64_t done = act.done, expected = act.done, running = 0, failed = act.failed;
            for (auto & j : act.its) {
                done += j.second->done;
                expected += j.second->expected;
                running += j.second->running;
                failed += j.second->failed;
            }

            expected = std::max(expected, act.expected);

            std::string s;

            if (running || done || expected || failed) {
                if (running)
                    s = fmt(ANSI_BLUE + numberFmt + ANSI_NORMAL "/" ANSI_GREEN + numberFmt + ANSI_NORMAL "/" + numberFmt,
                        running / unit, done / unit, expected / unit);
                else if (expected != done)
                    s = fmt(ANSI_GREEN + numberFmt + ANSI_NORMAL "/" + numberFmt,
                        done / unit, expected / unit);
                else
                    s = fmt(done ? ANSI_GREEN + numberFmt + ANSI_NORMAL : numberFmt, done / unit);
                s = fmt(itemFmt, s);

                if (failed)
                    s += fmt(" (" ANSI_RED "%d failed" ANSI_NORMAL ")", failed / unit);
            }

            return s;
        };

        auto showActivity = [&](ActivityType type, const std::string & itemFmt, const std::string & numberFmt = "%d", double unit = 1) {
            auto s = renderActivity(type, itemFmt, numberFmt, unit);
            if (s.empty()) return;
            if (!res.empty()) res += ", ";
            res += s;
        };

        showActivity(actBuilds, "%s built");

        auto s1 = renderActivity(actCopyPaths, "%s copied");
        auto s2 = renderActivity(actCopyPath, "%s MiB", "%.1f", MiB);

        if (!s1.empty() || !s2.empty()) {
            if (!res.empty()) res += ", ";
            if (s1.empty()) res += "0 copied"; else res += s1;
            if (!s2.empty()) { res += " ("; res += s2; res += ')'; }
        }

        showActivity(actDownload, "%s MiB DL", "%.1f", MiB);

        {
            auto s = renderActivity(actOptimiseStore, "%s paths optimised");
            if (s != "") {
                s += fmt(", %.1f MiB / %d inodes freed", state.bytesLinked / MiB, state.filesLinked);
                if (!res.empty()) res += ", ";
                res += s;
            }
        }

        // FIXME: don't show "done" paths in green.
        showActivity(actVerifyPaths, "%s paths verified");

        if (state.corruptedPaths) {
            if (!res.empty()) res += ", ";
            res += fmt(ANSI_RED "%d corrupted" ANSI_NORMAL, state.corruptedPaths);
        }

        if (state.untrustedPaths) {
            if (!res.empty()) res += ", ";
            res += fmt(ANSI_RED "%d untrusted" ANSI_NORMAL, state.untrustedPaths);
        }

        return res;
    }
};

void startProgressBar()
{
    logger = new ProgressBar();
}

void stopProgressBar()
{
    auto progressBar = dynamic_cast<ProgressBar *>(logger);
    if (progressBar) progressBar->stop();

}

}
<commit_msg>progress-bar: re-draw last update if nothing new for 1sec.<commit_after>#include "progress-bar.hh"
#include "util.hh"
#include "sync.hh"
#include "store-api.hh"

#include <atomic>
#include <map>
#include <thread>

namespace nix {

static std::string getS(const std::vector<Logger::Field> & fields, size_t n)
{
    assert(n < fields.size());
    assert(fields[n].type == Logger::Field::tString);
    return fields[n].s;
}

static uint64_t getI(const std::vector<Logger::Field> & fields, size_t n)
{
    assert(n < fields.size());
    assert(fields[n].type == Logger::Field::tInt);
    return fields[n].i;
}

class ProgressBar : public Logger
{
private:

    struct ActInfo
    {
        std::string s, lastLine, phase;
        ActivityType type = actUnknown;
        uint64_t done = 0;
        uint64_t expected = 0;
        uint64_t running = 0;
        uint64_t failed = 0;
        std::map<ActivityType, uint64_t> expectedByType;
        bool visible = true;
        ActivityId parent;
    };

    struct ActivitiesByType
    {
        std::map<ActivityId, std::list<ActInfo>::iterator> its;
        uint64_t done = 0;
        uint64_t expected = 0;
        uint64_t failed = 0;
    };

    struct State
    {
        std::list<ActInfo> activities;
        std::map<ActivityId, std::list<ActInfo>::iterator> its;

        std::map<ActivityType, ActivitiesByType> activitiesByType;

        uint64_t filesLinked = 0, bytesLinked = 0;

        uint64_t corruptedPaths = 0, untrustedPaths = 0;

        bool active = true;
    };

    Sync<State> state_;

    std::thread updateThread;

    std::condition_variable quitCV, updateCV;

public:

    ProgressBar()
    {
        updateThread = std::thread([&]() {
            auto state(state_.lock());
            while (state->active) {
                auto r = state.wait_for(updateCV, std::chrono::seconds(1));
                draw(*state);
                if (r == std::cv_status::no_timeout)
                  state.wait_for(quitCV, std::chrono::milliseconds(50));
            }
        });
    }

    ~ProgressBar()
    {
        stop();
        updateThread.join();
    }

    void stop()
    {
        auto state(state_.lock());
        if (!state->active) return;
        state->active = false;
        std::string status = getStatus(*state);
        writeToStderr("\r\e[K");
        if (status != "")
            writeToStderr("[" + status + "]\n");
        updateCV.notify_one();
        quitCV.notify_one();
    }

    void log(Verbosity lvl, const FormatOrString & fs) override
    {
        auto state(state_.lock());
        log(*state, lvl, fs.s);
    }

    void log(State & state, Verbosity lvl, const std::string & s)
    {
        writeToStderr("\r\e[K" + s + ANSI_NORMAL "\n");
        draw(state);
    }

    void startActivity(ActivityId act, Verbosity lvl, ActivityType type,
        const std::string & s, const Fields & fields, ActivityId parent) override
    {
        auto state(state_.lock());

        if (lvl <= verbosity && !s.empty())
            log(*state, lvl, s + "...");

        state->activities.emplace_back(ActInfo());
        auto i = std::prev(state->activities.end());
        i->s = s;
        i->type = type;
        i->parent = parent;
        state->its.emplace(act, i);
        state->activitiesByType[type].its.emplace(act, i);

        if (type == actBuild) {
            auto name = storePathToName(getS(fields, 0));
            if (hasSuffix(name, ".drv"))
                name.resize(name.size() - 4);
            i->s = fmt("building " ANSI_BOLD "%s" ANSI_NORMAL, name);
            auto machineName = getS(fields, 1);
            if (machineName != "")
                i->s += fmt(" on " ANSI_BOLD "%s" ANSI_NORMAL, machineName);
            auto curRound = getI(fields, 2);
            auto nrRounds = getI(fields, 3);
            if (nrRounds != 1)
                i->s += fmt(" (round %d/%d)", curRound, nrRounds);
        }

        if (type == actSubstitute) {
            auto name = storePathToName(getS(fields, 0));
            auto sub = getS(fields, 1);
            i->s = fmt(
                hasPrefix(sub, "local")
                ? "copying " ANSI_BOLD "%s" ANSI_NORMAL " from %s"
                : "fetching " ANSI_BOLD "%s" ANSI_NORMAL " from %s",
                name, sub);
        }

        if (type == actQueryPathInfo) {
            auto name = storePathToName(getS(fields, 0));
            i->s = fmt("querying " ANSI_BOLD "%s" ANSI_NORMAL " on %s", name, getS(fields, 1));
        }

        if ((type == actDownload && hasAncestor(*state, actCopyPath, parent))
            || (type == actDownload && hasAncestor(*state, actQueryPathInfo, parent))
            || (type == actCopyPath && hasAncestor(*state, actSubstitute, parent)))
            i->visible = false;

        update();
    }

    /* Check whether an activity has an ancestore with the specified
       type. */
    bool hasAncestor(State & state, ActivityType type, ActivityId act)
    {
        while (act != 0) {
            auto i = state.its.find(act);
            if (i == state.its.end()) break;
            if (i->second->type == type) return true;
            act = i->second->parent;
        }
        return false;
    }

    void stopActivity(ActivityId act) override
    {
        auto state(state_.lock());

        auto i = state->its.find(act);
        if (i != state->its.end()) {

            auto & actByType = state->activitiesByType[i->second->type];
            actByType.done += i->second->done;
            actByType.failed += i->second->failed;

            for (auto & j : i->second->expectedByType)
                state->activitiesByType[j.first].expected -= j.second;

            actByType.its.erase(act);
            state->activities.erase(i->second);
            state->its.erase(i);
        }

        update();
    }

    void result(ActivityId act, ResultType type, const std::vector<Field> & fields) override
    {
        auto state(state_.lock());

        if (type == resFileLinked) {
            state->filesLinked++;
            state->bytesLinked += getI(fields, 0);
            update();
        }

        else if (type == resBuildLogLine) {
            auto lastLine = trim(getS(fields, 0));
            if (!lastLine.empty()) {
                auto i = state->its.find(act);
                assert(i != state->its.end());
                ActInfo info = *i->second;
                state->activities.erase(i->second);
                info.lastLine = lastLine;
                state->activities.emplace_back(info);
                i->second = std::prev(state->activities.end());
                update();
            }
        }

        else if (type == resUntrustedPath) {
            state->untrustedPaths++;
            update();
        }

        else if (type == resCorruptedPath) {
            state->corruptedPaths++;
            update();
        }

        else if (type == resSetPhase) {
            auto i = state->its.find(act);
            assert(i != state->its.end());
            i->second->phase = getS(fields, 0);
            update();
        }

        else if (type == resProgress) {
            auto i = state->its.find(act);
            assert(i != state->its.end());
            ActInfo & actInfo = *i->second;
            actInfo.done = getI(fields, 0);
            actInfo.expected = getI(fields, 1);
            actInfo.running = getI(fields, 2);
            actInfo.failed = getI(fields, 3);
            update();
        }

        else if (type == resSetExpected) {
            auto i = state->its.find(act);
            assert(i != state->its.end());
            ActInfo & actInfo = *i->second;
            auto type = (ActivityType) getI(fields, 0);
            auto & j = actInfo.expectedByType[type];
            state->activitiesByType[type].expected -= j;
            j = getI(fields, 1);
            state->activitiesByType[type].expected += j;
            update();
        }
    }

    void update()
    {
        updateCV.notify_one();
    }

    void draw(State & state)
    {
        if (!state.active) return;

        std::string line;

        std::string status = getStatus(state);
        if (!status.empty()) {
            line += '[';
            line += status;
            line += "]";
        }

        if (!state.activities.empty()) {
            if (!status.empty()) line += " ";
            auto i = state.activities.rbegin();

            while (i != state.activities.rend() && (!i->visible || (i->s.empty() && i->lastLine.empty())))
                ++i;

            if (i != state.activities.rend()) {
                line += i->s;
                if (!i->phase.empty()) {
                    line += " (";
                    line += i->phase;
                    line += ")";
                }
                if (!i->lastLine.empty()) {
                    if (!i->s.empty()) line += ": ";
                    line += i->lastLine;
                }
            }
        }

        auto width = getWindowSize().second;
        if (width <= 0) std::numeric_limits<decltype(width)>::max();

        writeToStderr("\r" + filterANSIEscapes(line, false, width) + "\e[K");
    }

    std::string getStatus(State & state)
    {
        auto MiB = 1024.0 * 1024.0;

        std::string res;

        auto renderActivity = [&](ActivityType type, const std::string & itemFmt, const std::string & numberFmt = "%d", double unit = 1) {
            auto & act = state.activitiesByType[type];
            uint64_t done = act.done, expected = act.done, running = 0, failed = act.failed;
            for (auto & j : act.its) {
                done += j.second->done;
                expected += j.second->expected;
                running += j.second->running;
                failed += j.second->failed;
            }

            expected = std::max(expected, act.expected);

            std::string s;

            if (running || done || expected || failed) {
                if (running)
                    s = fmt(ANSI_BLUE + numberFmt + ANSI_NORMAL "/" ANSI_GREEN + numberFmt + ANSI_NORMAL "/" + numberFmt,
                        running / unit, done / unit, expected / unit);
                else if (expected != done)
                    s = fmt(ANSI_GREEN + numberFmt + ANSI_NORMAL "/" + numberFmt,
                        done / unit, expected / unit);
                else
                    s = fmt(done ? ANSI_GREEN + numberFmt + ANSI_NORMAL : numberFmt, done / unit);
                s = fmt(itemFmt, s);

                if (failed)
                    s += fmt(" (" ANSI_RED "%d failed" ANSI_NORMAL ")", failed / unit);
            }

            return s;
        };

        auto showActivity = [&](ActivityType type, const std::string & itemFmt, const std::string & numberFmt = "%d", double unit = 1) {
            auto s = renderActivity(type, itemFmt, numberFmt, unit);
            if (s.empty()) return;
            if (!res.empty()) res += ", ";
            res += s;
        };

        showActivity(actBuilds, "%s built");

        auto s1 = renderActivity(actCopyPaths, "%s copied");
        auto s2 = renderActivity(actCopyPath, "%s MiB", "%.1f", MiB);

        if (!s1.empty() || !s2.empty()) {
            if (!res.empty()) res += ", ";
            if (s1.empty()) res += "0 copied"; else res += s1;
            if (!s2.empty()) { res += " ("; res += s2; res += ')'; }
        }

        showActivity(actDownload, "%s MiB DL", "%.1f", MiB);

        {
            auto s = renderActivity(actOptimiseStore, "%s paths optimised");
            if (s != "") {
                s += fmt(", %.1f MiB / %d inodes freed", state.bytesLinked / MiB, state.filesLinked);
                if (!res.empty()) res += ", ";
                res += s;
            }
        }

        // FIXME: don't show "done" paths in green.
        showActivity(actVerifyPaths, "%s paths verified");

        if (state.corruptedPaths) {
            if (!res.empty()) res += ", ";
            res += fmt(ANSI_RED "%d corrupted" ANSI_NORMAL, state.corruptedPaths);
        }

        if (state.untrustedPaths) {
            if (!res.empty()) res += ", ";
            res += fmt(ANSI_RED "%d untrusted" ANSI_NORMAL, state.untrustedPaths);
        }

        return res;
    }
};

void startProgressBar()
{
    logger = new ProgressBar();
}

void stopProgressBar()
{
    auto progressBar = dynamic_cast<ProgressBar *>(logger);
    if (progressBar) progressBar->stop();

}

}
<|endoftext|>


<commit_before>/* libs/graphics/sgl/SkShader.cpp
**
** Copyright 2006, The Android Open Source Project
**
** 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 "SkShader.h"
#include "SkPaint.h"

SkShader::SkShader() : fLocalMatrix(NULL) {
    SkDEBUGCODE(fInSession = false;)
}

SkShader::SkShader(SkFlattenableReadBuffer& buffer)
        : INHERITED(buffer), fLocalMatrix(NULL) {
    if (buffer.readBool()) {
        SkMatrix matrix;
        buffer.read(&matrix, sizeof(matrix));
        setLocalMatrix(matrix);
    }
    SkDEBUGCODE(fInSession = false;)
}

SkShader::~SkShader() {
    SkASSERT(!fInSession);
    sk_free(fLocalMatrix);
}

void SkShader::beginSession() {
    SkASSERT(!fInSession);
    SkDEBUGCODE(fInSession = true;)
}

void SkShader::endSession() {
    SkASSERT(fInSession);
    SkDEBUGCODE(fInSession = false;)
}

void SkShader::flatten(SkFlattenableWriteBuffer& buffer) {
    this->INHERITED::flatten(buffer);
    buffer.writeBool(fLocalMatrix != NULL);
    if (fLocalMatrix) {
        buffer.writeMul4(fLocalMatrix, sizeof(SkMatrix));
    }
}

bool SkShader::getLocalMatrix(SkMatrix* localM) const {
    if (fLocalMatrix) {
        if (localM) {
            *localM = *fLocalMatrix;
        }
        return true;
    } else {
        if (localM) {
            localM->reset();
        }
        return false;
    }
}

void SkShader::setLocalMatrix(const SkMatrix& localM) {
    if (localM.isIdentity()) {
        this->resetLocalMatrix();
    } else {
        if (fLocalMatrix == NULL) {
            fLocalMatrix = (SkMatrix*)sk_malloc_throw(sizeof(SkMatrix));
        }
        *fLocalMatrix = localM;
    }
}

void SkShader::resetLocalMatrix() {
    if (fLocalMatrix) {
        sk_free(fLocalMatrix);
        fLocalMatrix = NULL;
    }
}

bool SkShader::setContext(const SkBitmap& device,
                          const SkPaint& paint,
                          const SkMatrix& matrix) {
    const SkMatrix* m = &matrix;
    SkMatrix        total;

    fDeviceConfig = SkToU8(device.getConfig());
    fPaintAlpha = paint.getAlpha();
    if (fLocalMatrix) {
        total.setConcat(matrix, *fLocalMatrix);
        m = &total;
    }
    if (m->invert(&fTotalInverse)) {
        fTotalInverseClass = (uint8_t)ComputeMatrixClass(fTotalInverse);
        return true;
    }
    return false;
}

#include "SkColorPriv.h"

void SkShader::shadeSpan16(int x, int y, uint16_t span16[], int count) {
    SkASSERT(span16);
    SkASSERT(count > 0);
    SkASSERT(this->canCallShadeSpan16());

    // basically, if we get here, the subclass screwed up
    SkASSERT(!"kHasSpan16 flag is set, but shadeSpan16() not implemented");
}

#define kTempColorQuadCount 6   // balance between speed (larger) and saving stack-space
#define kTempColorCount     (kTempColorQuadCount << 2)

#ifdef SK_CPU_BENDIAN
    #define SkU32BitShiftToByteOffset(shift)    (3 - ((shift) >> 3))
#else
    #define SkU32BitShiftToByteOffset(shift)    ((shift) >> 3)
#endif

void SkShader::shadeSpanAlpha(int x, int y, uint8_t alpha[], int count) {
    SkASSERT(count > 0);

    SkPMColor   colors[kTempColorCount];

    while ((count -= kTempColorCount) >= 0) {
        this->shadeSpan(x, y, colors, kTempColorCount);
        x += kTempColorCount;

        const uint8_t* srcA = (const uint8_t*)colors + SkU32BitShiftToByteOffset(SK_A32_SHIFT);
        int quads = kTempColorQuadCount;
        do {
            U8CPU a0 = srcA[0];
            U8CPU a1 = srcA[4];
            U8CPU a2 = srcA[8];
            U8CPU a3 = srcA[12];
            srcA += 4*4;
            *alpha++ = SkToU8(a0);
            *alpha++ = SkToU8(a1);
            *alpha++ = SkToU8(a2);
            *alpha++ = SkToU8(a3);
        } while (--quads != 0);
    }
    SkASSERT(count < 0);
    SkASSERT(count + kTempColorCount >= 0);
    if (count += kTempColorCount) {
        this->shadeSpan(x, y, colors, count);

        const uint8_t* srcA = (const uint8_t*)colors + SkU32BitShiftToByteOffset(SK_A32_SHIFT);
        do {
            *alpha++ = *srcA;
            srcA += 4;
        } while (--count != 0);
    }
#if 0
    do {
        int n = count;
        if (n > kTempColorCount)
            n = kTempColorCount;
        SkASSERT(n > 0);

        this->shadeSpan(x, y, colors, n);
        x += n;
        count -= n;

        const uint8_t* srcA = (const uint8_t*)colors + SkU32BitShiftToByteOffset(SK_A32_SHIFT);
        do {
            *alpha++ = *srcA;
            srcA += 4;
        } while (--n != 0);
    } while (count > 0);
#endif
}

SkShader::MatrixClass SkShader::ComputeMatrixClass(const SkMatrix& mat) {
    MatrixClass mc = kLinear_MatrixClass;

    if (mat.getType() & SkMatrix::kPerspective_Mask) {
        if (mat.fixedStepInX(0, NULL, NULL)) {
            mc = kFixedStepInX_MatrixClass;
        } else {
            mc = kPerspective_MatrixClass;
        }
    }
    return mc;
}

//////////////////////////////////////////////////////////////////////////////

bool SkShader::asABitmap(SkBitmap*, SkMatrix*, TileMode*) {
    return false;
}

SkShader* SkShader::CreateBitmapShader(const SkBitmap& src,
                                       TileMode tmx, TileMode tmy) {
    return SkShader::CreateBitmapShader(src, tmx, tmy, NULL, 0);
}

//////////////////////////////////////////////////////////////////////////////

#include "SkColorShader.h"
#include "SkUtils.h"

SkColorShader::SkColorShader(SkFlattenableReadBuffer& b) : INHERITED(b) {
    fFlags = 0; // computed in setContext
    fInheritColor = b.readU8();
    if (fInheritColor) {
        return;
    }
    fColor = b.readU32();
}

void SkColorShader::flatten(SkFlattenableWriteBuffer& buffer) {
    this->INHERITED::flatten(buffer);
    buffer.write8(fInheritColor);
    if (fInheritColor) {
        return;
    }
    buffer.write32(fColor);
}

uint8_t SkColorShader::getSpan16Alpha() const {
    return SkGetPackedA32(fPMColor);
}

bool SkColorShader::setContext(const SkBitmap& device, const SkPaint& paint,
                               const SkMatrix& matrix) {
    if (!this->INHERITED::setContext(device, paint, matrix)) {
        return false;
    }

    SkColor c;
    unsigned a;

    if (fInheritColor) {
        c = paint.getColor();
        a = SkColorGetA(c);
    } else {
        c = fColor;
        a = SkAlphaMul(SkColorGetA(c), SkAlpha255To256(paint.getAlpha()));
    }

    unsigned r = SkColorGetR(c);
    unsigned g = SkColorGetG(c);
    unsigned b = SkColorGetB(c);

    // we want this before we apply any alpha
    fColor16 = SkPack888ToRGB16(r, g, b);

    if (a != 255) {
        r = SkMulDiv255Round(r, a);
        g = SkMulDiv255Round(g, a);
        b = SkMulDiv255Round(b, a);
    }
    fPMColor = SkPackARGB32(a, r, g, b);

    fFlags = kConstInY32_Flag;
    if (paint.isDither() == false) {
        fFlags |= kHasSpan16_Flag;
    }
    if (SkGetPackedA32(fPMColor) == 255) {
        fFlags |= kOpaqueAlpha_Flag;
    }

    return true;
}

void SkColorShader::shadeSpan(int x, int y, SkPMColor span[], int count) {
    sk_memset32(span, fPMColor, count);
}

void SkColorShader::shadeSpan16(int x, int y, uint16_t span[], int count) {
    sk_memset16(span, fColor16, count);
}

void SkColorShader::shadeSpanAlpha(int x, int y, uint8_t alpha[], int count) {
    memset(alpha, SkGetPackedA32(fPMColor), count);
}

<commit_msg>only report hasspan16 if we're opaque, otherwise we get a different blend via 565 than the 8888 case<commit_after>/* libs/graphics/sgl/SkShader.cpp
**
** Copyright 2006, The Android Open Source Project
**
** 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 "SkShader.h"
#include "SkPaint.h"

SkShader::SkShader() : fLocalMatrix(NULL) {
    SkDEBUGCODE(fInSession = false;)
}

SkShader::SkShader(SkFlattenableReadBuffer& buffer)
        : INHERITED(buffer), fLocalMatrix(NULL) {
    if (buffer.readBool()) {
        SkMatrix matrix;
        buffer.read(&matrix, sizeof(matrix));
        setLocalMatrix(matrix);
    }
    SkDEBUGCODE(fInSession = false;)
}

SkShader::~SkShader() {
    SkASSERT(!fInSession);
    sk_free(fLocalMatrix);
}

void SkShader::beginSession() {
    SkASSERT(!fInSession);
    SkDEBUGCODE(fInSession = true;)
}

void SkShader::endSession() {
    SkASSERT(fInSession);
    SkDEBUGCODE(fInSession = false;)
}

void SkShader::flatten(SkFlattenableWriteBuffer& buffer) {
    this->INHERITED::flatten(buffer);
    buffer.writeBool(fLocalMatrix != NULL);
    if (fLocalMatrix) {
        buffer.writeMul4(fLocalMatrix, sizeof(SkMatrix));
    }
}

bool SkShader::getLocalMatrix(SkMatrix* localM) const {
    if (fLocalMatrix) {
        if (localM) {
            *localM = *fLocalMatrix;
        }
        return true;
    } else {
        if (localM) {
            localM->reset();
        }
        return false;
    }
}

void SkShader::setLocalMatrix(const SkMatrix& localM) {
    if (localM.isIdentity()) {
        this->resetLocalMatrix();
    } else {
        if (fLocalMatrix == NULL) {
            fLocalMatrix = (SkMatrix*)sk_malloc_throw(sizeof(SkMatrix));
        }
        *fLocalMatrix = localM;
    }
}

void SkShader::resetLocalMatrix() {
    if (fLocalMatrix) {
        sk_free(fLocalMatrix);
        fLocalMatrix = NULL;
    }
}

bool SkShader::setContext(const SkBitmap& device,
                          const SkPaint& paint,
                          const SkMatrix& matrix) {
    const SkMatrix* m = &matrix;
    SkMatrix        total;

    fDeviceConfig = SkToU8(device.getConfig());
    fPaintAlpha = paint.getAlpha();
    if (fLocalMatrix) {
        total.setConcat(matrix, *fLocalMatrix);
        m = &total;
    }
    if (m->invert(&fTotalInverse)) {
        fTotalInverseClass = (uint8_t)ComputeMatrixClass(fTotalInverse);
        return true;
    }
    return false;
}

#include "SkColorPriv.h"

void SkShader::shadeSpan16(int x, int y, uint16_t span16[], int count) {
    SkASSERT(span16);
    SkASSERT(count > 0);
    SkASSERT(this->canCallShadeSpan16());

    // basically, if we get here, the subclass screwed up
    SkASSERT(!"kHasSpan16 flag is set, but shadeSpan16() not implemented");
}

#define kTempColorQuadCount 6   // balance between speed (larger) and saving stack-space
#define kTempColorCount     (kTempColorQuadCount << 2)

#ifdef SK_CPU_BENDIAN
    #define SkU32BitShiftToByteOffset(shift)    (3 - ((shift) >> 3))
#else
    #define SkU32BitShiftToByteOffset(shift)    ((shift) >> 3)
#endif

void SkShader::shadeSpanAlpha(int x, int y, uint8_t alpha[], int count) {
    SkASSERT(count > 0);

    SkPMColor   colors[kTempColorCount];

    while ((count -= kTempColorCount) >= 0) {
        this->shadeSpan(x, y, colors, kTempColorCount);
        x += kTempColorCount;

        const uint8_t* srcA = (const uint8_t*)colors + SkU32BitShiftToByteOffset(SK_A32_SHIFT);
        int quads = kTempColorQuadCount;
        do {
            U8CPU a0 = srcA[0];
            U8CPU a1 = srcA[4];
            U8CPU a2 = srcA[8];
            U8CPU a3 = srcA[12];
            srcA += 4*4;
            *alpha++ = SkToU8(a0);
            *alpha++ = SkToU8(a1);
            *alpha++ = SkToU8(a2);
            *alpha++ = SkToU8(a3);
        } while (--quads != 0);
    }
    SkASSERT(count < 0);
    SkASSERT(count + kTempColorCount >= 0);
    if (count += kTempColorCount) {
        this->shadeSpan(x, y, colors, count);

        const uint8_t* srcA = (const uint8_t*)colors + SkU32BitShiftToByteOffset(SK_A32_SHIFT);
        do {
            *alpha++ = *srcA;
            srcA += 4;
        } while (--count != 0);
    }
#if 0
    do {
        int n = count;
        if (n > kTempColorCount)
            n = kTempColorCount;
        SkASSERT(n > 0);

        this->shadeSpan(x, y, colors, n);
        x += n;
        count -= n;

        const uint8_t* srcA = (const uint8_t*)colors + SkU32BitShiftToByteOffset(SK_A32_SHIFT);
        do {
            *alpha++ = *srcA;
            srcA += 4;
        } while (--n != 0);
    } while (count > 0);
#endif
}

SkShader::MatrixClass SkShader::ComputeMatrixClass(const SkMatrix& mat) {
    MatrixClass mc = kLinear_MatrixClass;

    if (mat.getType() & SkMatrix::kPerspective_Mask) {
        if (mat.fixedStepInX(0, NULL, NULL)) {
            mc = kFixedStepInX_MatrixClass;
        } else {
            mc = kPerspective_MatrixClass;
        }
    }
    return mc;
}

//////////////////////////////////////////////////////////////////////////////

bool SkShader::asABitmap(SkBitmap*, SkMatrix*, TileMode*) {
    return false;
}

SkShader* SkShader::CreateBitmapShader(const SkBitmap& src,
                                       TileMode tmx, TileMode tmy) {
    return SkShader::CreateBitmapShader(src, tmx, tmy, NULL, 0);
}

//////////////////////////////////////////////////////////////////////////////

#include "SkColorShader.h"
#include "SkUtils.h"

SkColorShader::SkColorShader(SkFlattenableReadBuffer& b) : INHERITED(b) {
    fFlags = 0; // computed in setContext
    fInheritColor = b.readU8();
    if (fInheritColor) {
        return;
    }
    fColor = b.readU32();
}

void SkColorShader::flatten(SkFlattenableWriteBuffer& buffer) {
    this->INHERITED::flatten(buffer);
    buffer.write8(fInheritColor);
    if (fInheritColor) {
        return;
    }
    buffer.write32(fColor);
}

uint8_t SkColorShader::getSpan16Alpha() const {
    return SkGetPackedA32(fPMColor);
}

bool SkColorShader::setContext(const SkBitmap& device, const SkPaint& paint,
                               const SkMatrix& matrix) {
    if (!this->INHERITED::setContext(device, paint, matrix)) {
        return false;
    }

    SkColor c;
    unsigned a;

    if (fInheritColor) {
        c = paint.getColor();
        a = SkColorGetA(c);
    } else {
        c = fColor;
        a = SkAlphaMul(SkColorGetA(c), SkAlpha255To256(paint.getAlpha()));
    }

    unsigned r = SkColorGetR(c);
    unsigned g = SkColorGetG(c);
    unsigned b = SkColorGetB(c);

    // we want this before we apply any alpha
    fColor16 = SkPack888ToRGB16(r, g, b);

    if (a != 255) {
        r = SkMulDiv255Round(r, a);
        g = SkMulDiv255Round(g, a);
        b = SkMulDiv255Round(b, a);
    }
    fPMColor = SkPackARGB32(a, r, g, b);

    fFlags = kConstInY32_Flag;
    if (255 == a) {
        fFlags |= kOpaqueAlpha_Flag;
        if (paint.isDither() == false) {
            fFlags |= kHasSpan16_Flag;
        }
    }

    return true;
}

void SkColorShader::shadeSpan(int x, int y, SkPMColor span[], int count) {
    sk_memset32(span, fPMColor, count);
}

void SkColorShader::shadeSpan16(int x, int y, uint16_t span[], int count) {
    sk_memset16(span, fColor16, count);
}

void SkColorShader::shadeSpanAlpha(int x, int y, uint8_t alpha[], int count) {
    memset(alpha, SkGetPackedA32(fPMColor), count);
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: OBoundParam.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: oj $ $Date: 2001-07-05 11:05:34 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _CONNECTIVITY_OBOUNPARAM_HXX_
#define _CONNECTIVITY_OBOUNPARAM_HXX_

#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif

namespace connectivity
{
    namespace odbc
    {
        class OBoundParam
        {

        public:
            OBoundParam()
            {
                paramLength = NULL;
                binaryData  = NULL;
                pA1=0;
                pA2=0;
                pB1=0;
                pB2=0;
                pC1=0;
                pC2=0;
                pS1=0;
                pS2=0;
            }
            ~OBoundParam()
            {
                delete [] binaryData;
                delete [] paramLength;
            }
            //--------------------------------------------------------------------
            // initialize
            // Perform an necessary initialization
            //--------------------------------------------------------------------
            void initialize ()
            {
                // Allocate storage for the length.  Note - the length is
                // stored in native format, and will have to be converted
                // to a Java sal_Int32.  The jdbcodbc 'C' bridge provides an
                // interface to do this.

                paramLength = new sal_Int8[4];
            }

            //--------------------------------------------------------------------
            // allocBindDataBuffer
            // Allocates and returns a new bind data buffer of the specified
            // length
            //--------------------------------------------------------------------
            sal_Int8* allocBindDataBuffer (sal_Int32 bufLen)
            {
                binaryData = new sal_Int8[bufLen];

                // Reset the input stream, we are doing a new bind
                setInputStream (NULL, 0);

                return binaryData;
            }

            //--------------------------------------------------------------------
            // getBindDataBuffer
            // Returns the data buffer to be used when binding to a parameter
            //--------------------------------------------------------------------
            sal_Int8* getBindDataBuffer ()
            {
                return binaryData;
            }

            //--------------------------------------------------------------------
            // getBindLengthBuffer
            // Returns the length buffer to be used when binding to a parameter
            //--------------------------------------------------------------------
            sal_Int8* getBindLengthBuffer ()
            {
                return paramLength;
            }

            //--------------------------------------------------------------------
            // setInputStream
            // Sets the input stream for the bound parameter
            //--------------------------------------------------------------------
            void setInputStream(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream>& inputStream,
                                sal_Int32 len)
            {
                paramInputStream = inputStream;
                paramInputStreamLen = len;
            }

            //--------------------------------------------------------------------
            // getInputStream
            // Gets the input stream for the bound parameter
            //--------------------------------------------------------------------
            ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream> getInputStream ()
            {
                return paramInputStream;
            }

            //--------------------------------------------------------------------
            // getInputStreamLen
            // Gets the input stream length for the bound parameter
            //--------------------------------------------------------------------
            sal_Int32 getInputStreamLen ()
            {
                return paramInputStreamLen;
            }

            //--------------------------------------------------------------------
            // setSqlType
            // Sets the Java sql type used to register an OUT parameter
            //--------------------------------------------------------------------

            void setSqlType(sal_Int32 type)
            {
                sqlType = type;
            }

            //--------------------------------------------------------------------
            // getSqlType
            // Gets the Java sql type used to register an OUT parameter
            //--------------------------------------------------------------------

            sal_Int32 getSqlType ()
            {
                return sqlType;
            }

            //--------------------------------------------------------------------
            // setStreamType
            // Sets the input stream type used to register an OUT parameter
            //--------------------------------------------------------------------

            void setStreamType (sal_Int32 type)
            {
                streamType = type;
            }

            //--------------------------------------------------------------------
            // getStreamType
            // Gets the input stream type used to register an OUT parameter
            //--------------------------------------------------------------------

            sal_Int32 getStreamType ()
            {
                return streamType;
            }

            //--------------------------------------------------------------------
            // setOutputParameter
            // Sets the flag indicating if this is an OUTPUT parameter
            //--------------------------------------------------------------------

            void setOutputParameter (sal_Bool output)
            {
                outputParameter = output;
            }

            //--------------------------------------------------------------------
            // isOutputParameter
            // Gets the OUTPUT parameter flag
            //--------------------------------------------------------------------

            sal_Bool isOutputParameter ()
            {
                return outputParameter;
            }

        protected:
            //====================================================================
            // Data attributes
            //====================================================================

            sal_Int8* binaryData;       // Storage area to be used
                                        // when binding the parameter

            sal_Int8* paramLength;      // Storage area to be used
                                        // for the bound length of the
                                        // parameter.  Note that this
                                        // data is in native format.

            ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream> paramInputStream;
                                        // When an input stream is
                                        // bound to a parameter, the
                                        // input stream is saved
                                        // until needed.

            sal_Int32 paramInputStreamLen;                // Length of input stream

            sal_Int32 sqlType;                          // Java SQL type used to
                                                            // register an OUT parameter

            sal_Int32 streamType;                  // Input stream type
                                        // (ASCII, BINARY, UNICODE)

            sal_Bool outputParameter;   // true for OUTPUT parameters

            sal_Int32 pA1;              //pointers
            sal_Int32 pA2;
            sal_Int32 pB1;
            sal_Int32 pB2;
            sal_Int32 pC1;
            sal_Int32 pC2;
            sal_Int32 pS1;
            sal_Int32 pS2;// reserved for strings(UTFChars)

        public:
            static int ASCII;
            static int UNICODE;
            static int BINARY;
        };
    }
}
#endif // _CONNECTIVITY_OBOUNPARAM_HXX_

<commit_msg>INTEGRATION: CWS ooo19126 (1.2.348); FILE MERGED 2005/09/05 17:25:44 rt 1.2.348.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: OBoundParam.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 07:34:29 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _CONNECTIVITY_OBOUNPARAM_HXX_
#define _CONNECTIVITY_OBOUNPARAM_HXX_

#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif

namespace connectivity
{
    namespace odbc
    {
        class OBoundParam
        {

        public:
            OBoundParam()
            {
                paramLength = NULL;
                binaryData  = NULL;
                pA1=0;
                pA2=0;
                pB1=0;
                pB2=0;
                pC1=0;
                pC2=0;
                pS1=0;
                pS2=0;
            }
            ~OBoundParam()
            {
                delete [] binaryData;
                delete [] paramLength;
            }
            //--------------------------------------------------------------------
            // initialize
            // Perform an necessary initialization
            //--------------------------------------------------------------------
            void initialize ()
            {
                // Allocate storage for the length.  Note - the length is
                // stored in native format, and will have to be converted
                // to a Java sal_Int32.  The jdbcodbc 'C' bridge provides an
                // interface to do this.

                paramLength = new sal_Int8[4];
            }

            //--------------------------------------------------------------------
            // allocBindDataBuffer
            // Allocates and returns a new bind data buffer of the specified
            // length
            //--------------------------------------------------------------------
            sal_Int8* allocBindDataBuffer (sal_Int32 bufLen)
            {
                binaryData = new sal_Int8[bufLen];

                // Reset the input stream, we are doing a new bind
                setInputStream (NULL, 0);

                return binaryData;
            }

            //--------------------------------------------------------------------
            // getBindDataBuffer
            // Returns the data buffer to be used when binding to a parameter
            //--------------------------------------------------------------------
            sal_Int8* getBindDataBuffer ()
            {
                return binaryData;
            }

            //--------------------------------------------------------------------
            // getBindLengthBuffer
            // Returns the length buffer to be used when binding to a parameter
            //--------------------------------------------------------------------
            sal_Int8* getBindLengthBuffer ()
            {
                return paramLength;
            }

            //--------------------------------------------------------------------
            // setInputStream
            // Sets the input stream for the bound parameter
            //--------------------------------------------------------------------
            void setInputStream(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream>& inputStream,
                                sal_Int32 len)
            {
                paramInputStream = inputStream;
                paramInputStreamLen = len;
            }

            //--------------------------------------------------------------------
            // getInputStream
            // Gets the input stream for the bound parameter
            //--------------------------------------------------------------------
            ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream> getInputStream ()
            {
                return paramInputStream;
            }

            //--------------------------------------------------------------------
            // getInputStreamLen
            // Gets the input stream length for the bound parameter
            //--------------------------------------------------------------------
            sal_Int32 getInputStreamLen ()
            {
                return paramInputStreamLen;
            }

            //--------------------------------------------------------------------
            // setSqlType
            // Sets the Java sql type used to register an OUT parameter
            //--------------------------------------------------------------------

            void setSqlType(sal_Int32 type)
            {
                sqlType = type;
            }

            //--------------------------------------------------------------------
            // getSqlType
            // Gets the Java sql type used to register an OUT parameter
            //--------------------------------------------------------------------

            sal_Int32 getSqlType ()
            {
                return sqlType;
            }

            //--------------------------------------------------------------------
            // setStreamType
            // Sets the input stream type used to register an OUT parameter
            //--------------------------------------------------------------------

            void setStreamType (sal_Int32 type)
            {
                streamType = type;
            }

            //--------------------------------------------------------------------
            // getStreamType
            // Gets the input stream type used to register an OUT parameter
            //--------------------------------------------------------------------

            sal_Int32 getStreamType ()
            {
                return streamType;
            }

            //--------------------------------------------------------------------
            // setOutputParameter
            // Sets the flag indicating if this is an OUTPUT parameter
            //--------------------------------------------------------------------

            void setOutputParameter (sal_Bool output)
            {
                outputParameter = output;
            }

            //--------------------------------------------------------------------
            // isOutputParameter
            // Gets the OUTPUT parameter flag
            //--------------------------------------------------------------------

            sal_Bool isOutputParameter ()
            {
                return outputParameter;
            }

        protected:
            //====================================================================
            // Data attributes
            //====================================================================

            sal_Int8* binaryData;       // Storage area to be used
                                        // when binding the parameter

            sal_Int8* paramLength;      // Storage area to be used
                                        // for the bound length of the
                                        // parameter.  Note that this
                                        // data is in native format.

            ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream> paramInputStream;
                                        // When an input stream is
                                        // bound to a parameter, the
                                        // input stream is saved
                                        // until needed.

            sal_Int32 paramInputStreamLen;                // Length of input stream

            sal_Int32 sqlType;                          // Java SQL type used to
                                                            // register an OUT parameter

            sal_Int32 streamType;                  // Input stream type
                                        // (ASCII, BINARY, UNICODE)

            sal_Bool outputParameter;   // true for OUTPUT parameters

            sal_Int32 pA1;              //pointers
            sal_Int32 pA2;
            sal_Int32 pB1;
            sal_Int32 pB2;
            sal_Int32 pC1;
            sal_Int32 pC2;
            sal_Int32 pS1;
            sal_Int32 pS2;// reserved for strings(UTFChars)

        public:
            static int ASCII;
            static int UNICODE;
            static int BINARY;
        };
    }
}
#endif // _CONNECTIVITY_OBOUNPARAM_HXX_

<|endoftext|>


<commit_before>#include "hit.hpp"
#include "shape.hpp"

Hit::Hit() :
hit_{false},
distance_{INFINITY},
intersection_{glm::vec3{ INFINITY,INFINITY,INFINITY }},
normal_{glm::vec3{ INFINITY,INFINITY,INFINITY }},
sptr_{nullptr} {}

Hit::Hit(bool hit, float dis, glm::vec3 const& intersection,
    glm::vec3 const& norm, std::shared_ptr<Shape> sptr) :
hit_{hit},
distance_{dis},
intersection_{intersection},
normal_{norm},
sptr_{sptr} {}

Hit& Hit::operator=(Hit const& hit) {
    if (this == &hit) {
        return *this;
    }

    hit_ = hit.hit_;
    distance_ = hit.distance_;
    intersection_ = hit.intersection_;
    normal_ = hit.normal_;
    sptr_ = hit.sptr_;

    return *this;
}

bool Hit::operator==(Hit const& hit2) const{
      return ((hit_ == hit2.hit_) && (distance_ == hit2.distance_) && (intersection_ == hit2.intersection_) && (normal_ == hit2.normal_) && (sptr_ == hit2.sptr_));
    }

std::ostream& operator<<(std::ostream& os, Hit const& hit) {
    os << "Hit: " << hit.hit_ << std::endl
       << "Distanz: " << hit.distance_ << std::endl
       << "Intersection: ("
       << hit.intersection_.x << ", "
       << hit.intersection_.y << ", "
       << hit.intersection_.z << ")" << std::endl
       << "Normal: ("
       << hit.normal_.x << ", "
       << hit.normal_.y << ", "
       << hit.normal_.z << ")" << std::endl;
    return os;
}
<commit_msg>fixing infinity warning<commit_after>#include <limits>
#include "hit.hpp"
#include "shape.hpp"

Hit::Hit() :
hit_{false},
distance_{std::numeric_limits<float>::infinity()},
intersection_{std::numeric_limits<float>::infinity(),std::numeric_limits<float>::infinity(),std::numeric_limits<float>::infinity()},
normal_{std::numeric_limits<float>::infinity(),std::numeric_limits<float>::infinity(),std::numeric_limits<float>::infinity()},
sptr_{nullptr} {}

Hit::Hit(bool hit, float dis, glm::vec3 const& intersection,
    glm::vec3 const& norm, std::shared_ptr<Shape> sptr) :
hit_{hit},
distance_{dis},
intersection_{intersection},
normal_{norm},
sptr_{sptr} {}

Hit& Hit::operator=(Hit const& hit) {
    if (this == &hit) {
        return *this;
    }

    hit_ = hit.hit_;
    distance_ = hit.distance_;
    intersection_ = hit.intersection_;
    normal_ = hit.normal_;
    sptr_ = hit.sptr_;

    return *this;
}

bool Hit::operator==(Hit const& hit2) const{
      return ((hit_ == hit2.hit_) && (distance_ == hit2.distance_) && (intersection_ == hit2.intersection_) && (normal_ == hit2.normal_) && (sptr_ == hit2.sptr_));
    }

std::ostream& operator<<(std::ostream& os, Hit const& hit) {
    os << "Hit: " << hit.hit_ << std::endl
       << "Distanz: " << hit.distance_ << std::endl
       << "Intersection: ("
       << hit.intersection_.x << ", "
       << hit.intersection_.y << ", "
       << hit.intersection_.z << ")" << std::endl
       << "Normal: ("
       << hit.normal_.x << ", "
       << hit.normal_.y << ", "
       << hit.normal_.z << ")" << std::endl;
    return os;
}
<|endoftext|>


<commit_before>#include "ROOT/RDataFrame.hxx"
#include "TChain.h"
#include "TEntryList.h"
#include "TFile.h"
#include "TROOT.h"
#include "TSystem.h"
#include "TTree.h"
#include "gtest/gtest.h"

#include <algorithm> // std::sort
#include <vector>

// Write to disk file filename with TTree "t" with nEntries of branch "e" assuming integer values [0..nEntries).
void MakeInputFile(const std::string &filename, int nEntries)
{
   const auto treename = "t";
   auto d = ROOT::RDataFrame(nEntries)
               .Define("e", [](ULong64_t e) { return int(e); }, {"rdfentry_"})
               .Snapshot<int>(treename, filename, {"e"});
}

class RMTRAII {
   bool fIsMT;

public:
   RMTRAII(bool isMT) : fIsMT(isMT)
   {
      if (fIsMT)
         ROOT::EnableImplicitMT();
   }
   ~RMTRAII()
   {
      if (fIsMT)
         ROOT::DisableImplicitMT();
   }
};

void TestTreeWithEntryList(bool isMT = false)
{
   const auto nEntries = 10;
   const auto treename = "t";
   const auto filename = "rdfentrylist.root";
   MakeInputFile(filename, nEntries);

   RMTRAII gomt(isMT);

   TEntryList elist("e", "e", treename, filename);
   elist.Enter(0);
   elist.Enter(nEntries - 1);

   TFile f(filename);
   auto t = f.Get<TTree>(treename);
   t->SetEntryList(&elist);

   auto entries = ROOT::RDataFrame(*t).Take<int>("e").GetValue();
   std::sort(entries.begin(), entries.end()); // could be out of order in MT runs
   EXPECT_EQ(entries, std::vector<int>({0, nEntries - 1}));

   gSystem->Unlink(filename);
}

void TestChainWithEntryList(bool isMT = false)
{
   const auto nEntries = 10;
   const auto treename = "t";
   const auto file1 = "rdfentrylist1.root";
   const auto file2 = "rdfentrylist2.root";
   MakeInputFile(file1, nEntries);
   MakeInputFile(file2, nEntries);

   RMTRAII gomt(isMT);

   TEntryList elist1("e", "e", treename, file1);
   elist1.Enter(0);
   elist1.Enter(nEntries - 1);
   TEntryList elist2("e", "e", treename, file2);
   elist2.Enter(0);
   elist2.Enter(nEntries - 1);

   // make a TEntryList that contains two TEntryLists in its list of TEntryLists,
   // as required by TChain (see TEntryList's doc)
   TEntryList elists;
   elists.Add(&elist1);
   elists.Add(&elist2);

   TChain c(treename);
   c.Add(file1, nEntries);
   c.Add(file2, nEntries);
   c.SetEntryList(&elists);

   auto entries = ROOT::RDataFrame(c).Take<int>("e").GetValue();
   std::sort(entries.begin(), entries.end()); // could be out of order in MT runs
   EXPECT_EQ(entries, std::vector<int>({0, 0, nEntries - 1, nEntries - 1}));

   gSystem->Unlink(file1);
   gSystem->Unlink(file2);
}

TEST(RDFEntryList, Chain)
{
   TestChainWithEntryList();
}

TEST(RDFEntryList, Tree)
{
   TestTreeWithEntryList();
}

#ifdef R__USE_IMT
TEST(RDFEntryList, ChainMT)
{
   TestChainWithEntryList(true);
}

TEST(RDFEntryList, TreeMT)
{
   TestTreeWithEntryList(true);
}
#endif
<commit_msg>[DF] Check for ROOT-10753 in RDF+TEntryList tests<commit_after>#include "ROOT/RDataFrame.hxx"
#include "TChain.h"
#include "TEntryList.h"
#include "TFile.h"
#include "TROOT.h"
#include "TSystem.h"
#include "TTree.h"
#include "gtest/gtest.h"

#include <algorithm> // std::sort
#include <vector>

// Write to disk one file for each filename, with TTree "t" with nEntries of branch "e" with increasing values
// starting at valueStart
void MakeInputFile(const std::string &filename, int nEntries, int valueStart = 0)
{
   int e = valueStart;
   const auto treename = "t";
   auto d = ROOT::RDataFrame(nEntries).Define("e", [&] { return e++; }).Snapshot<int>(treename, filename, {"e"});
}

class RMTRAII {
   bool fIsMT;

public:
   RMTRAII(bool isMT) : fIsMT(isMT)
   {
      if (fIsMT)
         ROOT::EnableImplicitMT();
   }
   ~RMTRAII()
   {
      if (fIsMT)
         ROOT::DisableImplicitMT();
   }
};

void TestTreeWithEntryList(bool isMT = false)
{
   const auto nEntries = 10;
   const auto treename = "t";
   const auto filename = "rdfentrylist.root";
   MakeInputFile(filename, nEntries);

   RMTRAII gomt(isMT);

   TEntryList elist("e", "e", treename, filename);
   elist.Enter(0);
   elist.Enter(nEntries - 1);

   TFile f(filename);
   auto t = f.Get<TTree>(treename);
   t->SetEntryList(&elist);

   auto entries = ROOT::RDataFrame(*t).Take<int>("e").GetValue();
   std::sort(entries.begin(), entries.end()); // could be out of order in MT runs
   EXPECT_EQ(entries, std::vector<int>({0, nEntries - 1}));

   gSystem->Unlink(filename);
}

void TestChainWithEntryList(bool isMT = false)
{
   // The test might seem contrived, because it is. We want to check:
   // - that we read the correct entries from the correct trees, so we need to read different entries per tree
   // - that TTreeProcessorMT re-builds TEntryLists correctly for each file/cluster, so we need a different number
   //   of entries and we need to select, via TEntryList, entries of tree2 that do not exist in tree1

   const auto nEntries = 10;
   const auto treename = "t";
   const auto file1 = "rdfentrylist1.root";
   const auto file2 = "rdfentrylist2.root";
   MakeInputFile(file1, nEntries);
   MakeInputFile(file2, nEntries * 2, /*valueStart=*/nEntries);

   RMTRAII gomt(isMT);

   TEntryList elist1("e", "e", treename, file1);
   elist1.Enter(0);
   elist1.Enter(nEntries - 1);
   TEntryList elist2("e", "e", treename, file2);
   elist2.Enter(nEntries + 1);
   elist2.Enter(2 * nEntries - 1);

   // make a TEntryList that contains two TEntryLists in its list of TEntryLists,
   // as required by TChain (see TEntryList's doc)
   TEntryList elists;
   elists.Add(&elist1);
   elists.Add(&elist2);

   TChain c(treename);
   c.Add(file1, nEntries);
   c.Add(file2, nEntries * 2);
   c.SetEntryList(&elists);

   auto entries = ROOT::RDataFrame(c).Take<int>("e").GetValue();
   std::sort(entries.begin(), entries.end()); // could be out of order in MT runs
   EXPECT_EQ(entries, std::vector<int>({0, nEntries - 1, 2 * nEntries + 1, 3 * nEntries - 1}));

   gSystem->Unlink(file1);
   gSystem->Unlink(file2);
}

TEST(RDFEntryList, Chain)
{
   TestChainWithEntryList();
}

TEST(RDFEntryList, Tree)
{
   TestTreeWithEntryList();
}

#ifdef R__USE_IMT
TEST(RDFEntryList, ChainMT)
{
   TestChainWithEntryList(true);
}

TEST(RDFEntryList, TreeMT)
{
   TestTreeWithEntryList(true);
}
#endif
<|endoftext|>


<commit_before> inline
 kth_cv_omp::kth_cv_omp(const std::string in_path,
		const std::string in_actionNames,
		const field<std::string> in_all_people,
		const int in_scale_factor,
		const int in_shift,
		const int in_scene, //only for kth
		const int in_segment_length,
		const int in_dim
 ):path(in_path), actionNames(in_actionNames), all_people (in_all_people), scale_factor(in_scale_factor), shift(in_shift), total_scenes(in_scene), segment_length(in_segment_length), dim(in_dim)
 {
   actions.load( actionNames );

 }

 // Log-Euclidean Distance
 inline
 void
 kth_cv_omp::logEucl()
 {

   int n_actions = actions.n_rows;
   int n_peo =  all_people.n_rows;

   float acc;
   acc = 0;

   int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3
   vec real_labels;
   vec est_labels;
   field<std::string> test_video_list(n_test);

   real_labels.zeros(n_test);
   est_labels.zeros(n_test);

   int k=0;

   for (int sc = 1; sc<=total_scenes; ++sc) //scene
   {
     for (int pe = 0; pe< n_peo; ++pe)
     {
       for (int act=0; act<n_actions; ++act)
       {
	 if(  !( ( sc==3 && pe==12) && act==1) ) //person13_handclapping_d3
	 {

	   //load number of segments

	   vec total_seg;
	   int num_s;
	   std::stringstream load_sub_path;
	   std::stringstream load_num_seg;

	   load_sub_path  << path << "/kth-cov-mat/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
	   load_num_seg << load_sub_path.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".dat";
	   total_seg.load( load_num_seg.str());
	   num_s = total_seg(0);
	   uvec  est_lab_segm;
	   est_lab_segm.zeros(num_s);
	   vec count = zeros<vec>( n_actions );

	   for (int s=0; s<num_s; ++s)
	   {
	     std::stringstream load_cov_seg;
	     load_cov_seg << load_sub_path.str() << "/LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5";

	     //cout << "LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5" << endl;
	     //debe devolver el est_labe de ese segmento
	     est_lab_segm(s) = logEucl_one_seg_est_lab( pe, load_sub_path.str(),  load_cov_seg.str());
	     count( est_lab_segm(s) )++;
	     //getchar();
	   }

	   uword  index_video;
	   double max_val = count.max(index_video);
	   //est_lab_segm.t().print("est_lab_segm");
	   cout << "This video is " << actions(act) << " and was classified as class: " << actions(index_video ) << endl;

	   real_labels(k) = act;
	   est_labels(k) = index_video;
	   test_video_list(k) = load_sub_path.str();

	   real_labels.save("Log_Eucl_real_labels.dat", raw_ascii);
	   est_labels.save("Log_Eucl_est_labels.dat", raw_ascii);
	   test_video_list.save("Log_Eucl_test_video_list.dat", raw_ascii);
	   k++;

	   if (index_video == act)  {
	     acc++;

	   }

	   //getchar();
	 }
       }

     }
   }

   cout << "Performance: " << acc*100/n_test << " %" << endl;

 }

 inline
 uword
 kth_cv_omp::logEucl_one_seg_est_lab(int pe_test, std::string load_sub_path, std::string segm_name)
 {
   //wall_clock timer;
   //timer.tic();

   mat logMtest_cov;
   logMtest_cov.load(segm_name);

   int n_actions = actions.n_rows;
   int n_peo =  all_people.n_rows;

   double dist, tmp_dist;
   tmp_dist = datum::inf;

   double est_lab;
   //cout << "Comparing with person ";

   for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr)
   {
     if (pe_tr!= pe_test)
     {

       //cout << " " << all_people (pe_tr);

       for (int sc = 1; sc<=total_scenes; ++sc) //scene
       {
	 for (int act=0; act<n_actions; ++act)
	 {
	   vec total_seg;
	   int num_s;
	   std::stringstream load_num_seg;
	   load_num_seg << load_sub_path << "/num_seg_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim  << ".dat";
	   total_seg.load( load_num_seg.str());
	   num_s = total_seg(0);

	   vec dist_segm_s = zeros<vec> (num_s);

	   omp_set_num_threads(6);
	   cout << omp_get_num_threads() << endl;
	   #pragma omp for
	   for (int s_tr=0; s_tr<num_s; ++s_tr)
	   {
	     std::stringstream load_cov_seg_tr;
	     load_cov_seg_tr << load_sub_path << "/LogMcov_seg" << s_tr << "_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim  << ".h5";

	     //cout << "Comparing with cov_seg" << s_tr << "_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim  << ".h5" << endl;
	     mat logMtrain_cov;
	     logMtrain_cov.load( load_cov_seg_tr.str() );

	     //logMtest_cov.print("logMtest_cov");
	     //train_cov.print("train_cov");

	     dist_segm_s(s_tr) = norm( logMtest_cov - logMtrain_cov, "fro");

	     //cout << "dist " << dis
	     //cout << "Press a key" << endl;
	     //getchar();
	   }

	   #pragma omp barrier

	   dist_segm_s.t().print("dist_segm_s");
	   getchar();
	 }
       }
     }
   }

   //double n = timer.toc();
   //cout << "number of seconds: " << n << endl;
   //cout << " est_lab "<< est_lab << endl << endl;
   //getchar();
   return est_lab;

 }

 //DO IT
 // Stein Divergence

 inline
 void
 kth_cv_omp::SteinDiv()
 {

   int n_actions = actions.n_rows;
   int n_peo =  all_people.n_rows;

   float acc;
   acc = 0;

      int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3

   vec real_labels;
   vec est_labels;
   field<std::string> test_video_list(n_test);

   real_labels.zeros(n_test);
   est_labels.zeros(n_test);

   int k=0;

   for (int sc = 1; sc<=total_scenes; ++sc) //scene
   {
     for (int pe = 0; pe< n_peo; ++pe)
     {
       for (int act=0; act<n_actions; ++act)
       {
	 if(  !( ( sc==3 && pe==12) && act==1) ) //person13_handclapping_d3
	 {
	   //load number of segments

	   vec total_seg;
	   int num_s;
	   std::stringstream load_sub_path;
	   std::stringstream load_num_seg;

	   load_sub_path  << path << "/kth-cov-mat/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
	   load_num_seg << load_sub_path.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".dat";
	   total_seg.load( load_num_seg.str());
	   num_s = total_seg(0);
	   uvec  est_lab_segm;
	   est_lab_segm.zeros(num_s);
	   vec count = zeros<vec>( n_actions );

	   for (int s=0; s<num_s; ++s)
	   {
	     std::stringstream load_cov_seg;
	     load_cov_seg << load_sub_path.str() << "/cov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5";

	     est_lab_segm(s) = SteinDiv_one_seg_est_lab( pe, load_sub_path.str(),  load_cov_seg.str());
	     count( est_lab_segm(s) )++;
	     //getchar();
	   }

	   uword  index_video;
	   double max_val = count.max(index_video);
	   //est_lab_segm.t().print("est_lab_segm");
	   cout << "This video is " << actions(act) << " and was classified as class: " << actions(index_video ) << endl;

	   real_labels(k) = act;
	   est_labels(k) = index_video;
	   test_video_list(k) = load_sub_path.str();

	   real_labels.save("Stein_div_real_labels.dat", raw_ascii);
	   est_labels.save("Stein_div__est_labels.dat", raw_ascii);
	   test_video_list.save("Stein_div_test_video_list.dat", raw_ascii);
	   k++;

	   if (index_video == act)  {
	     acc++;

	   }

	   //getchar();
	 }

       }
     }
   }

   cout << "Performance: " << acc*100/n_test << " %" << endl;

 }

 //DO IT!!!!!!!!!
 inline
 uword
 kth_cv_omp::SteinDiv_one_seg_est_lab(int pe_test, std::string load_sub_path, std::string segm_name)
 {
   //wall_clock timer;
   //timer.tic();

   mat test_cov;
   test_cov.load(segm_name);

   int n_actions = actions.n_rows;
   int n_peo =  all_people.n_rows;

   double dist_stein, tmp_dist;
   tmp_dist = datum::inf;

   double est_lab;
   //cout << "Comparing with person ";

   for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr)
   {
     if (pe_tr!= pe_test)
     {

       //cout << " " << all_people (pe_tr);

       for (int sc = 1; sc<=total_scenes; ++sc) //scene
       {
	 for (int act=0; act<n_actions; ++act)
	 {
	   vec total_seg;
	   int num_s;
	   std::stringstream load_num_seg;
	   load_num_seg << load_sub_path << "/num_seg_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim  << ".dat";
	   total_seg.load( load_num_seg.str());
	   num_s = total_seg(0);

	   for (int s_tr=0; s_tr<num_s; ++s_tr)
	   {
	     std::stringstream load_cov_seg_tr;
	     load_cov_seg_tr << load_sub_path << "/cov_seg" << s_tr << "_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim  << ".h5";

	     mat train_cov;
	     train_cov.load( load_cov_seg_tr.str() );

	     //Esto vienen de PartI4. No recuerdo mas :(
	     double det_op1 = det( diagmat( (test_cov + train_cov)/2 ) );
	     double det_op2 = det( diagmat( ( test_cov%train_cov ) ) );
	     dist_stein =  log( det_op1 ) - 0.5*log( det_op2 ) ;

	     //dist_stein = norm( logMtest_cov - logMtrain_cov, "fro");

	     //cout << "dist " << dist << endl;

	     if (dist_stein < tmp_dist)
	     {
	       //cout << "Es menor" << endl;
	       tmp_dist = dist_stein;
	       est_lab = act;
	     }
	     //cout << "Press a key" << endl;
	     //getchar();
	   }
	 }
       }
     }
   }

   //double n = timer.toc();
   //cout << "number of seconds: " << n << endl;
   //cout << " est_lab "<< est_lab << endl << endl;
   //getchar();
   return est_lab;

 }

 <commit_msg>try oPenMP<commit_after> inline
 kth_cv_omp::kth_cv_omp(const std::string in_path,
		const std::string in_actionNames,
		const field<std::string> in_all_people,
		const int in_scale_factor,
		const int in_shift,
		const int in_scene, //only for kth
		const int in_segment_length,
		const int in_dim
 ):path(in_path), actionNames(in_actionNames), all_people (in_all_people), scale_factor(in_scale_factor), shift(in_shift), total_scenes(in_scene), segment_length(in_segment_length), dim(in_dim)
 {
   actions.load( actionNames );

 }

 // Log-Euclidean Distance
 inline
 void
 kth_cv_omp::logEucl()
 {

   int n_actions = actions.n_rows;
   int n_peo =  all_people.n_rows;

   float acc;
   acc = 0;

   int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3
   vec real_labels;
   vec est_labels;
   field<std::string> test_video_list(n_test);

   real_labels.zeros(n_test);
   est_labels.zeros(n_test);

   int k=0;

   for (int sc = 1; sc<=total_scenes; ++sc) //scene
   {
     for (int pe = 0; pe< n_peo; ++pe)
     {
       for (int act=0; act<n_actions; ++act)
       {
	 if(  !( ( sc==3 && pe==12) && act==1) ) //person13_handclapping_d3
	 {

	   //load number of segments

	   vec total_seg;
	   int num_s;
	   std::stringstream load_sub_path;
	   std::stringstream load_num_seg;

	   load_sub_path  << path << "/kth-cov-mat/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
	   load_num_seg << load_sub_path.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".dat";
	   total_seg.load( load_num_seg.str());
	   num_s = total_seg(0);
	   uvec  est_lab_segm;
	   est_lab_segm.zeros(num_s);
	   vec count = zeros<vec>( n_actions );

	   for (int s=0; s<num_s; ++s)
	   {
	     std::stringstream load_cov_seg;
	     load_cov_seg << load_sub_path.str() << "/LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5";

	     //cout << "LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5" << endl;
	     //debe devolver el est_labe de ese segmento
	     est_lab_segm(s) = logEucl_one_seg_est_lab( pe, load_sub_path.str(),  load_cov_seg.str());
	     count( est_lab_segm(s) )++;
	     //getchar();
	   }

	   uword  index_video;
	   double max_val = count.max(index_video);
	   //est_lab_segm.t().print("est_lab_segm");
	   cout << "This video is " << actions(act) << " and was classified as class: " << actions(index_video ) << endl;

	   real_labels(k) = act;
	   est_labels(k) = index_video;
	   test_video_list(k) = load_sub_path.str();

	   real_labels.save("Log_Eucl_real_labels.dat", raw_ascii);
	   est_labels.save("Log_Eucl_est_labels.dat", raw_ascii);
	   test_video_list.save("Log_Eucl_test_video_list.dat", raw_ascii);
	   k++;

	   if (index_video == act)  {
	     acc++;

	   }

	   //getchar();
	 }
       }

     }
   }

   cout << "Performance: " << acc*100/n_test << " %" << endl;

 }

 inline
 uword
 kth_cv_omp::logEucl_one_seg_est_lab(int pe_test, std::string load_sub_path, std::string segm_name)
 {
   //wall_clock timer;
   //timer.tic();

   mat logMtest_cov;
   logMtest_cov.load(segm_name);

   int n_actions = actions.n_rows;
   int n_peo =  all_people.n_rows;

   double dist, tmp_dist;
   tmp_dist = datum::inf;

   double est_lab;
   //cout << "Comparing with person ";

   for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr)
   {
     if (pe_tr!= pe_test)
     {

       //cout << " " << all_people (pe_tr);

       for (int sc = 1; sc<=total_scenes; ++sc) //scene
       {
	 for (int act=0; act<n_actions; ++act)
	 {
	   vec total_seg;
	   int num_s;
	   std::stringstream load_num_seg;
	   load_num_seg << load_sub_path << "/num_seg_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim  << ".dat";
	   total_seg.load( load_num_seg.str());
	   num_s = total_seg(0);

	   vec dist_segm_s = zeros<vec> (num_s);

	   omp_set_num_threads(10);
	   cout << omp_get_num_threads() << endl;
	   #pragma omp for
	   for (int s_tr=0; s_tr<num_s; ++s_tr)
	   {
	     std::stringstream load_cov_seg_tr;
	     load_cov_seg_tr << load_sub_path << "/LogMcov_seg" << s_tr << "_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim  << ".h5";

	     //cout << "Comparing with cov_seg" << s_tr << "_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim  << ".h5" << endl;
	     mat logMtrain_cov;
	     logMtrain_cov.load( load_cov_seg_tr.str() );

	     //logMtest_cov.print("logMtest_cov");
	     //train_cov.print("train_cov");

	     dist_segm_s(s_tr) = norm( logMtest_cov - logMtrain_cov, "fro");

	     //cout << "dist " << dis
	     //cout << "Press a key" << endl;
	     //getchar();
	   }

	   #pragma omp barrier

	   dist_segm_s.t().print("dist_segm_s");
	   getchar();
	 }
       }
     }
   }

   //double n = timer.toc();
   //cout << "number of seconds: " << n << endl;
   //cout << " est_lab "<< est_lab << endl << endl;
   //getchar();
   return est_lab;

 }

 //DO IT
 // Stein Divergence

 inline
 void
 kth_cv_omp::SteinDiv()
 {

   int n_actions = actions.n_rows;
   int n_peo =  all_people.n_rows;

   float acc;
   acc = 0;

      int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3

   vec real_labels;
   vec est_labels;
   field<std::string> test_video_list(n_test);

   real_labels.zeros(n_test);
   est_labels.zeros(n_test);

   int k=0;

   for (int sc = 1; sc<=total_scenes; ++sc) //scene
   {
     for (int pe = 0; pe< n_peo; ++pe)
     {
       for (int act=0; act<n_actions; ++act)
       {
	 if(  !( ( sc==3 && pe==12) && act==1) ) //person13_handclapping_d3
	 {
	   //load number of segments

	   vec total_seg;
	   int num_s;
	   std::stringstream load_sub_path;
	   std::stringstream load_num_seg;

	   load_sub_path  << path << "/kth-cov-mat/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
	   load_num_seg << load_sub_path.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".dat";
	   total_seg.load( load_num_seg.str());
	   num_s = total_seg(0);
	   uvec  est_lab_segm;
	   est_lab_segm.zeros(num_s);
	   vec count = zeros<vec>( n_actions );

	   for (int s=0; s<num_s; ++s)
	   {
	     std::stringstream load_cov_seg;
	     load_cov_seg << load_sub_path.str() << "/cov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5";

	     est_lab_segm(s) = SteinDiv_one_seg_est_lab( pe, load_sub_path.str(),  load_cov_seg.str());
	     count( est_lab_segm(s) )++;
	     //getchar();
	   }

	   uword  index_video;
	   double max_val = count.max(index_video);
	   //est_lab_segm.t().print("est_lab_segm");
	   cout << "This video is " << actions(act) << " and was classified as class: " << actions(index_video ) << endl;

	   real_labels(k) = act;
	   est_labels(k) = index_video;
	   test_video_list(k) = load_sub_path.str();

	   real_labels.save("Stein_div_real_labels.dat", raw_ascii);
	   est_labels.save("Stein_div__est_labels.dat", raw_ascii);
	   test_video_list.save("Stein_div_test_video_list.dat", raw_ascii);
	   k++;

	   if (index_video == act)  {
	     acc++;

	   }

	   //getchar();
	 }

       }
     }
   }

   cout << "Performance: " << acc*100/n_test << " %" << endl;

 }

 //DO IT!!!!!!!!!
 inline
 uword
 kth_cv_omp::SteinDiv_one_seg_est_lab(int pe_test, std::string load_sub_path, std::string segm_name)
 {
   //wall_clock timer;
   //timer.tic();

   mat test_cov;
   test_cov.load(segm_name);

   int n_actions = actions.n_rows;
   int n_peo =  all_people.n_rows;

   double dist_stein, tmp_dist;
   tmp_dist = datum::inf;

   double est_lab;
   //cout << "Comparing with person ";

   for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr)
   {
     if (pe_tr!= pe_test)
     {

       //cout << " " << all_people (pe_tr);

       for (int sc = 1; sc<=total_scenes; ++sc) //scene
       {
	 for (int act=0; act<n_actions; ++act)
	 {
	   vec total_seg;
	   int num_s;
	   std::stringstream load_num_seg;
	   load_num_seg << load_sub_path << "/num_seg_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim  << ".dat";
	   total_seg.load( load_num_seg.str());
	   num_s = total_seg(0);

	   for (int s_tr=0; s_tr<num_s; ++s_tr)
	   {
	     std::stringstream load_cov_seg_tr;
	     load_cov_seg_tr << load_sub_path << "/cov_seg" << s_tr << "_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim  << ".h5";

	     mat train_cov;
	     train_cov.load( load_cov_seg_tr.str() );

	     //Esto vienen de PartI4. No recuerdo mas :(
	     double det_op1 = det( diagmat( (test_cov + train_cov)/2 ) );
	     double det_op2 = det( diagmat( ( test_cov%train_cov ) ) );
	     dist_stein =  log( det_op1 ) - 0.5*log( det_op2 ) ;

	     //dist_stein = norm( logMtest_cov - logMtrain_cov, "fro");

	     //cout << "dist " << dist << endl;

	     if (dist_stein < tmp_dist)
	     {
	       //cout << "Es menor" << endl;
	       tmp_dist = dist_stein;
	       est_lab = act;
	     }
	     //cout << "Press a key" << endl;
	     //getchar();
	   }
	 }
       }
     }
   }

   //double n = timer.toc();
   //cout << "number of seconds: " << n << endl;
   //cout << " est_lab "<< est_lab << endl << endl;
   //getchar();
   return est_lab;

 }

 <|endoftext|>