<commit_before>//
// Copyright (c) 2008-2015 the Urho3D project.
//
// 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:addmember
//
// 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 "../Precompiled.h"

#include "../Core/Context.h"
#include "../IO/Log.h"
#include "../Resource/JSONValue.h"

#include "../DebugNew.h"

namespace Urho3D
{

const JSONValue JSONValue::EMPTY;
const JSONArray JSONValue::emptyArray;
const JSONObject JSONValue::emptyObject;

JSONValue& JSONValue::operator =(bool rhs)
{
    SetType(JSON_BOOL);
    boolValue_ = rhs;

    return *this;
}

JSONValue& JSONValue::operator =(int rhs)
{
    SetType(JSON_NUMBER, JSONNT_INT);
    numberValue_ = rhs;

    return *this;
}

JSONValue& JSONValue::operator =(unsigned rhs)
{
    SetType(JSON_NUMBER, JSONNT_UINT);
    numberValue_ = rhs;

    return *this;
}

JSONValue& JSONValue::operator =(float rhs)
{
    SetType(JSON_NUMBER, JSONNT_FLOAT_DOUBLE);
    numberValue_ = rhs;

    return *this;
}

JSONValue& JSONValue::operator =(double rhs)
{
    SetType(JSON_NUMBER, JSONNT_FLOAT_DOUBLE);
    numberValue_ = rhs;

    return *this;
}

JSONValue& JSONValue::operator =(const String& rhs)
{
    SetType(JSON_STRING);
    *stringValue_ = rhs;

    return *this;
}

JSONValue& JSONValue::operator =(const char* rhs)
{
    SetType(JSON_STRING);
    *stringValue_ = rhs;

    return *this;
}

JSONValue& JSONValue::operator =(const JSONArray& rhs)
{
    SetType(JSON_ARRAY);
    *arrayValue_ = rhs;

    return *this;
}

JSONValue& JSONValue::operator =(const JSONObject& rhs)
{
    SetType(JSON_OBJECT);
    *objectValue_ = rhs;

    return *this;
}

JSONValue& JSONValue::operator =(const JSONValue& rhs)
{
    if (this == &rhs)
        return *this;

    SetType(rhs.GetValueType(), rhs.GetNumberType());

    switch (GetValueType())
    {
    case JSON_BOOL:
        boolValue_ = rhs.boolValue_;
        break;

    case JSON_NUMBER:
        numberValue_ = rhs.numberValue_;
        break;

    case JSON_STRING:
        *stringValue_ = *rhs.stringValue_;
        break;

    case JSON_ARRAY:
        *arrayValue_ = *rhs.arrayValue_;
        break;

    case JSON_OBJECT:
        *objectValue_ = *rhs.objectValue_;

    default:
        break;
    }

    return *this;
}

JSONValueType JSONValue::GetValueType() const
{
    return (JSONValueType)(type_ >> 16);
}

JSONNumberType JSONValue::GetNumberType() const
{
    return (JSONNumberType)(type_ & 0xffff);
}

JSONValue& JSONValue::operator [](unsigned index)
{
    // Convert to array type
    SetType(JSON_ARRAY);

    return (*arrayValue_)[index];
}

const JSONValue& JSONValue::operator [](unsigned index) const
{
    if (GetValueType() != JSON_ARRAY)
        return EMPTY;

    return (*arrayValue_)[index];
}

void JSONValue::Push(const JSONValue& value)
{
    // Convert to array type
    SetType(JSON_ARRAY);

    arrayValue_->Push(value);
}

void JSONValue::Pop()
{
    if (GetValueType() != JSON_ARRAY)
        return;

    arrayValue_->Pop();
}

void JSONValue::Insert(unsigned pos, const JSONValue& value)
{
    if (GetValueType() != JSON_ARRAY)
        return;

    arrayValue_->Insert(pos, value);
}

void JSONValue::Erase(unsigned pos, unsigned length)
{
    if (GetValueType() != JSON_ARRAY)
        return;

    arrayValue_->Erase(pos, length);
}

void JSONValue::Resize(unsigned newSize)
{
    // Convert to array type
    SetType(JSON_ARRAY);

    arrayValue_->Resize(newSize);
}

unsigned JSONValue::Size() const
{
    if (GetValueType() == JSON_ARRAY)
        return arrayValue_->Size();

    return 0;
}

JSONValue& JSONValue::operator [](const String& key)
{
    // Convert to object type
    SetType(JSON_OBJECT);

    return (*objectValue_)[key];
}

const JSONValue& JSONValue::operator [](const String& key) const
{
    if (GetValueType() != JSON_OBJECT)
        return EMPTY;

    return (*objectValue_)[key];
}

void JSONValue::Set(const String& key, const JSONValue& value)
{
    // Convert to object type
    SetType(JSON_OBJECT);

    (*objectValue_)[key] = value;
}

const JSONValue& JSONValue::Get(const String& key) const
{
    if (GetValueType() != JSON_OBJECT)
        return EMPTY;

    JSONObject::ConstIterator i = objectValue_->Find(key);
    if (i == objectValue_->End())
        return EMPTY;

    return i->second_;
}

bool JSONValue::Erase(const String& key)
{
    if (GetValueType() != JSON_OBJECT)
        return false;

    return objectValue_->Erase(key);
}

bool JSONValue::Contains(const String& key) const
{
    if  (GetValueType() != JSON_OBJECT)
        return false;

    return objectValue_->Contains(key);
}

JSONObjectIterator JSONValue::Begin()
{
    // Convert to object type.
    SetType(JSON_OBJECT);

    return objectValue_->Begin();
}

ConstJSONObjectIterator JSONValue::Begin() const
{
    if (GetValueType() != JSON_OBJECT)
        return emptyObject.Begin();

    return objectValue_->Begin();
}

JSONObjectIterator JSONValue::End()
{
    // Convert to object type.
    SetType(JSON_OBJECT);

    return objectValue_->Begin();
}

ConstJSONObjectIterator JSONValue::End() const
{
    if (GetValueType() != JSON_OBJECT)
        return emptyObject.End();

    return objectValue_->End();
}

void JSONValue::Clear()
{
    if (GetValueType() == JSON_ARRAY)
        arrayValue_->Clear();
    else if (GetValueType() == JSON_OBJECT)
        objectValue_->Clear();
}

void JSONValue::SetType(JSONValueType valueType, JSONNumberType numberType)
{
    int type = (valueType << 16) | numberType;
    if (type == type_)
        return;

    switch (GetValueType())
    {
    case JSON_STRING:
        delete stringValue_;
        break;

    case JSON_ARRAY:
        delete arrayValue_;
        break;

    case JSON_OBJECT:
        delete objectValue_;
        break;

    default:
        break;
    }

    type_ = type;

    switch (GetValueType())
    {
    case JSON_STRING:
        stringValue_ = new String();
        break;

    case JSON_ARRAY:
        arrayValue_ = new JSONArray();
        break;

    case JSON_OBJECT:
        objectValue_ = new JSONObject();
        break;

    default:
        break;
    }
}

void JSONValue::SetVariant(const Variant& variant, Context* context)
{
    if (!IsNull())
    {
        URHO3D_LOGWARNING("JsonValue is not null");
    }

    (*this)["type"] = variant.GetTypeName();
    (*this)["value"].SetVariantValue(variant, context);
}

Variant JSONValue::GetVariant() const
{
    VariantType type = Variant::GetTypeFromName((*this)["type"].GetString());
    return (*this)["value"].GetVariantValue(type);
}

void JSONValue::SetVariantValue(const Variant& variant, Context* context)
{
    if (!IsNull())
    {
        URHO3D_LOGWARNING("JsonValue is not null");
    }

    switch (variant.GetType())
    {
    case VAR_BOOL:
        *this = variant.GetBool();
        return;

    case VAR_INT:
        *this = variant.GetInt();
        return;

    case VAR_FLOAT:
        *this = variant.GetFloat();
        return;

    case VAR_DOUBLE:
        *this = variant.GetDouble();
        return;

    case VAR_STRING:
        *this = variant.GetString();
        return;

    case VAR_VARIANTVECTOR:
        SetVariantVector(variant.GetVariantVector(), context);
        return;

    case VAR_VARIANTMAP:
        SetVariantMap(variant.GetVariantMap(), context);
        return;

    case VAR_RESOURCEREF:
        {
            if (!context)
            {
                URHO3D_LOGERROR("Context must not be null for ResourceRef");
                return;
            }

            const ResourceRef& ref = variant.GetResourceRef();
            *this = String(context->GetTypeName(ref.type_)) + ";" + ref.name_;
        }
        return;

    case VAR_RESOURCEREFLIST:
        {
            if (!context)
            {
                URHO3D_LOGERROR("Context must not be null for ResourceRefList");
                return;
            }

            const ResourceRefList& refList = variant.GetResourceRefList();
            String str(context->GetTypeName(refList.type_));
            for (unsigned i = 0; i < refList.names_.Size(); ++i)
            {
                str += ";";
                str += refList.names_[i];
            }
            *this = str;
        }
        return;

    case VAR_STRINGVECTOR:
        {
            const StringVector& vector = variant.GetStringVector();
            Resize(vector.Size());
            for (unsigned i = 0; i < vector.Size(); ++i)
                (*this)[i] = vector[i];
        }
        return;

    default:
        *this = variant.ToString();
    }
}

Variant JSONValue::GetVariantValue(VariantType type) const
{
    Variant variant;
    switch (type)
    {
    case VAR_BOOL:
        variant = GetBool();
        break;

    case VAR_INT:
        variant = GetInt();
        break;

    case VAR_FLOAT:
        variant = GetFloat();
        break;

    case VAR_DOUBLE:
        variant = GetDouble();
        break;

    case VAR_STRING:
        variant = GetString();
        break;

    case VAR_VARIANTVECTOR:
        variant = GetVariantVector();
        break;

    case VAR_VARIANTMAP:
        variant = GetVariantMap();
        break;

    case VAR_RESOURCEREF:
        {
            ResourceRef ref;
            Vector<String> values = GetString().Split(';');
            if (values.Size() == 2)
            {
                ref.type_ = values[0];
                ref.name_ = values[1];
            }
            variant = ref;
        }
        break;

    case VAR_RESOURCEREFLIST:
        {
            ResourceRefList refList;
            Vector<String> values = GetString().Split(';', true);
            if (values.Size() >= 1)
            {
                refList.type_ = values[0];
                refList.names_.Resize(values.Size() - 1);
                for (unsigned i = 1; i < values.Size(); ++i)
                    refList.names_[i - 1] = values[i];
            }
            variant = refList;
        }
        break;

    case VAR_STRINGVECTOR:
        {
            StringVector vector;
            for (unsigned i = 0; i < Size(); ++i)
                vector.Push((*this)[i].GetString());
            variant = vector;
        }
        break;

    default:
        variant.FromString(type, GetString());
    }

    return variant;
}

void JSONValue::SetVariantMap(const VariantMap& variantMap, Context* context)
{
    SetType(JSON_OBJECT);
    for (VariantMap::ConstIterator i = variantMap.Begin(); i != variantMap.End(); ++i)
        (*this)[i->first_.ToString()].SetVariant(i->second_);
}

VariantMap JSONValue::GetVariantMap() const
{
    VariantMap variantMap;
    if (!IsObject())
    {
        URHO3D_LOGERROR("JSONValue is not a object");
        return variantMap;
    }

    for (ConstJSONObjectIterator i = Begin(); i != End(); ++i)
    {
        StringHash key(ToUInt(i->first_));
        Variant variant = i->second_.GetVariant();
        variantMap[key] = variant;
    }

    return variantMap;
}

void JSONValue::SetVariantVector(const VariantVector& variantVector, Context* context)
{
    SetType(JSON_ARRAY);
    for (unsigned i = 0; i < variantVector.Size(); ++i)
        (*this)[i].SetVariant(variantVector[i]);
}

VariantVector JSONValue::GetVariantVector() const
{
    VariantVector variantVector;
    if (!IsArray())
    {
        URHO3D_LOGERROR("JSONValue is not a array");
        return variantVector;
    }

    for (unsigned i = 0; i < Size(); ++i)
    {
        Variant variant = (*this)[i].GetVariant();
        variantVector.Push(variant);
    }

    return variantVector;
}

}<commit_msg>Squashed commit of the following:<commit_after>//
// Copyright (c) 2008-2015 the Urho3D project.
//
// 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:addmember
//
// 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 "../Precompiled.h"

#include "../Core/Context.h"
#include "../IO/Log.h"
#include "../Resource/JSONValue.h"

#include "../DebugNew.h"

namespace Urho3D
{

const JSONValue JSONValue::EMPTY;
const JSONArray JSONValue::emptyArray;
const JSONObject JSONValue::emptyObject;

JSONValue& JSONValue::operator =(bool rhs)
{
    SetType(JSON_BOOL);
    boolValue_ = rhs;

    return *this;
}

JSONValue& JSONValue::operator =(int rhs)
{
    SetType(JSON_NUMBER, JSONNT_INT);
    numberValue_ = rhs;

    return *this;
}

JSONValue& JSONValue::operator =(unsigned rhs)
{
    SetType(JSON_NUMBER, JSONNT_UINT);
    numberValue_ = rhs;

    return *this;
}

JSONValue& JSONValue::operator =(float rhs)
{
    SetType(JSON_NUMBER, JSONNT_FLOAT_DOUBLE);
    numberValue_ = rhs;

    return *this;
}

JSONValue& JSONValue::operator =(double rhs)
{
    SetType(JSON_NUMBER, JSONNT_FLOAT_DOUBLE);
    numberValue_ = rhs;

    return *this;
}

JSONValue& JSONValue::operator =(const String& rhs)
{
    SetType(JSON_STRING);
    *stringValue_ = rhs;

    return *this;
}

JSONValue& JSONValue::operator =(const char* rhs)
{
    SetType(JSON_STRING);
    *stringValue_ = rhs;

    return *this;
}

JSONValue& JSONValue::operator =(const JSONArray& rhs)
{
    SetType(JSON_ARRAY);
    *arrayValue_ = rhs;

    return *this;
}

JSONValue& JSONValue::operator =(const JSONObject& rhs)
{
    SetType(JSON_OBJECT);
    *objectValue_ = rhs;

    return *this;
}

JSONValue& JSONValue::operator =(const JSONValue& rhs)
{
    if (this == &rhs)
        return *this;

    SetType(rhs.GetValueType(), rhs.GetNumberType());

    switch (GetValueType())
    {
    case JSON_BOOL:
        boolValue_ = rhs.boolValue_;
        break;

    case JSON_NUMBER:
        numberValue_ = rhs.numberValue_;
        break;

    case JSON_STRING:
        *stringValue_ = *rhs.stringValue_;
        break;

    case JSON_ARRAY:
        *arrayValue_ = *rhs.arrayValue_;
        break;

    case JSON_OBJECT:
        *objectValue_ = *rhs.objectValue_;

    default:
        break;
    }

    return *this;
}

JSONValueType JSONValue::GetValueType() const
{
    return (JSONValueType)(type_ >> 16);
}

JSONNumberType JSONValue::GetNumberType() const
{
    return (JSONNumberType)(type_ & 0xffff);
}

JSONValue& JSONValue::operator [](unsigned index)
{
    // Convert to array type
    SetType(JSON_ARRAY);

    return (*arrayValue_)[index];
}

const JSONValue& JSONValue::operator [](unsigned index) const
{
    if (GetValueType() != JSON_ARRAY)
        return EMPTY;

    return (*arrayValue_)[index];
}

void JSONValue::Push(const JSONValue& value)
{
    // Convert to array type
    SetType(JSON_ARRAY);

    arrayValue_->Push(value);
}

void JSONValue::Pop()
{
    if (GetValueType() != JSON_ARRAY)
        return;

    arrayValue_->Pop();
}

void JSONValue::Insert(unsigned pos, const JSONValue& value)
{
    if (GetValueType() != JSON_ARRAY)
        return;

    arrayValue_->Insert(pos, value);
}

void JSONValue::Erase(unsigned pos, unsigned length)
{
    if (GetValueType() != JSON_ARRAY)
        return;

    arrayValue_->Erase(pos, length);
}

void JSONValue::Resize(unsigned newSize)
{
    // Convert to array type
    SetType(JSON_ARRAY);

    arrayValue_->Resize(newSize);
}

unsigned JSONValue::Size() const
{
    if (GetValueType() == JSON_ARRAY)
        return arrayValue_->Size();

    return 0;
}

JSONValue& JSONValue::operator [](const String& key)
{
    // Convert to object type
    SetType(JSON_OBJECT);

    return (*objectValue_)[key];
}

const JSONValue& JSONValue::operator [](const String& key) const
{
    if (GetValueType() != JSON_OBJECT)
        return EMPTY;

    return (*objectValue_)[key];
}

void JSONValue::Set(const String& key, const JSONValue& value)
{
    // Convert to object type
    SetType(JSON_OBJECT);

    (*objectValue_)[key] = value;
}

const JSONValue& JSONValue::Get(const String& key) const
{
    if (GetValueType() != JSON_OBJECT)
        return EMPTY;

    JSONObject::ConstIterator i = objectValue_->Find(key);
    if (i == objectValue_->End())
        return EMPTY;

    return i->second_;
}

bool JSONValue::Erase(const String& key)
{
    if (GetValueType() != JSON_OBJECT)
        return false;

    return objectValue_->Erase(key);
}

bool JSONValue::Contains(const String& key) const
{
    if  (GetValueType() != JSON_OBJECT)
        return false;

    return objectValue_->Contains(key);
}

JSONObjectIterator JSONValue::Begin()
{
    // Convert to object type.
    SetType(JSON_OBJECT);

    return objectValue_->Begin();
}

ConstJSONObjectIterator JSONValue::Begin() const
{
    if (GetValueType() != JSON_OBJECT)
        return emptyObject.Begin();

    return objectValue_->Begin();
}

JSONObjectIterator JSONValue::End()
{
    // Convert to object type.
    SetType(JSON_OBJECT);

    return objectValue_->Begin();
}

ConstJSONObjectIterator JSONValue::End() const
{
    if (GetValueType() != JSON_OBJECT)
        return emptyObject.End();

    return objectValue_->End();
}

void JSONValue::Clear()
{
    if (GetValueType() == JSON_ARRAY)
        arrayValue_->Clear();
    else if (GetValueType() == JSON_OBJECT)
        objectValue_->Clear();
}

void JSONValue::SetType(JSONValueType valueType, JSONNumberType numberType)
{
    int type = (valueType << 16) | numberType;
    if (type == type_)
        return;

    switch (GetValueType())
    {
    case JSON_STRING:
        delete stringValue_;
        break;

    case JSON_ARRAY:
        delete arrayValue_;
        break;

    case JSON_OBJECT:
        delete objectValue_;
        break;

    default:
        break;
    }

    type_ = type;

    switch (GetValueType())
    {
    case JSON_STRING:
        stringValue_ = new String();
        break;

    case JSON_ARRAY:
        arrayValue_ = new JSONArray();
        break;

    case JSON_OBJECT:
        objectValue_ = new JSONObject();
        break;

    default:
        break;
    }
}

void JSONValue::SetVariant(const Variant& variant, Context* context)
{
    if (!IsNull())
    {
        URHO3D_LOGWARNING("JsonValue is not null");
    }

    (*this)["type"] = variant.GetTypeName();
    (*this)["value"].SetVariantValue(variant, context);
}

Variant JSONValue::GetVariant() const
{
    VariantType type = Variant::GetTypeFromName((*this)["type"].GetString());
    return (*this)["value"].GetVariantValue(type);
}

void JSONValue::SetVariantValue(const Variant& variant, Context* context)
{
    if (!IsNull())
    {
        URHO3D_LOGWARNING("JsonValue is not null");
    }

    switch (variant.GetType())
    {
    case VAR_BOOL:
        *this = variant.GetBool();
        return;

    case VAR_INT:
        *this = variant.GetInt();
        return;

    case VAR_FLOAT:
        *this = variant.GetFloat();
        return;

    case VAR_DOUBLE:
        *this = variant.GetDouble();
        return;

    case VAR_STRING:
        *this = variant.GetString();
        return;

    case VAR_VARIANTVECTOR:
        SetVariantVector(variant.GetVariantVector(), context);
        return;

    case VAR_VARIANTMAP:
        SetVariantMap(variant.GetVariantMap(), context);
        return;

    case VAR_RESOURCEREF:
        {
            if (!context)
            {
                URHO3D_LOGERROR("Context must not be null for ResourceRef");
                return;
            }

            const ResourceRef& ref = variant.GetResourceRef();
            *this = String(context->GetTypeName(ref.type_)) + ";" + ref.name_;
        }
        return;

    case VAR_RESOURCEREFLIST:
        {
            if (!context)
            {
                URHO3D_LOGERROR("Context must not be null for ResourceRefList");
                return;
            }

            const ResourceRefList& refList = variant.GetResourceRefList();
            String str(context->GetTypeName(refList.type_));
            for (unsigned i = 0; i < refList.names_.Size(); ++i)
            {
                str += ";";
                str += refList.names_[i];
            }
            *this = str;
        }
        return;

    case VAR_STRINGVECTOR:
        {
            const StringVector& vector = variant.GetStringVector();
            Resize(vector.Size());
            for (unsigned i = 0; i < vector.Size(); ++i)
                (*this)[i] = vector[i];
        }
        return;

    default:
        *this = variant.ToString();
    }
}

Variant JSONValue::GetVariantValue(VariantType type) const
{
    Variant variant;
    switch (type)
    {
    case VAR_BOOL:
        variant = GetBool();
        break;

    case VAR_INT:
        variant = GetInt();
        break;

    case VAR_FLOAT:
        variant = GetFloat();
        break;

    case VAR_DOUBLE:
        variant = GetDouble();
        break;

    case VAR_STRING:
        variant = GetString();
        break;

    case VAR_VARIANTVECTOR:
        variant = GetVariantVector();
        break;

    case VAR_VARIANTMAP:
        variant = GetVariantMap();
        break;

    case VAR_RESOURCEREF:
        {
            ResourceRef ref;
            Vector<String> values = GetString().Split(';');
            if (values.Size() == 2)
            {
                ref.type_ = values[0];
                ref.name_ = values[1];
            }
            variant = ref;
        }
        break;

    case VAR_RESOURCEREFLIST:
        {
            ResourceRefList refList;
            Vector<String> values = GetString().Split(';', true);
            if (values.Size() >= 1)
            {
                refList.type_ = values[0];
                refList.names_.Resize(values.Size() - 1);
                for (unsigned i = 1; i < values.Size(); ++i)
                    refList.names_[i - 1] = values[i];
            }
            variant = refList;
        }
        break;

    case VAR_STRINGVECTOR:
        {
            StringVector vector;
            for (unsigned i = 0; i < Size(); ++i)
                vector.Push((*this)[i].GetString());
            variant = vector;
        }
        break;

    default:
        variant.FromString(type, GetString());
    }

    return variant;
}

void JSONValue::SetVariantMap(const VariantMap& variantMap, Context* context)
{
    SetType(JSON_OBJECT);
    for (VariantMap::ConstIterator i = variantMap.Begin(); i != variantMap.End(); ++i)
        (*this)[i->first_.ToString()].SetVariant(i->second_);
}

VariantMap JSONValue::GetVariantMap() const
{
    VariantMap variantMap;
    if (!IsObject())
    {
        URHO3D_LOGERROR("JSONValue is not a object");
        return variantMap;
    }

    for (ConstJSONObjectIterator i = Begin(); i != End(); ++i)
    {
        StringHash key(ToUInt(i->first_));
        Variant variant = i->second_.GetVariant();
        variantMap[key] = variant;
    }

    return variantMap;
}

void JSONValue::SetVariantVector(const VariantVector& variantVector, Context* context)
{
    SetType(JSON_ARRAY);
    arrayValue_->Reserve(variantVector.Size());
    for (unsigned i = 0; i < variantVector.Size(); ++i)
    {
        JSONValue val;
        val.SetVariant(variantVector[i], context);
        arrayValue_->Push(val);
    }
}

VariantVector JSONValue::GetVariantVector() const
{
    VariantVector variantVector;
    if (!IsArray())
    {
        URHO3D_LOGERROR("JSONValue is not a array");
        return variantVector;
    }

    for (unsigned i = 0; i < Size(); ++i)
    {
        Variant variant = (*this)[i].GetVariant();
        variantVector.Push(variant);
    }

    return variantVector;
}

}
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2012 Scientific Computing and Imaging Institute,
   University of Utah.

   License for the specific language governing rights and limitations under
   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 <iostream>
#include <QtGui>
#include <Interface/Application/NetworkExecutionProgressBar.h>

using namespace SCIRun::Gui;

NetworkExecutionProgressBar::NetworkExecutionProgressBar(QWidget* parent) : numModulesDone_(0), totalModules_(0)
{
  barAction_ = new QWidgetAction(parent);
  barAction_->setDefaultWidget(progressBar_ = new QProgressBar(parent));
  barAction_->setVisible(true);

  counterAction_ = new QWidgetAction(parent);
  counterAction_->setDefaultWidget(counterLabel_ = new QLabel(counterLabelString(), parent));
  counterAction_->setVisible(true);
}

QList<QAction*> NetworkExecutionProgressBar::actions() const
{
  return QList<QAction*>() << barAction_ << counterAction_;
}

void NetworkExecutionProgressBar::updateTotalModules(int count)
{
  //std::cout << "updateTotalModules: " << count << std::endl;
  if (count >= 0 && count != totalModules_)
  {
    totalModules_ = count;
    numModulesDone_ = 0;
    counterLabel_->setText(counterLabelString());
    progressBar_->setMaximum(count);
    progressBar_->setValue(0);
  }
}
void NetworkExecutionProgressBar::incrementModulesDone()
{
  //std::cout << "incrementModulesDone: " << numModulesDone_ << std::endl;
  if (numModulesDone_ < totalModules_)
  {
    numModulesDone_++;
    counterLabel_->setText(counterLabelString());
    progressBar_->setValue(numModulesDone_);
  }
}

void NetworkExecutionProgressBar::resetModulesDone()
{
  //std::cout << "resetModulesDone: " << std::endl;
  numModulesDone_ = 0;
  counterLabel_->setText(counterLabelString());
  progressBar_->setValue(numModulesDone_);
}

QString NetworkExecutionProgressBar::counterLabelString() const
{
  return QString("  %1 / %2  ").arg(numModulesDone_).arg(totalModules_);
}<commit_msg>Closes #83.<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2012 Scientific Computing and Imaging Institute,
   University of Utah.

   License for the specific language governing rights and limitations under
   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 <iostream>
#include <QtGui>
#include <Interface/Application/NetworkExecutionProgressBar.h>

using namespace SCIRun::Gui;

NetworkExecutionProgressBar::NetworkExecutionProgressBar(QWidget* parent) : numModulesDone_(0), totalModules_(0)
{
  barAction_ = new QWidgetAction(parent);
  barAction_->setDefaultWidget(progressBar_ = new QProgressBar(parent));
  barAction_->setVisible(true);

  counterAction_ = new QWidgetAction(parent);
  counterAction_->setDefaultWidget(counterLabel_ = new QLabel(counterLabelString(), parent));
  counterAction_->setVisible(true);
}

QList<QAction*> NetworkExecutionProgressBar::actions() const
{
  return QList<QAction*>() << barAction_ << counterAction_;
}

void NetworkExecutionProgressBar::updateTotalModules(int count)
{
  //std::cout << "updateTotalModules: " << count << std::endl;
  if (count >= 0 && count != totalModules_)
  {
    totalModules_ = count;
    numModulesDone_ = 0;
    counterLabel_->setText(counterLabelString());
    if (0 != count)
      progressBar_->setMaximum(count);
    progressBar_->setValue(0);
  }
}
void NetworkExecutionProgressBar::incrementModulesDone()
{
  //std::cout << "incrementModulesDone: " << numModulesDone_ << std::endl;
  if (numModulesDone_ < totalModules_)
  {
    numModulesDone_++;
    counterLabel_->setText(counterLabelString());
    progressBar_->setValue(numModulesDone_);
  }
}

void NetworkExecutionProgressBar::resetModulesDone()
{
  //std::cout << "resetModulesDone: " << std::endl;
  numModulesDone_ = 0;
  counterLabel_->setText(counterLabelString());
  progressBar_->setValue(numModulesDone_);
}

QString NetworkExecutionProgressBar::counterLabelString() const
{
  return QString("  %1 / %2  ").arg(numModulesDone_).arg(totalModules_);
}<|endoftext|>


<commit_before>// smallpt, a Path Tracer by Kevin Beason, 2008
//
// Modified by Peter uek
// For the original code, see github.com/munificient/smallpt
// For the original license, see smallpt.LICENSE.txt

#include <cmath>
#include <cstdlib>
#include <cstdio>

#include <sycl.hpp>

#include "classes.h"
#include "msvc.h"

namespace ns_sycl_gtx {

static const int numSpheres = 9;
Sphere spheres[numSpheres] = {//Scene: radius, position, emission, color, material
	Sphere(1e5, Vec(1e5 + 1, 40.8, 81.6), Vec(), Vec(.75, .25, .25), DIFF),//Left
	Sphere(1e5, Vec(-1e5 + 99, 40.8, 81.6), Vec(), Vec(.25, .25, .75), DIFF),//Rght
	Sphere(1e5, Vec(50, 40.8, 1e5), Vec(), Vec(.75, .75, .75), DIFF),//Back
	Sphere(1e5, Vec(50, 40.8, -1e5 + 170), Vec(), Vec(), DIFF),//Frnt
	Sphere(1e5, Vec(50, 1e5, 81.6), Vec(), Vec(.75, .75, .75), DIFF),//Botm
	Sphere(1e5, Vec(50, -1e5 + 81.6, 81.6), Vec(), Vec(.75, .75, .75), DIFF),//Top
	Sphere(16.5, Vec(27, 16.5, 47), Vec(), Vec(1, 1, 1)*.999, SPEC),//Mirr
	Sphere(16.5, Vec(73, 16.5, 78), Vec(), Vec(1, 1, 1)*.999, REFR),//Glas
	Sphere(600, Vec(50, 681.6 - .27, 81.6), Vec(12, 12, 12), Vec(), DIFF) //Lite
};

inline bool intersect(const Ray& r, double& t, int& id) {
	double d;
	double inf = t = 1e20;
	for(int i = numSpheres; i > 0;) {
		--i;
		if((d = spheres[i].intersect(r)) && d < t) {
			t = d;
			id = i;
		}
	}
	return t < inf;
}

enum class DoNext {
	Return, ContinueLoop, Proceed
};

DoNext radianceInner(
	Ray& r, int& depth, unsigned short* Xi,	// Original parameters
	double& t, int& id, Vec& cl, Vec& cf,	// Passed references
	// Output references
	double& Re, double& Tr, double& P, double& RP, double& TP, Ray& reflRay, Vec& x, Vec& tdir
) {
	if(!intersect(r, t, id)) {
		// if miss, don't add anything
		return DoNext::Return;
	}
	const Sphere& obj = spheres[id]; // the hit object
	x = r.o + r.d*t;
	Vec n = (x - obj.p).norm();
	Vec nl = n;
	if(n.dot(r.d) > 0) {
		nl = nl * -1;
	}
	Vec f = obj.c;
	double p;	// max refl
	if(f.x > f.y && f.x > f.z) {
		p = f.x;
	}
	else if(f.y > f.z) {
		p = f.y;
	}
	else {
		p = f.z;
	}

	cl = cl + cf.mult(obj.e);

	depth += 1;
	if(depth > 5) {
		if(erand48(Xi) < p) {
			f = f*(1 / p);
		}
		else {
			return DoNext::Return;
		}
	}

	cf = cf.mult(f);

	if(obj.refl == DIFF) {	// Ideal DIFFUSE reflection
		double r1 = 2 * M_PI*erand48(Xi), r2 = erand48(Xi), r2s = sqrt(r2);
		Vec w = nl;
		Vec u;
		if(fabs(w.x) > .1) {
			u.y = 1;
		}
		else {
			u.x = 1;
		}
		u = (u % w).norm();
		Vec v = w%u;
		Vec d = (u*cos(r1)*r2s + v*sin(r1)*r2s + w*sqrt(1 - r2)).norm();

		// Recursion
		r = Ray(x, d);
		return DoNext::ContinueLoop;
	}
	else if(obj.refl == SPEC) {	// Ideal SPECULAR reflection
		// Recursion
		r = Ray(x, r.d - n * 2 * n.dot(r.d));
		return DoNext::ContinueLoop;
	}
	reflRay = Ray(x, r.d - n * 2 * n.dot(r.d));	// Ideal dielectric REFRACTION
	bool into = n.dot(nl) > 0;	// Ray from outside going in?
	double nc = 1;
	double nt = 1.5;
	double nnt;
	if(into) {
		nnt = nc / nt;
	}
	else {
		nnt = nt / nc;
	}
	double ddn = r.d.dot(nl);
	double cos2t;
	if((cos2t = 1 - nnt*nnt*(1 - ddn*ddn)) < 0) {	// Total internal reflection
		// Recursion
		r = reflRay;
		return DoNext::ContinueLoop;
	}
	double tmp = 1;
	if(!into) {
		tmp = -1;
	}
	tdir = (r.d*nnt - n*(tmp*(ddn*nnt + sqrt(cos2t)))).norm();
	double a = nt - nc;
	double b = nt + nc;
	double R0 = a*a / (b*b);
	double c = 1;
	if(into) {
		c += ddn;
	}
	else {
		c -= tdir.dot(n);
	}
	Re = R0 + (1 - R0)*c*c*c*c*c;
	Tr = 1 - Re;
	P = .25 + .5*Re;
	RP = Re / P;
	TP = Tr / (1 - P);

	return DoNext::Proceed;
}

void radiance(Ray r, int depth, unsigned short* Xi, Vec& cl, Vec& cf) {
	double t;	// distance to intersection
	int id = 0;	// id of intersected object

	double Re, Tr, P, RP, TP;
	Ray reflRay(0, 0);
	Vec x, tdir;

	while(true) {
		auto doNext = radianceInner(
			r, depth, Xi,
			t, id, cl, cf,
			Re, Tr, P, RP, TP, reflRay, x, tdir
		);

		if(doNext == DoNext::ContinueLoop) {
			continue;
		}
		if(doNext == DoNext::Return) {
			return;
		}

		if(erand48(Xi) < P) {
			cf = cf * RP;
			r = reflRay;
		}
		else {
			cf = cf * TP;
			r = Ray(x, tdir);
		}
	}
}

template <int depth_ = 0>
Vec radiance(Ray r, unsigned short* Xi, Vec cl = { 0, 0, 0 }, Vec cf = {1, 1, 1}) {
	double t;	// distance to intersection
	int id = 0;	// id of intersected object
	int depth = depth_;

	// cl is accumulated color
	// cf is accumulated reflectance

	double Re, Tr, P, RP, TP;
	Ray reflRay(0, 0);
	Vec x, tdir;

	while(true) {
		auto doNext = radianceInner(
			r, depth, Xi,
			t, id, cl, cf,
			Re, Tr, P, RP, TP, reflRay, x, tdir
		);

		if(doNext == DoNext::ContinueLoop) {
			continue;
		}
		if(doNext == DoNext::Return) {
			return cl;
		}

		if(depth == 1) {
			return radiance<1>(reflRay, Xi, cl, cf * Re) + radiance<1>(Ray(x, tdir), Xi, cl, cf * Tr);
		}
		else if(depth == 2) {
			return radiance<2>(reflRay, Xi, cl, cf * Re) + radiance<2>(Ray(x, tdir), Xi, cl, cf * Tr);
		}
		else {
			radiance(r, depth, Xi, cl, cf);
			return cl;
		}
	}
}

} // namespace ns_sycl_gtx

inline double clamp(double x) {
	if(x < 0) {
		return 0;
	}
	if(x > 1) {
		return 1;
	}
	return x;
}

void compute_sycl_gtx_openmp(int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c) {
	#pragma omp parallel for schedule(dynamic, 1) private(r)
	for(int y = 0; y < h; y++) {						// Loop over image rows
		fprintf(stderr, "\rRendering (%d spp) %5.2f%%", samps * 4, 100.*y / (h - 1));
		for(unsigned short x = 0, Xi[3] = { 0, 0, y*y*y }; x < w; x++) {	// Loop cols
			for(int sy = 0, i = (h - y - 1)*w + x; sy < 2; sy++) {	 // 2x2 subpixel rows
				for(int sx = 0; sx < 2; sx++, r = Vec()) {		// 2x2 subpixel cols
					for(int s = 0; s < samps; s++) {
						double r1 = 2 * erand48(Xi);
						double r2 = 2 * erand48(Xi);

						double dx, dy;
						if(r1 < 1) {
							dx = sqrt(r1) - 1;
						}
						else {
							dx = 1 - sqrt(2 - r1);
						}
						if(r2 < 1) {
							dy = sqrt(r2) - 1;
						}
						else {
							dy = 1 - sqrt(2 - r2);
						}

						Vec d = cx*(((sx + .5 + dx) / 2 + x) / w - .5) + cy*(((sy + .5 + dy) / 2 + y) / h - .5) + cam.d;
						r = r + ns_sycl_gtx::radiance(Ray(cam.o + d * 140, d.norm()), Xi)*(1. / samps);
					} // Camera rays are pushed ^^^^^ forward to start in interior

					c[i] = c[i] + Vec(clamp(r.x), clamp(r.y), clamp(r.z))*.25;
				}
			}
		}
	}
}
void compute_sycl_gtx(int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c, cl::sycl::device_selector& selector) {
	using namespace cl::sycl;

	queue q(selector);

	buffer<Vec> colors(c, range<1>(w*h));

	q.submit([&](handler& cgh) {
		// TODO
	});
}

void compute_sycl_gtx_cpu(int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c) {
	cl::sycl::cpu_selector cpu;
	compute_sycl_gtx(w, h, samps, cam, cx, cy, r, c, cpu);
}

void compute_sycl_gtx_gpu(int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c) {
	cl::sycl::gpu_selector gpu;
	compute_sycl_gtx(w, h, samps, cam, cx, cy, r, c, gpu);
}
<commit_msg>Basic kernel.<commit_after>// smallpt, a Path Tracer by Kevin Beason, 2008
//
// Modified by Peter uek
// For the original code, see github.com/munificient/smallpt
// For the original license, see smallpt.LICENSE.txt

#include <cmath>
#include <cstdlib>
#include <cstdio>

#include <sycl.hpp>

#include "classes.h"
#include "msvc.h"

namespace ns_sycl_gtx {

static const int numSpheres = 9;
Sphere spheres[numSpheres] = {//Scene: radius, position, emission, color, material
	Sphere(1e5, Vec(1e5 + 1, 40.8, 81.6), Vec(), Vec(.75, .25, .25), DIFF),//Left
	Sphere(1e5, Vec(-1e5 + 99, 40.8, 81.6), Vec(), Vec(.25, .25, .75), DIFF),//Rght
	Sphere(1e5, Vec(50, 40.8, 1e5), Vec(), Vec(.75, .75, .75), DIFF),//Back
	Sphere(1e5, Vec(50, 40.8, -1e5 + 170), Vec(), Vec(), DIFF),//Frnt
	Sphere(1e5, Vec(50, 1e5, 81.6), Vec(), Vec(.75, .75, .75), DIFF),//Botm
	Sphere(1e5, Vec(50, -1e5 + 81.6, 81.6), Vec(), Vec(.75, .75, .75), DIFF),//Top
	Sphere(16.5, Vec(27, 16.5, 47), Vec(), Vec(1, 1, 1)*.999, SPEC),//Mirr
	Sphere(16.5, Vec(73, 16.5, 78), Vec(), Vec(1, 1, 1)*.999, REFR),//Glas
	Sphere(600, Vec(50, 681.6 - .27, 81.6), Vec(12, 12, 12), Vec(), DIFF) //Lite
};

inline bool intersect(const Ray& r, double& t, int& id) {
	double d;
	double inf = t = 1e20;
	for(int i = numSpheres; i > 0;) {
		--i;
		if((d = spheres[i].intersect(r)) && d < t) {
			t = d;
			id = i;
		}
	}
	return t < inf;
}

enum class DoNext {
	Return, ContinueLoop, Proceed
};

DoNext radianceInner(
	Ray& r, int& depth, unsigned short* Xi,	// Original parameters
	double& t, int& id, Vec& cl, Vec& cf,	// Passed references
	// Output references
	double& Re, double& Tr, double& P, double& RP, double& TP, Ray& reflRay, Vec& x, Vec& tdir
) {
	if(!intersect(r, t, id)) {
		// if miss, don't add anything
		return DoNext::Return;
	}
	const Sphere& obj = spheres[id]; // the hit object
	x = r.o + r.d*t;
	Vec n = (x - obj.p).norm();
	Vec nl = n;
	if(n.dot(r.d) > 0) {
		nl = nl * -1;
	}
	Vec f = obj.c;
	double p;	// max refl
	if(f.x > f.y && f.x > f.z) {
		p = f.x;
	}
	else if(f.y > f.z) {
		p = f.y;
	}
	else {
		p = f.z;
	}

	cl = cl + cf.mult(obj.e);

	depth += 1;
	if(depth > 5) {
		if(erand48(Xi) < p) {
			f = f*(1 / p);
		}
		else {
			return DoNext::Return;
		}
	}

	cf = cf.mult(f);

	if(obj.refl == DIFF) {	// Ideal DIFFUSE reflection
		double r1 = 2 * M_PI*erand48(Xi), r2 = erand48(Xi), r2s = sqrt(r2);
		Vec w = nl;
		Vec u;
		if(fabs(w.x) > .1) {
			u.y = 1;
		}
		else {
			u.x = 1;
		}
		u = (u % w).norm();
		Vec v = w%u;
		Vec d = (u*cos(r1)*r2s + v*sin(r1)*r2s + w*sqrt(1 - r2)).norm();

		// Recursion
		r = Ray(x, d);
		return DoNext::ContinueLoop;
	}
	else if(obj.refl == SPEC) {	// Ideal SPECULAR reflection
		// Recursion
		r = Ray(x, r.d - n * 2 * n.dot(r.d));
		return DoNext::ContinueLoop;
	}
	reflRay = Ray(x, r.d - n * 2 * n.dot(r.d));	// Ideal dielectric REFRACTION
	bool into = n.dot(nl) > 0;	// Ray from outside going in?
	double nc = 1;
	double nt = 1.5;
	double nnt;
	if(into) {
		nnt = nc / nt;
	}
	else {
		nnt = nt / nc;
	}
	double ddn = r.d.dot(nl);
	double cos2t;
	if((cos2t = 1 - nnt*nnt*(1 - ddn*ddn)) < 0) {	// Total internal reflection
		// Recursion
		r = reflRay;
		return DoNext::ContinueLoop;
	}
	double tmp = 1;
	if(!into) {
		tmp = -1;
	}
	tdir = (r.d*nnt - n*(tmp*(ddn*nnt + sqrt(cos2t)))).norm();
	double a = nt - nc;
	double b = nt + nc;
	double R0 = a*a / (b*b);
	double c = 1;
	if(into) {
		c += ddn;
	}
	else {
		c -= tdir.dot(n);
	}
	Re = R0 + (1 - R0)*c*c*c*c*c;
	Tr = 1 - Re;
	P = .25 + .5*Re;
	RP = Re / P;
	TP = Tr / (1 - P);

	return DoNext::Proceed;
}

void radiance(Ray r, int depth, unsigned short* Xi, Vec& cl, Vec& cf) {
	double t;	// distance to intersection
	int id = 0;	// id of intersected object

	double Re, Tr, P, RP, TP;
	Ray reflRay(0, 0);
	Vec x, tdir;

	while(true) {
		auto doNext = radianceInner(
			r, depth, Xi,
			t, id, cl, cf,
			Re, Tr, P, RP, TP, reflRay, x, tdir
		);

		if(doNext == DoNext::ContinueLoop) {
			continue;
		}
		if(doNext == DoNext::Return) {
			return;
		}

		if(erand48(Xi) < P) {
			cf = cf * RP;
			r = reflRay;
		}
		else {
			cf = cf * TP;
			r = Ray(x, tdir);
		}
	}
}

template <int depth_ = 0>
Vec radiance(Ray r, unsigned short* Xi, Vec cl = { 0, 0, 0 }, Vec cf = {1, 1, 1}) {
	double t;	// distance to intersection
	int id = 0;	// id of intersected object
	int depth = depth_;

	// cl is accumulated color
	// cf is accumulated reflectance

	double Re, Tr, P, RP, TP;
	Ray reflRay(0, 0);
	Vec x, tdir;

	while(true) {
		auto doNext = radianceInner(
			r, depth, Xi,
			t, id, cl, cf,
			Re, Tr, P, RP, TP, reflRay, x, tdir
		);

		if(doNext == DoNext::ContinueLoop) {
			continue;
		}
		if(doNext == DoNext::Return) {
			return cl;
		}

		if(depth == 1) {
			return radiance<1>(reflRay, Xi, cl, cf * Re) + radiance<1>(Ray(x, tdir), Xi, cl, cf * Tr);
		}
		else if(depth == 2) {
			return radiance<2>(reflRay, Xi, cl, cf * Re) + radiance<2>(Ray(x, tdir), Xi, cl, cf * Tr);
		}
		else {
			radiance(r, depth, Xi, cl, cf);
			return cl;
		}
	}
}

} // namespace ns_sycl_gtx

inline double clamp(double x) {
	if(x < 0) {
		return 0;
	}
	if(x > 1) {
		return 1;
	}
	return x;
}

void compute_sycl_gtx_openmp(int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c) {
	#pragma omp parallel for schedule(dynamic, 1) private(r)
	for(int y = 0; y < h; y++) {						// Loop over image rows
		fprintf(stderr, "\rRendering (%d spp) %5.2f%%", samps * 4, 100.*y / (h - 1));
		for(unsigned short x = 0, Xi[3] = { 0, 0, y*y*y }; x < w; x++) {	// Loop cols
			for(int sy = 0, i = (h - y - 1)*w + x; sy < 2; sy++) {	 // 2x2 subpixel rows
				for(int sx = 0; sx < 2; sx++, r = Vec()) {		// 2x2 subpixel cols
					for(int s = 0; s < samps; s++) {
						double r1 = 2 * erand48(Xi);
						double r2 = 2 * erand48(Xi);

						double dx, dy;
						if(r1 < 1) {
							dx = sqrt(r1) - 1;
						}
						else {
							dx = 1 - sqrt(2 - r1);
						}
						if(r2 < 1) {
							dy = sqrt(r2) - 1;
						}
						else {
							dy = 1 - sqrt(2 - r2);
						}

						Vec d = cx*(((sx + .5 + dx) / 2 + x) / w - .5) + cy*(((sy + .5 + dy) / 2 + y) / h - .5) + cam.d;
						r = r + ns_sycl_gtx::radiance(Ray(cam.o + d * 140, d.norm()), Xi)*(1. / samps);
					} // Camera rays are pushed ^^^^^ forward to start in interior

					c[i] = c[i] + Vec(clamp(r.x), clamp(r.y), clamp(r.z))*.25;
				}
			}
		}
	}
}

void compute_sycl_gtx(int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* clrs, cl::sycl::device_selector& selector) {
	using namespace cl::sycl;

	queue q(selector);

	buffer<Vec> colors(clrs, range<1>(w*h));

	q.submit([&](handler& cgh) {
		auto c = colors.get_access<access::read_write, access::global_buffer>();

		// TODO: Should not be mutable
		cgh.parallel_for<class smallpt>(range<2>(w, h), [=](id<2> index) mutable {
			auto x = index[0];
			auto y = index[1];
			unsigned short Xi[3] = { 0, 0, (size_t)y*y*y };	// TODO
			int1 i = (h - y - 1)*w + x;

			// 2x2 subpixel rows
			SYCL_FOR(int1 sy = 0, sy < 2, sy++)
			SYCL_BEGIN {
				// 2x2 subpixel cols
				SYCL_FOR(int1 sx = 0, sx < 2, sx++)
				SYCL_BEGIN {
					SYCL_FOR(int1 s = 0, s < samps, s++) {
						double2 rnew;
						rnew.x = 2 * erand48(Xi);
						rnew.y = 2 * erand48(Xi);

						double2 dd;

						SYCL_IF(rnew.x < 1)
						SYCL_BEGIN {
							dd.x = sqrt(rnew.x) - 1;
						}
						SYCL_END
						SYCL_ELSE
						SYCL_BEGIN {
							dd.x = 1 - sqrt(2 - rnew.x);
						}
						SYCL_END

						SYCL_IF(rnew.y < 1)
						SYCL_BEGIN {
							dd.y = sqrt(rnew.y) - 1;
						}
						SYCL_END
						SYCL_ELSE
						SYCL_BEGIN {
							dd.y = 1 - sqrt(2 - rnew.y);
						}
						SYCL_END

						Vec d = cx * (((sx + .5 + rnew.x) / 2 + x) / w - .5) +
								cy * (((sy + .5 + rnew.y) / 2 + y) / h - .5) +
								cam.d;

						// TODO:
						//r = r + ns_sycl_gtx::radiance(Ray(cam.o + d * 140, d.norm()), Xi)*(1. / samps);
					} // Camera rays are pushed ^^^^^ forward to start in interior

					c[i] = c[i] + Vec(clamp(r.x), clamp(r.y), clamp(r.z))*.25;

					r = Vec();
				}
				SYCL_END
			}
			SYCL_END
		});
	});
}

void compute_sycl_gtx_cpu(int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c) {
	cl::sycl::cpu_selector cpu;
	compute_sycl_gtx(w, h, samps, cam, cx, cy, r, c, cpu);
}

void compute_sycl_gtx_gpu(int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c) {
	cl::sycl::gpu_selector gpu;
	compute_sycl_gtx(w, h, samps, cam, cx, cy, r, c, gpu);
}
<|endoftext|>


<commit_before>/*=========================================================================
*
*  Copyright NumFOCUS
*
*  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.txt
*
*  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 "sitkMacro.h"

#include "SimpleITKTestHarness.h"

static const char * DESCRIPTION = "We expect this exception";

class sitkExceptionsTest
  : public ::testing::Test
{
public:

  void ThrowsitkException( )
  {
    sitkExceptionMacro( << DESCRIPTION );
  }
};

TEST_F(sitkExceptionsTest, Test1) {
  ASSERT_THROW( ThrowsitkException(), ::itk::simple::GenericException );

  try
    {
    ThrowsitkException();
    }
  catch ( ::itk::simple::GenericException &e )
    {
    // could do some nifty testing here too
    EXPECT_EQ ( e.GetNameOfClass(), std::string("GenericException") );
    //EXPECT_NE ( std::string ( e.GetLocation() ),  "" ); HACK FIXME
    // exception revision
    return;
    }

  // should gotten that exception
  FAIL();
}

TEST_F(sitkExceptionsTest, Test2) {

  // this can only be tested when true, if it was false the file won't compile
  static_assert( true, "this is just a test" );

  SUCCEED();
}

TEST_F(sitkExceptionsTest, Test3) {

  // This test is designed to improve coverage of the GenericException class

  // Default constructor
  const itk::simple::GenericException empty;
  itk::simple::GenericException e0;

  itk::simple::GenericException e1( __FILE__, __LINE__ );

  itk::simple::GenericException e2( __FILE__, __LINE__, "testing yet another constructor" );

  // copy constructor
  itk::simple::GenericException e3( e2 );

  // asignment
  e0 = e2;
  e0 = e1;
  e0 = empty;

  sitkClangDiagnosticPush();
  sitkClangWarningIgnore("-Wself-assign-overloaded");
  // test self assignment too
  e0 = e0;
  sitkClangDiagnosticPop();

  EXPECT_TRUE( e1 == e1 );
  EXPECT_TRUE( empty == empty );
  EXPECT_FALSE( e2 == e1 );

  EXPECT_NO_THROW( e2.ToString() );
  EXPECT_NO_THROW( e2.GetLocation() );
  EXPECT_NO_THROW( e2.GetDescription() );
  EXPECT_NO_THROW( e2.GetFile() );
  EXPECT_NO_THROW( e2.GetLine() );
  EXPECT_NO_THROW( e2.what() );

  // check accessor for empty/null
  EXPECT_NO_THROW( empty.ToString() );
  EXPECT_NO_THROW( empty.GetLocation() );
  EXPECT_NO_THROW( empty.GetDescription() );
  EXPECT_NO_THROW( empty.GetFile() );
  EXPECT_NO_THROW( empty.GetLine() );
  EXPECT_NO_THROW( empty.what() );

}
<commit_msg>Add `sitkExceptionsTest.TestDestructionAfterAssignment` unit test<commit_after>/*=========================================================================
*
*  Copyright NumFOCUS
*
*  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.txt
*
*  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 "sitkMacro.h"

#include "SimpleITKTestHarness.h"

static const char * DESCRIPTION = "We expect this exception";

class sitkExceptionsTest
  : public ::testing::Test
{
public:

  void ThrowsitkException( )
  {
    sitkExceptionMacro( << DESCRIPTION );
  }
};

TEST_F(sitkExceptionsTest, Test1) {
  ASSERT_THROW( ThrowsitkException(), ::itk::simple::GenericException );

  try
    {
    ThrowsitkException();
    }
  catch ( ::itk::simple::GenericException &e )
    {
    // could do some nifty testing here too
    EXPECT_EQ ( e.GetNameOfClass(), std::string("GenericException") );
    //EXPECT_NE ( std::string ( e.GetLocation() ),  "" ); HACK FIXME
    // exception revision
    return;
    }

  // should gotten that exception
  FAIL();
}

TEST_F(sitkExceptionsTest, Test2) {

  // this can only be tested when true, if it was false the file won't compile
  static_assert( true, "this is just a test" );

  SUCCEED();
}

TEST_F(sitkExceptionsTest, Test3) {

  // This test is designed to improve coverage of the GenericException class

  // Default constructor
  const itk::simple::GenericException empty;
  itk::simple::GenericException e0;

  itk::simple::GenericException e1( __FILE__, __LINE__ );

  itk::simple::GenericException e2( __FILE__, __LINE__, "testing yet another constructor" );

  // copy constructor
  itk::simple::GenericException e3( e2 );

  // asignment
  e0 = e2;
  e0 = e1;
  e0 = empty;

  sitkClangDiagnosticPush();
  sitkClangWarningIgnore("-Wself-assign-overloaded");
  // test self assignment too
  e0 = e0;
  sitkClangDiagnosticPop();

  EXPECT_TRUE( e1 == e1 );
  EXPECT_TRUE( empty == empty );
  EXPECT_FALSE( e2 == e1 );

  EXPECT_NO_THROW( e2.ToString() );
  EXPECT_NO_THROW( e2.GetLocation() );
  EXPECT_NO_THROW( e2.GetDescription() );
  EXPECT_NO_THROW( e2.GetFile() );
  EXPECT_NO_THROW( e2.GetLine() );
  EXPECT_NO_THROW( e2.what() );

  // check accessor for empty/null
  EXPECT_NO_THROW( empty.ToString() );
  EXPECT_NO_THROW( empty.GetLocation() );
  EXPECT_NO_THROW( empty.GetDescription() );
  EXPECT_NO_THROW( empty.GetFile() );
  EXPECT_NO_THROW( empty.GetLine() );
  EXPECT_NO_THROW( empty.what() );

}

TEST_F(sitkExceptionsTest, TestDestructionAfterAssignment) {

    // Test that the program does not crash when two GenericException
    // variables get destructed (automatically, by getting out of scope),
    // when one of them is assigned to the other. (Such a crash might occur
    // with previous versions of SimpleITK, version <= v2.2rc3.)

    const itk::simple::GenericException source(__FILE__, __LINE__);
    itk::simple::GenericException target;

    target = source;

    // After assignment, the variables should compare equal, but moreover,
    // when they get out of scope, their destructors should not crash.
    EXPECT_EQ(target, source);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: LocaleNode.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2004-01-20 13:41:27 $
 *
 *  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 _LOCALE_NODE_
#define _LOCALE_NODE_
#include <com/sun/star/xml/sax/XParser.hpp>
#include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>

#include <vector>

#include <com/sun/star/registry/XImplementationRegistration.hpp>
#include <com/sun/star/lang/XComponent.hpp>

#include <com/sun/star/xml/sax/SAXParseException.hpp>
#include <com/sun/star/xml/sax/XParser.hpp>
#include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>

#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/io/XActiveDataSource.hpp>

#include <cppuhelper/servicefactory.hxx>
#include <cppuhelper/implbase1.hxx>
#include <cppuhelper/implbase3.hxx>

using namespace ::rtl;
using namespace ::std;
using namespace ::com::sun::star::xml::sax;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::io;

class OFileWriter
{
public:

OFileWriter(const char *pcFile, const char *locale );
~OFileWriter();
    virtual void  writeStringCharacters(const ::rtl::OUString& str) const;
    virtual void  writeAsciiString(const char *str)const ;
    virtual void  writeInt(sal_Int16 nb) const;
    virtual void  writeFunction(const char *func, const char *count, const char *array) const;
    virtual void  writeRefFunction(const char *func, const ::rtl::OUString& useLocale) const;
    virtual void  writeFunction(const char *func, const char *count, const char *array, const char *from, const char *to) const;
    virtual void  writeRefFunction(const char *func, const ::rtl::OUString& useLocale, const char *to) const;
    virtual void  writeFunction2(const char *func, const char *style, const char* attr, const char *array) const;
    virtual void  writeRefFunction2(const char *func, const ::rtl::OUString& useLocale) const;
    virtual void  writeFunction3(const char *func, const char *style, const char* levels, const char* attr, const char *array) const;
    virtual void  writeRefFunction3(const char *func, const ::rtl::OUString& useLocale) const;
    virtual void  writeIntParameter(const sal_Char* pAsciiStr, const sal_Int16 count, sal_Int16 val) const;
    virtual void  writeDefaultParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& str, sal_Int16 count) const;
    virtual void  writeDefaultParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& str) const;
    virtual void  writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars) const;
    virtual void  writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count) const;
    virtual void  writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count0, sal_Int16 count1) const;
    virtual void  writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, const sal_Int16 count) const;
    virtual void  writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars) const;
    virtual void  writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count0, sal_Int16 count1) const;
    virtual void  flush(void) const ;
    virtual void  closeOutput(void) const;
private:
    char m_pcFile[1024];
    char theLocale[50];
    FILE *m_f;
};

class Attr {
    Sequence <OUString> name;
    Sequence <OUString> value;

public:
    Attr (const Reference< XAttributeList > & attr);
    OUString getValueByName (const sal_Char *str) const;
    sal_Int32 getLength() const;
    OUString getTypeByIndex (sal_Int32 idx) const;
    OUString getValueByIndex (sal_Int32 idx) const ;
};

class LocaleNode{
    OUString aName;
    Attr * xAttribs;
    OUString aValue;
    LocaleNode * parent;
    LocaleNode* * children;
    void setParent ( LocaleNode*  node);
    sal_Int32 nChildren;
    sal_Int32 childArrSize;
    //inline LocaleNode() { ; }
public:
    LocaleNode (const OUString& name, const Reference< XAttributeList > & attr);
    inline void setValue(const OUString &oValue) { aValue += oValue; };
    inline const OUString getName() { return aName; };
    inline const OUString getValue() { return aValue; };
    inline const Attr* getAttr() { return xAttribs; };
    inline const sal_Int32 getNumberOfChildren () { return nChildren; };
    inline  LocaleNode * getChildAt (sal_Int32 idx) { return children[idx] ; };
    LocaleNode * findNode ( const sal_Char *name);
    void print () ;
    void printR () ;
    ~LocaleNode();
    void addChild (  LocaleNode * node);
    virtual void generateCode (const OFileWriter &of);
    static LocaleNode* createNode (const OUString& name,const Reference< XAttributeList > & attr);
};

class LCInfoNode : public LocaleNode {
public:
    inline LCInfoNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };
    virtual void generateCode (const OFileWriter &of);
};

class LCCTYPENode : public LocaleNode {
public:
    inline LCCTYPENode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of);
};

class LCFormatNode : public LocaleNode {
public:
    inline LCFormatNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of);
};

class LCCollationNode : public LocaleNode {
public:
    inline LCCollationNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of);
};

class LCSearchNode : public LocaleNode {
public:
    inline LCSearchNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of);
};

class LCCalendarNode : public LocaleNode {
public:
    inline LCCalendarNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of);
};

class LCCurrencyNode : public LocaleNode {
public:
    inline LCCurrencyNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of);
};

class LCTransliterationNode : public LocaleNode {
public:
    inline LCTransliterationNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of);
};

class LCMiscNode : public LocaleNode {
public:
    inline LCMiscNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of);
};

class LCNumberingLevelNode : public LocaleNode {
public:
    inline LCNumberingLevelNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of);
};

class LCOutlineNumberingLevelNode : public LocaleNode {
public:
    inline LCOutlineNumberingLevelNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of);
};

#endif
<commit_msg>INTEGRATION: CWS i18n12 (1.5.2); FILE MERGED 2004/04/30 14:30:27 er 1.5.2.2: #i25323# add virtual to dtors 2004/04/09 20:06:27 khong 1.5.2.1: #i25323# put index page information into localedata for each langauges<commit_after>/*************************************************************************
 *
 *  $RCSfile: LocaleNode.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2004-05-28 16:40:10 $
 *
 *  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 _LOCALE_NODE_
#define _LOCALE_NODE_
#include <com/sun/star/xml/sax/XParser.hpp>
#include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>

#include <vector>

#include <com/sun/star/registry/XImplementationRegistration.hpp>
#include <com/sun/star/lang/XComponent.hpp>

#include <com/sun/star/xml/sax/SAXParseException.hpp>
#include <com/sun/star/xml/sax/XParser.hpp>
#include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>

#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/io/XActiveDataSource.hpp>

#include <cppuhelper/servicefactory.hxx>
#include <cppuhelper/implbase1.hxx>
#include <cppuhelper/implbase3.hxx>

using namespace ::rtl;
using namespace ::std;
using namespace ::com::sun::star::xml::sax;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::io;

class OFileWriter
{
public:

OFileWriter(const char *pcFile, const char *locale );
virtual ~OFileWriter();
    virtual void  writeStringCharacters(const ::rtl::OUString& str) const;
    virtual void  writeAsciiString(const char *str)const ;
    virtual void  writeInt(sal_Int16 nb) const;
    virtual void  writeFunction(const char *func, const char *count, const char *array) const;
    virtual void  writeRefFunction(const char *func, const ::rtl::OUString& useLocale) const;
    virtual void  writeFunction(const char *func, const char *count, const char *array, const char *from, const char *to) const;
    virtual void  writeRefFunction(const char *func, const ::rtl::OUString& useLocale, const char *to) const;
    virtual void  writeFunction2(const char *func, const char *style, const char* attr, const char *array) const;
    virtual void  writeRefFunction2(const char *func, const ::rtl::OUString& useLocale) const;
    virtual void  writeFunction3(const char *func, const char *style, const char* levels, const char* attr, const char *array) const;
    virtual void  writeRefFunction3(const char *func, const ::rtl::OUString& useLocale) const;
    virtual void  writeIntParameter(const sal_Char* pAsciiStr, const sal_Int16 count, sal_Int16 val) const;
    virtual void  writeDefaultParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& str, sal_Int16 count) const;
    virtual void  writeDefaultParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& str) const;
    virtual void  writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars) const;
    virtual void  writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count) const;
    virtual void  writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count0, sal_Int16 count1) const;
    virtual void  writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, const sal_Int16 count) const;
    virtual void  writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars) const;
    virtual void  writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count0, sal_Int16 count1) const;
    virtual void  flush(void) const ;
    virtual void  closeOutput(void) const;
private:
    char m_pcFile[1024];
    char theLocale[50];
    FILE *m_f;
};

class Attr {
    Sequence <OUString> name;
    Sequence <OUString> value;

public:
    Attr (const Reference< XAttributeList > & attr);
    OUString getValueByName (const sal_Char *str) const;
    sal_Int32 getLength() const;
    OUString getTypeByIndex (sal_Int32 idx) const;
    OUString getValueByIndex (sal_Int32 idx) const ;
};

class LocaleNode{
    OUString aName;
    Attr * xAttribs;
    OUString aValue;
    LocaleNode * parent;
    LocaleNode* * children;
    void setParent ( LocaleNode*  node);
    sal_Int32 nChildren;
    sal_Int32 childArrSize;
    //inline LocaleNode() { ; }
public:
    LocaleNode (const OUString& name, const Reference< XAttributeList > & attr);
    inline void setValue(const OUString &oValue) { aValue += oValue; };
    inline const OUString getName() { return aName; };
    inline const OUString getValue() { return aValue; };
    inline const Attr* getAttr() { return xAttribs; };
    inline const sal_Int32 getNumberOfChildren () { return nChildren; };
    inline  LocaleNode * getChildAt (sal_Int32 idx) { return children[idx] ; };
    LocaleNode * findNode ( const sal_Char *name);
    void print () ;
    void printR () ;
    virtual ~LocaleNode();
    void addChild (  LocaleNode * node);
    virtual void generateCode (const OFileWriter &of);
    static LocaleNode* createNode (const OUString& name,const Reference< XAttributeList > & attr);
};

class LCInfoNode : public LocaleNode {
public:
    inline LCInfoNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };
    virtual void generateCode (const OFileWriter &of);
};

class LCCTYPENode : public LocaleNode {
public:
    inline LCCTYPENode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of);
};

class LCFormatNode : public LocaleNode {
public:
    inline LCFormatNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of);
};

class LCCollationNode : public LocaleNode {
public:
    inline LCCollationNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of);
};

class LCIndexNode : public LocaleNode {
public:
    inline LCIndexNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of);
};

class LCSearchNode : public LocaleNode {
public:
    inline LCSearchNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of);
};

class LCCalendarNode : public LocaleNode {
public:
    inline LCCalendarNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of);
};

class LCCurrencyNode : public LocaleNode {
public:
    inline LCCurrencyNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of);
};

class LCTransliterationNode : public LocaleNode {
public:
    inline LCTransliterationNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of);
};

class LCMiscNode : public LocaleNode {
public:
    inline LCMiscNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of);
};

class LCNumberingLevelNode : public LocaleNode {
public:
    inline LCNumberingLevelNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of);
};

class LCOutlineNumberingLevelNode : public LocaleNode {
public:
    inline LCOutlineNumberingLevelNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of);
};

#endif
<|endoftext|>


<commit_before>#include "mbed.h"
#include "SDFileSystem.h"
#include "test_env.h"

#if defined(TARGET_KL25Z)
SDFileSystem sd(PTD2, PTD3, PTD1, PTD0, "sd");

#elif defined(TARGET_KL46Z)
SDFileSystem sd(PTD6, PTD7, PTD5, PTD4, "sd");

#elif defined(TARGET_K64F)
SDFileSystem sd(PTD2, PTD3, PTD1, PTD0, "sd");

#elif defined(TARGET_K22F)
SDFileSystem sd(PTD6, PTD7, PTD5, PTD4, "sd");

#elif defined(TARGET_K20D50M)
SDFileSystem sd(PTD2, PTD3, PTD1, PTC2, "sd");

#elif defined(TARGET_nRF51822)
SDFileSystem sd(p12, p13, p15, p14, "sd");

#elif defined(TARGET_NUCLEO_F030R8) || \
      defined(TARGET_NUCLEO_F070RB) || \
      defined(TARGET_NUCLEO_F072RB) || \
      defined(TARGET_NUCLEO_F091RC) || \
      defined(TARGET_NUCLEO_F103RB) || \
      defined(TARGET_NUCLEO_F302R8) || \
      defined(TARGET_NUCLEO_F303RE) || \
      defined(TARGET_NUCLEO_F334R8) || \
      defined(TARGET_NUCLEO_F401RE) || \
      defined(TARGET_NUCLEO_F411RE) || \
      defined(TARGET_NUCLEO_L053R8) || \
      defined(TARGET_NUCLEO_L152RE)
SDFileSystem sd(D11, D12, D13, D10, "sd");

#elif defined(TARGET_DISCO_F051R8)
SDFileSystem sd(SPI_MOSI, SPI_MISO, SPI_SCK, SPI_CS, "sd");

#elif defined(TARGET_LPC2368)
SDFileSystem sd(p11, p12, p13, p14, "sd");

#elif defined(TARGET_LPC11U68)
SDFileSystem sd(D11, D12, D13, D10, "sd");

#elif defined(TARGET_LPC1549)
SDFileSystem sd(D11, D12, D13, D10, "sd");

#elif defined(TARGET_RZ_A1H)
SDFileSystem sd(P8_5, P8_6, P8_3, P8_4, "sd");

#else
SDFileSystem sd(p11, p12, p13, p14, "sd");
#endif

namespace {
const char *sd_file_path = "/sd/out.txt";
const int DATA_SIZE = 256;
}

int main()
{
    uint8_t data_written[DATA_SIZE] = { 0 };
    bool result = true;

    // Fill data_written buffer with random data
    // Write these data into the file
    {
        FILE *f = fopen(sd_file_path, "w");

        printf("SD: Writing ... ");
        for (int i = 0; i < DATA_SIZE; i++) {
            data_written[i] = rand() % 0XFF;
            fprintf(f, "%c", data_written[i]);
        }
        printf("[OK]\r\n");
        fclose(f);
    }

    // Read back the data from the file and store them in data_read
    {
        FILE *f = fopen(sd_file_path, "r");
        printf("SD: Reading data ... ");
        for (int i = 0; i < DATA_SIZE; i++) {
            uint8_t data = fgetc(f);
            if (data != data_written[i]) {
                result = false;
                break;
            }
        }
        printf("[%s]\r\n", result ? "OK" : "FAIL");
        fclose(f);
    }

    notify_completion(result);
}
<commit_msg>Refactored SD card basic test<commit_after>#include "mbed.h"
#include "SDFileSystem.h"
#include "test_env.h"

#if defined(TARGET_KL25Z)
SDFileSystem sd(PTD2, PTD3, PTD1, PTD0, "sd");

#elif defined(TARGET_KL46Z)
SDFileSystem sd(PTD6, PTD7, PTD5, PTD4, "sd");

#elif defined(TARGET_K64F)
SDFileSystem sd(PTD2, PTD3, PTD1, PTD0, "sd");

#elif defined(TARGET_K22F)
SDFileSystem sd(PTD6, PTD7, PTD5, PTD4, "sd");

#elif defined(TARGET_K20D50M)
SDFileSystem sd(PTD2, PTD3, PTD1, PTC2, "sd");

#elif defined(TARGET_nRF51822)
SDFileSystem sd(p12, p13, p15, p14, "sd");

#elif defined(TARGET_NUCLEO_F030R8) || \
      defined(TARGET_NUCLEO_F070RB) || \
      defined(TARGET_NUCLEO_F072RB) || \
      defined(TARGET_NUCLEO_F091RC) || \
      defined(TARGET_NUCLEO_F103RB) || \
      defined(TARGET_NUCLEO_F302R8) || \
      defined(TARGET_NUCLEO_F303RE) || \
      defined(TARGET_NUCLEO_F334R8) || \
      defined(TARGET_NUCLEO_F401RE) || \
      defined(TARGET_NUCLEO_F411RE) || \
      defined(TARGET_NUCLEO_L053R8) || \
      defined(TARGET_NUCLEO_L152RE)
SDFileSystem sd(D11, D12, D13, D10, "sd");

#elif defined(TARGET_DISCO_F051R8)
SDFileSystem sd(SPI_MOSI, SPI_MISO, SPI_SCK, SPI_CS, "sd");

#elif defined(TARGET_LPC2368)
SDFileSystem sd(p11, p12, p13, p14, "sd");

#elif defined(TARGET_LPC11U68)
SDFileSystem sd(D11, D12, D13, D10, "sd");

#elif defined(TARGET_LPC1549)
SDFileSystem sd(D11, D12, D13, D10, "sd");

#elif defined(TARGET_RZ_A1H)
SDFileSystem sd(P8_5, P8_6, P8_3, P8_4, "sd");

#else
SDFileSystem sd(p11, p12, p13, p14, "sd");
#endif

namespace {
const char *sd_file_path = "/sd/out.txt";
const int DATA_SIZE = 256;
}

int main()
{
    uint8_t data_written[DATA_SIZE] = { 0 };
    bool result = false;

    // Fill data_written buffer with random data
    // Write these data into the file
    bool write_result = false;
    {
        printf("SD: Writing ... ");
        FILE *f = fopen(sd_file_path, "w");
        if (f) {
            for (int i = 0; i < DATA_SIZE; i++) {
                data_written[i] = rand() % 0XFF;
                fprintf(f, "%c", data_written[i]);
            }
            write_result = true;
            fclose(f);
        }
        printf("[%s]\r\n", write_result ? "OK" : "FAIL");
    }

    // Read back the data from the file and store them in data_read
    bool read_result = false;
    {
        printf("SD: Reading data ... ");
        FILE *f = fopen(sd_file_path, "r");
        if (f) {
            for (int i = 0; i < DATA_SIZE; i++) {
                uint8_t data = fgetc(f);
                if (data != data_written[i]) {
                    read_result = false;
                    break;
                }
            }
            fclose(f);
        }
        printf("[%s]\r\n", read_result ? "OK" : "FAIL");
    }

    result = write_result && read_result;
    notify_completion(result);
}
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
// Mat::const_row_col_iterator implementation                                //
///////////////////////////////////////////////////////////////////////////////

template<typename eT>
inline
Mat<eT>::const_row_col_iterator::const_row_col_iterator()
    : M(NULL), current_pos(NULL), internal_col(0), internal_row(0)
  {
  // Technically this iterator is invalid (it may not point to a real element)
  }

template<typename eT>
inline
Mat<eT>::const_row_col_iterator::const_row_col_iterator(const row_col_iterator& it)
    : M(it.M), current_pos(it.current_pos), internal_col(it.col()), internal_row(it.row())
  {
  // Nothing to do.
  }

template<typename eT>
inline
Mat<eT>::const_row_col_iterator::const_row_col_iterator(const const_row_iterator& it)
    : M(&it.M), current_pos(&it.M(it.row, it.col)), internal_col(it.col), internal_row(it.row)
  {
  // Nothing to do.
  }

template<typename eT>
inline
Mat<eT>::const_row_col_iterator::const_row_col_iterator(const row_iterator& it)
    : M(&it.M), current_pos(&it.M(it.row, it.col)), internal_col(it.col), internal_row(it.row)
  {
  // Nothing to do.
  }

template<typename eT>
inline
Mat<eT>::const_row_col_iterator::const_row_col_iterator(const Mat<eT>& in_M, const uword row, const uword col)
    : M(&in_M), current_pos(&in_M(row,col)), internal_col(col), internal_row(row)
  {
  // Nothing to do.
  }

template<typename eT>
inline typename Mat<eT>::const_row_col_iterator&
Mat<eT>::const_row_col_iterator::operator++()
  {
  current_pos++;
  internal_row++;

  // Check to see if we moved a column.
  if(internal_row == M->n_rows)
    {
    internal_col++;
    internal_row = 0;
    }

  return *this;
  }

template<typename eT>
inline typename Mat<eT>::const_row_col_iterator
Mat<eT>::const_row_col_iterator::operator++(int)
  {
  typename Mat<eT>::const_row_col_iterator temp(*this);

  ++(*this);

  return temp;
  }

template<typename eT>
inline typename Mat<eT>::const_row_col_iterator&
Mat<eT>::const_row_col_iterator::operator--()
    {
  if(internal_row > 0)
    {
    current_pos--;
    internal_row--;
    }
  else if(internal_col > 0)
    {
    current_pos--;
    internal_col--;
    internal_row = M->n_rows - 1;
    }
  }

template<typename eT>
inline typename Mat<eT>::const_row_col_iterator
Mat<eT>::const_row_col_iterator::operator--(int)
  {
  typename Mat<eT>::const_row_col_iterator temp(*this);

  --(*this);

  return temp;
  }

template<typename eT>
inline bool
Mat<eT>::const_row_col_iterator::operator==(const const_row_col_iterator& rhs) const
  {
  return (rhs.current_pos == current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::const_row_col_iterator::operator!=(const const_row_col_iterator& rhs) const
  {
  return (rhs.current_pos != current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::const_row_col_iterator::operator==(const row_col_iterator& rhs) const
  {
  return (rhs.current_pos == current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::const_row_col_iterator::operator!=(const row_col_iterator& rhs) const
  {
  return (rhs.current_pos != current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::const_row_col_iterator::operator==(const const_iterator& rhs) const
  {
  return (rhs == current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::const_row_col_iterator::operator!=(const const_iterator& rhs) const
  {
  return (rhs != current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::const_row_col_iterator::operator==(const iterator& rhs) const
  {
  return (rhs == current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::const_row_col_iterator::operator!=(const iterator& rhs) const
  {
  return (rhs != current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::const_row_col_iterator::operator==(const const_row_iterator& rhs) const
  {
  return (&rhs.M(rhs.row, rhs.col) == current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::const_row_col_iterator::operator!=(const const_row_iterator& rhs) const
  {
  return (&rhs.M(rhs.row, rhs.col) != current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::const_row_col_iterator::operator==(const row_iterator& rhs) const
  {
  return (&rhs.M(rhs.row, rhs.col) == current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::const_row_col_iterator::operator!=(const row_iterator& rhs) const
  {
  return (&rhs.M(rhs.row, rhs.col) != current_pos);
  }

///////////////////////////////////////////////////////////////////////////////
// Mat::row_col_iterator implementation                                //
///////////////////////////////////////////////////////////////////////////////

template<typename eT>
inline
Mat<eT>::row_col_iterator::row_col_iterator()
    : M(NULL), current_pos(NULL), internal_col(0), internal_row(0)
  {
  // Technically this iterator is invalid (it may not point to a real element)
  }

template<typename eT>
inline
Mat<eT>::row_col_iterator::row_col_iterator(const row_iterator& it)
    : M(&it.M), current_pos(&it.M(it.row, it.col)), internal_col(it.col), internal_row(it.row)
  {
  // Nothing to do.
  }

template<typename eT>
inline
Mat<eT>::row_col_iterator::row_col_iterator(Mat<eT>& in_M, const uword row, const uword col)
    : M(&in_M), current_pos(&in_M(row,col)), internal_col(col), internal_row(row)
  {
  // Nothing to do.
  }

template<typename eT>
inline typename Mat<eT>::row_col_iterator&
Mat<eT>::row_col_iterator::operator++()
  {
  current_pos++;
  internal_row++;

  // Check to see if we moved a column.
  if(internal_row == M->n_rows)
    {
    internal_col++;
    internal_row = 0;
    }

  return *this;
  }

template<typename eT>
inline typename Mat<eT>::row_col_iterator
Mat<eT>::row_col_iterator::operator++(int)
  {
  typename Mat<eT>::row_col_iterator temp(*this);

  ++(*this);

  return temp;
  }

template<typename eT>
inline typename Mat<eT>::row_col_iterator&
Mat<eT>::row_col_iterator::operator--()
    {
  if(internal_row != 0)
    {
    current_pos--;
    internal_row--;
    }
  else if(internal_col != 0)
    {
    current_pos--;
    internal_col--;
    internal_row = M->n_rows - 1;
    }
  }

template<typename eT>
inline typename Mat<eT>::row_col_iterator
Mat<eT>::row_col_iterator::operator--(int)
  {
  typename Mat<eT>::row_col_iterator temp(*this);

  --(*this);

  return temp;
  }

template<typename eT>
inline bool
Mat<eT>::row_col_iterator::operator==(const const_row_col_iterator& rhs) const
  {
  return (rhs.current_pos == current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::row_col_iterator::operator!=(const const_row_col_iterator& rhs) const
  {
  return (rhs.current_pos != current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::row_col_iterator::operator==(const row_col_iterator& rhs) const
  {
  return (rhs.current_pos == current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::row_col_iterator::operator!=(const row_col_iterator& rhs) const
  {
  return (rhs.current_pos != current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::row_col_iterator::operator==(const const_iterator& rhs) const
  {
  return (rhs == current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::row_col_iterator::operator!=(const const_iterator& rhs) const
  {
  return (rhs != current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::row_col_iterator::operator==(const iterator& rhs) const
  {
  return (rhs == current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::row_col_iterator::operator!=(const iterator& rhs) const
  {
  return (rhs != current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::row_col_iterator::operator==(const const_row_iterator& rhs) const
  {
  return (&rhs.M(rhs.row, rhs.col) == current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::row_col_iterator::operator!=(const const_row_iterator& rhs) const
  {
  return (&rhs.M(rhs.row, rhs.col) != current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::row_col_iterator::operator==(const row_iterator& rhs) const
  {
  return (&rhs.M(rhs.row, rhs.col) == current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::row_col_iterator::operator!=(const row_iterator& rhs) const
  {
  return (&rhs.M(rhs.row, rhs.col) != current_pos);
  }

///////////////////////////////////////////////////////////////////////////////
// extended Mat functionality implementation                                 //
///////////////////////////////////////////////////////////////////////////////

template<typename eT>
inline typename Mat<eT>::const_row_col_iterator
Mat<eT>::begin_row_col() const
  {
  return const_row_col_iterator(*this);
  }

template<typename eT>
inline typename Mat<eT>::row_col_iterator
Mat<eT>::begin_row_col()
  {
  return row_col_iterator(*this);
  }

template<typename eT>
inline typename Mat<eT>::const_row_col_iterator
Mat<eT>::end_row_col() const
  {
  return ++const_row_col_iterator(*this, n_rows - 1, n_cols - 1);
  }

template<typename eT>
inline typename Mat<eT>::row_col_iterator
Mat<eT>::end_row_col()
  {
  return ++row_col_iterator(*this, n_rows - 1, n_cols - 1);
  }
<commit_msg>Return *this for operator--().<commit_after>///////////////////////////////////////////////////////////////////////////////
// Mat::const_row_col_iterator implementation                                //
///////////////////////////////////////////////////////////////////////////////

template<typename eT>
inline
Mat<eT>::const_row_col_iterator::const_row_col_iterator()
    : M(NULL), current_pos(NULL), internal_col(0), internal_row(0)
  {
  // Technically this iterator is invalid (it may not point to a real element)
  }

template<typename eT>
inline
Mat<eT>::const_row_col_iterator::const_row_col_iterator(const row_col_iterator& it)
    : M(it.M), current_pos(it.current_pos), internal_col(it.col()), internal_row(it.row())
  {
  // Nothing to do.
  }

template<typename eT>
inline
Mat<eT>::const_row_col_iterator::const_row_col_iterator(const const_row_iterator& it)
    : M(&it.M), current_pos(&it.M(it.row, it.col)), internal_col(it.col), internal_row(it.row)
  {
  // Nothing to do.
  }

template<typename eT>
inline
Mat<eT>::const_row_col_iterator::const_row_col_iterator(const row_iterator& it)
    : M(&it.M), current_pos(&it.M(it.row, it.col)), internal_col(it.col), internal_row(it.row)
  {
  // Nothing to do.
  }

template<typename eT>
inline
Mat<eT>::const_row_col_iterator::const_row_col_iterator(const Mat<eT>& in_M, const uword row, const uword col)
    : M(&in_M), current_pos(&in_M(row,col)), internal_col(col), internal_row(row)
  {
  // Nothing to do.
  }

template<typename eT>
inline typename Mat<eT>::const_row_col_iterator&
Mat<eT>::const_row_col_iterator::operator++()
  {
  current_pos++;
  internal_row++;

  // Check to see if we moved a column.
  if(internal_row == M->n_rows)
    {
    internal_col++;
    internal_row = 0;
    }

  return *this;
  }

template<typename eT>
inline typename Mat<eT>::const_row_col_iterator
Mat<eT>::const_row_col_iterator::operator++(int)
  {
  typename Mat<eT>::const_row_col_iterator temp(*this);

  ++(*this);

  return temp;
  }

template<typename eT>
inline typename Mat<eT>::const_row_col_iterator&
Mat<eT>::const_row_col_iterator::operator--()
    {
  if(internal_row > 0)
    {
    current_pos--;
    internal_row--;
    }
  else if(internal_col > 0)
    {
    current_pos--;
    internal_col--;
    internal_row = M->n_rows - 1;
    }

  return *this;
  }

template<typename eT>
inline typename Mat<eT>::const_row_col_iterator
Mat<eT>::const_row_col_iterator::operator--(int)
  {
  typename Mat<eT>::const_row_col_iterator temp(*this);

  --(*this);

  return temp;
  }

template<typename eT>
inline bool
Mat<eT>::const_row_col_iterator::operator==(const const_row_col_iterator& rhs) const
  {
  return (rhs.current_pos == current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::const_row_col_iterator::operator!=(const const_row_col_iterator& rhs) const
  {
  return (rhs.current_pos != current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::const_row_col_iterator::operator==(const row_col_iterator& rhs) const
  {
  return (rhs.current_pos == current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::const_row_col_iterator::operator!=(const row_col_iterator& rhs) const
  {
  return (rhs.current_pos != current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::const_row_col_iterator::operator==(const const_iterator& rhs) const
  {
  return (rhs == current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::const_row_col_iterator::operator!=(const const_iterator& rhs) const
  {
  return (rhs != current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::const_row_col_iterator::operator==(const iterator& rhs) const
  {
  return (rhs == current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::const_row_col_iterator::operator!=(const iterator& rhs) const
  {
  return (rhs != current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::const_row_col_iterator::operator==(const const_row_iterator& rhs) const
  {
  return (&rhs.M(rhs.row, rhs.col) == current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::const_row_col_iterator::operator!=(const const_row_iterator& rhs) const
  {
  return (&rhs.M(rhs.row, rhs.col) != current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::const_row_col_iterator::operator==(const row_iterator& rhs) const
  {
  return (&rhs.M(rhs.row, rhs.col) == current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::const_row_col_iterator::operator!=(const row_iterator& rhs) const
  {
  return (&rhs.M(rhs.row, rhs.col) != current_pos);
  }

///////////////////////////////////////////////////////////////////////////////
// Mat::row_col_iterator implementation                                //
///////////////////////////////////////////////////////////////////////////////

template<typename eT>
inline
Mat<eT>::row_col_iterator::row_col_iterator()
    : M(NULL), current_pos(NULL), internal_col(0), internal_row(0)
  {
  // Technically this iterator is invalid (it may not point to a real element)
  }

template<typename eT>
inline
Mat<eT>::row_col_iterator::row_col_iterator(const row_iterator& it)
    : M(&it.M), current_pos(&it.M(it.row, it.col)), internal_col(it.col), internal_row(it.row)
  {
  // Nothing to do.
  }

template<typename eT>
inline
Mat<eT>::row_col_iterator::row_col_iterator(Mat<eT>& in_M, const uword row, const uword col)
    : M(&in_M), current_pos(&in_M(row,col)), internal_col(col), internal_row(row)
  {
  // Nothing to do.
  }

template<typename eT>
inline typename Mat<eT>::row_col_iterator&
Mat<eT>::row_col_iterator::operator++()
  {
  current_pos++;
  internal_row++;

  // Check to see if we moved a column.
  if(internal_row == M->n_rows)
    {
    internal_col++;
    internal_row = 0;
    }

  return *this;
  }

template<typename eT>
inline typename Mat<eT>::row_col_iterator
Mat<eT>::row_col_iterator::operator++(int)
  {
  typename Mat<eT>::row_col_iterator temp(*this);

  ++(*this);

  return temp;
  }

template<typename eT>
inline typename Mat<eT>::row_col_iterator&
Mat<eT>::row_col_iterator::operator--()
    {
  if(internal_row != 0)
    {
    current_pos--;
    internal_row--;
    }
  else if(internal_col != 0)
    {
    current_pos--;
    internal_col--;
    internal_row = M->n_rows - 1;
    }

  return *this;
  }

template<typename eT>
inline typename Mat<eT>::row_col_iterator
Mat<eT>::row_col_iterator::operator--(int)
  {
  typename Mat<eT>::row_col_iterator temp(*this);

  --(*this);

  return temp;
  }

template<typename eT>
inline bool
Mat<eT>::row_col_iterator::operator==(const const_row_col_iterator& rhs) const
  {
  return (rhs.current_pos == current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::row_col_iterator::operator!=(const const_row_col_iterator& rhs) const
  {
  return (rhs.current_pos != current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::row_col_iterator::operator==(const row_col_iterator& rhs) const
  {
  return (rhs.current_pos == current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::row_col_iterator::operator!=(const row_col_iterator& rhs) const
  {
  return (rhs.current_pos != current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::row_col_iterator::operator==(const const_iterator& rhs) const
  {
  return (rhs == current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::row_col_iterator::operator!=(const const_iterator& rhs) const
  {
  return (rhs != current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::row_col_iterator::operator==(const iterator& rhs) const
  {
  return (rhs == current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::row_col_iterator::operator!=(const iterator& rhs) const
  {
  return (rhs != current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::row_col_iterator::operator==(const const_row_iterator& rhs) const
  {
  return (&rhs.M(rhs.row, rhs.col) == current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::row_col_iterator::operator!=(const const_row_iterator& rhs) const
  {
  return (&rhs.M(rhs.row, rhs.col) != current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::row_col_iterator::operator==(const row_iterator& rhs) const
  {
  return (&rhs.M(rhs.row, rhs.col) == current_pos);
  }

template<typename eT>
inline bool
Mat<eT>::row_col_iterator::operator!=(const row_iterator& rhs) const
  {
  return (&rhs.M(rhs.row, rhs.col) != current_pos);
  }

///////////////////////////////////////////////////////////////////////////////
// extended Mat functionality implementation                                 //
///////////////////////////////////////////////////////////////////////////////

template<typename eT>
inline typename Mat<eT>::const_row_col_iterator
Mat<eT>::begin_row_col() const
  {
  return const_row_col_iterator(*this);
  }

template<typename eT>
inline typename Mat<eT>::row_col_iterator
Mat<eT>::begin_row_col()
  {
  return row_col_iterator(*this);
  }

template<typename eT>
inline typename Mat<eT>::const_row_col_iterator
Mat<eT>::end_row_col() const
  {
  return ++const_row_col_iterator(*this, n_rows - 1, n_cols - 1);
  }

template<typename eT>
inline typename Mat<eT>::row_col_iterator
Mat<eT>::end_row_col()
  {
  return ++row_col_iterator(*this, n_rows - 1, n_cols - 1);
  }
<|endoftext|>