<commit_before>//
//  SerializeSourcemap.cc
//  drafter
//
//  Created by Pavan Kumar Sunkara on 18/01/15.
//  Copyright (c) 2015 Apiary Inc. All rights reserved.
//

#include "SerializeSourcemap.h"

using namespace drafter;

using snowcrash::SourceMapBase;
using snowcrash::SourceMap;
using snowcrash::Collection;

using snowcrash::DataStructure;
using snowcrash::Asset;
using snowcrash::Payload;
using snowcrash::Header;
using snowcrash::Parameters;
using snowcrash::Parameter;
using snowcrash::Value;
using snowcrash::TransactionExample;
using snowcrash::Request;
using snowcrash::Response;
using snowcrash::Action;
using snowcrash::Resource;
using snowcrash::Element;
using snowcrash::Description;
using snowcrash::Blueprint;
using snowcrash::Metadata;

sos::Array WrapSourcemap(const SourceMapBase& value)
{
    sos::Array sourceMap;

    for (mdp::RangeSet<mdp::BytesRange>::const_iterator it = value.sourceMap.begin();
         it != value.sourceMap.end();
         ++it) {

        sos::Array sourceMapRow;

        sourceMapRow.push(sos::Number(it->location));
        sourceMapRow.push(sos::Number(it->length));

        sourceMap.push(sourceMapRow);
    }

    return sourceMap;
}

// Forward declarations
sos::Array WrapTypeSectionsSourcemap(const SourceMap<mson::TypeSections>& typeSections);
sos::Array WrapElementsSourcemap(const SourceMap<mson::Elements>& elements);

sos::Object WrapPropertyMemberSourcemap(const SourceMap<mson::PropertyMember>& propertyMember)
{
    sos::Object propertyMemberObject;

    // Name
    propertyMemberObject.set(SerializeKey::Name, WrapSourcemap(propertyMember.name));

    // Description
    propertyMemberObject.set(SerializeKey::Description, WrapSourcemap(propertyMember.description));

    // Value Definition
    propertyMemberObject.set(SerializeKey::ValueDefinition, WrapSourcemap(propertyMember.valueDefinition));

    // Type Sections
    propertyMemberObject.set(SerializeKey::Sections, WrapTypeSectionsSourcemap(propertyMember.sections));

    return propertyMemberObject;
}

sos::Object WrapValueMemberSourcemap(const SourceMap<mson::ValueMember>& valueMember)
{
    sos::Object valueMemberObject;

    // Description
    valueMemberObject.set(SerializeKey::Description, WrapSourcemap(valueMember.description));

    // Value Definition
    valueMemberObject.set(SerializeKey::ValueDefinition, WrapSourcemap(valueMember.valueDefinition));

    // Type Sections
    valueMemberObject.set(SerializeKey::Sections, WrapTypeSectionsSourcemap(valueMember.sections));

    return valueMemberObject;
}

sos::Array WrapMixinSourcemap(const SourceMap<mson::Mixin>& mixin)
{
    return WrapSourcemap(mixin);
}

sos::Base WrapElementSourcemapBase(const SourceMap<mson::Element>& element)
{
    if (!element.elements().collection.empty()) {
        // Same for oneOf
        return WrapElementsSourcemap(element.elements());     // return sos::Array
    }
    else if (!element.mixin.sourceMap.empty()) {
        return WrapMixinSourcemap(element.mixin);             // return sos::Array
    }
    else if (!element.value.empty()) {
        return WrapValueMemberSourcemap(element.value);       // return sos::Object
    }
    else if (!element.property.empty()) {
        return WrapPropertyMemberSourcemap(element.property); // return sos::Object
    }

    return sos::Null();                                       // return sos::Null
}

sos::Array WrapElementsSourcemap(const SourceMap<mson::Elements>& elements)
{
    return WrapCollection<mson::Element>()(elements.collection, WrapElementSourcemapBase);
}

sos::Array WrapTypeSectionsSourcemap(const SourceMap<mson::TypeSections>& sections)
{
    sos::Array sectionsArray;

    for (Collection<SourceMap<mson::TypeSection> >::const_iterator it = sections.collection.begin();
         it != sections.collection.end();
         ++it) {

        if (!it->description.sourceMap.empty()) {
            sectionsArray.push(WrapSourcemap(it->description));
        }
        else if (!it->value.sourceMap.empty()) {
            sectionsArray.push(WrapSourcemap(it->value));
        }
        else if (!it->elements().collection.empty()) {
            sectionsArray.push(WrapElementsSourcemap(it->elements()));
        }
    }

    return sectionsArray;
}

sos::Object WrapNamedTypeSourcemap(const SourceMap<mson::NamedType>& namedType)
{
    sos::Object namedTypeObject;

    // Name
    namedTypeObject.set(SerializeKey::Name, WrapSourcemap(namedType.name));

    // Type Definition
    namedTypeObject.set(SerializeKey::TypeDefinition, WrapSourcemap(namedType.typeDefinition));

    // Type Sections
    namedTypeObject.set(SerializeKey::Sections, WrapTypeSectionsSourcemap(namedType.sections));

    return namedTypeObject;
}

sos::Object WrapDataStructureSourcemap(const SourceMap<DataStructure>& dataStructure)
{
    sos::Object dataStructureObject;

    // Name
    dataStructureObject.set(SerializeKey::Name, WrapSourcemap(dataStructure.name));

    // Type Definition
    dataStructureObject.set(SerializeKey::TypeDefinition, WrapSourcemap(dataStructure.typeDefinition));

    // Type Sections
    dataStructureObject.set(SerializeKey::Sections, WrapTypeSectionsSourcemap(dataStructure.sections));

    return dataStructureObject;
}

sos::Object WrapAssetSourcemap(const SourceMap<Asset>& asset)
{
    sos::Object assetObject;

    // Content
    assetObject.set(SerializeKey::Content, WrapSourcemap(asset));

    return assetObject;
}

sos::Object WrapPayloadSourcemap(const SourceMap<Payload>& payload)
{
    sos::Object payloadObject;

    // Reference
    if (!payload.reference.sourceMap.empty()) {
        payloadObject.set(SerializeKey::Reference, WrapSourcemap(payload.reference));
    }

    // Name
    payloadObject.set(SerializeKey::Name, WrapSourcemap(payload.name));

    // Description
    payloadObject.set(SerializeKey::Description, WrapSourcemap(payload.description));

    // Headers
    payloadObject.set(SerializeKey::Headers,
                      WrapCollection<Header>()(payload.headers.collection, WrapSourcemap));

    // Body
    payloadObject.set(SerializeKey::Body, WrapSourcemap(payload.body));

    // Schema
    payloadObject.set(SerializeKey::Schema, WrapSourcemap(payload.schema));

    // Content
    sos::Array content;

    /// Attributes
    if (!payload.attributes.empty()) {
        content.push(WrapDataStructureSourcemap(payload.attributes));
    }

    /// Asset 'bodyExample'
    if (!payload.body.sourceMap.empty()) {
        content.push(WrapAssetSourcemap(payload.body));
    }

    /// Asset 'bodySchema'
    if (!payload.schema.sourceMap.empty()) {
        content.push(WrapAssetSourcemap(payload.schema));
    }

    payloadObject.set(SerializeKey::Content, content);

    return payloadObject;
}

sos::Array WrapParametersSourcemap(const SourceMap<Parameters>& parameters)
{
    sos::Array parametersArray;

    for (Collection<SourceMap<Parameter> >::const_iterator it = parameters.collection.begin();
         it != parameters.collection.end();
         ++it) {

        sos::Object parameter;

        // Name
        parameter.set(SerializeKey::Name, WrapSourcemap(it->name));

        // Description
        parameter.set(SerializeKey::Description, WrapSourcemap(it->description));

        // Type
        parameter.set(SerializeKey::Type, WrapSourcemap(it->type));

        // Use
        parameter.set(SerializeKey::Required, WrapSourcemap(it->use));

        // Example Value
        parameter.set(SerializeKey::Example, WrapSourcemap(it->exampleValue));

        // Default Value
        parameter.set(SerializeKey::Default, WrapSourcemap(it->defaultValue));

        // Values
        sos::Array values;

        for (Collection<SourceMap<Value> >::const_iterator valIt = it->values.collection.begin();
             valIt != it->values.collection.end();
             ++valIt) {

            sos::Object value;

            value.set(SerializeKey::Value, WrapSourcemap(*valIt));

            values.push(value);
        }

        parameter.set(SerializeKey::Values, values);
    }

    return parametersArray;
}

sos::Object WrapTransactionExampleSourcemap(const SourceMap<TransactionExample>& example)
{
    sos::Object exampleObject;

    // Name
    exampleObject.set(SerializeKey::Name, WrapSourcemap(example.name));

    // Description
    exampleObject.set(SerializeKey::Description, WrapSourcemap(example.description));

    // Requests
    exampleObject.set(SerializeKey::Requests,
                      WrapCollection<Request>()(example.requests.collection, WrapPayloadSourcemap));

    // Responses
    exampleObject.set(SerializeKey::Responses,
                      WrapCollection<Response>()(example.responses.collection, WrapPayloadSourcemap));

    return exampleObject;
}

sos::Object WrapActionSourcemap(const SourceMap<Action>& action)
{
    sos::Object actionObject;

    // Name
    actionObject.set(SerializeKey::Name, WrapSourcemap(action.name));

    // Description
    actionObject.set(SerializeKey::Description, WrapSourcemap(action.description));

    // HTTP Method
    actionObject.set(SerializeKey::Method, WrapSourcemap(action.method));

    // Parameters
    actionObject.set(SerializeKey::Parameters, WrapParametersSourcemap(action.parameters));

    // Transaction Examples
    actionObject.set(SerializeKey::Examples,
                     WrapCollection<TransactionExample>()(action.examples.collection, WrapTransactionExampleSourcemap));

    // Content
    sos::Array content;

    /// Attributes
    if (!action.attributes.empty()) {
        content.push(WrapDataStructureSourcemap(action.attributes));
    }

    actionObject.set(SerializeKey::Content, content);

    return actionObject;
}

sos::Object WrapResourceSourcemap(const SourceMap<Resource>& resource)
{
    sos::Object resourceObject;

    // Name
    resourceObject.set(SerializeKey::Name, WrapSourcemap(resource.name));

    // Description
    resourceObject.set(SerializeKey::Description, WrapSourcemap(resource.description));

    // URI Template
    resourceObject.set(SerializeKey::URITemplate, WrapSourcemap(resource.uriTemplate));

    // Model
    sos::Object model = (resource.model.name.sourceMap.empty() ? sos::Object() : WrapPayloadSourcemap(resource.model));
    resourceObject.set(SerializeKey::Model, model);

    // Parameters
    resourceObject.set(SerializeKey::Parameters, WrapParametersSourcemap(resource.parameters));

    // Actions
    resourceObject.set(SerializeKey::Actions,
                       WrapCollection<Action>()(resource.actions.collection, WrapActionSourcemap));

    // Content
    sos::Array content;

    /// Attributes
    if (!resource.attributes.empty()) {
        content.push(WrapDataStructureSourcemap(resource.attributes));
    }

    resourceObject.set(SerializeKey::Content, content);

    return resourceObject;
}

sos::Object WrapResourceGroupSourcemap(const SourceMap<Element>& resourceGroup)
{
    sos::Object resourceGroupObject;

    // Name
    resourceGroupObject.set(SerializeKey::Name, WrapSourcemap(resourceGroup.attributes.name));

    // Description & Resources
    SourceMap<Description> description;
    sos::Array resources;

    for (Collection<SourceMap<Element> >::const_iterator it = resourceGroup.content.elements().collection.begin();
         it != resourceGroup.content.elements().collection.end();
         ++it) {

        if (it->element == Element::ResourceElement) {
            resources.push(WrapResourceSourcemap(it->content.resource));
        }
        else if (it->element == Element::CopyElement) {
            description.sourceMap.append(it->content.copy.sourceMap);
        }
    }

    resourceGroupObject.set(SerializeKey::Description, WrapSourcemap(description));
    resourceGroupObject.set(SerializeKey::Resources, resources);

    return resourceGroupObject;
}

sos::Object WrapDataStructureContent(const SourceMap<DataStructure>& dataStructure)
{
    sos::Object dataStructureObject;

    // Source
    dataStructureObject.set(SerializeKey::Source, WrapNamedTypeSourcemap(dataStructure));

    return dataStructureObject;
}

sos::Object WrapElementSourcemap(const SourceMap<Element>& element)
{
    sos::Object elementObject;

    if (!element.attributes.name.sourceMap.empty()) {

        sos::Object attributes;

        attributes.set(SerializeKey::Name, WrapSourcemap(element.attributes.name));
        elementObject.set(SerializeKey::Attributes, attributes);
    }

    switch (element.element) {
        case Element::CopyElement:
        {
            elementObject.set(SerializeKey::Content, WrapSourcemap(element.content.copy));
            break;
        }

        case Element::DataStructureElement:
        {
            return WrapDataStructureSourcemap(element.content.dataStructure);
        }

        case Element::ResourceElement:
        {
            return WrapResourceSourcemap(element.content.resource);
        }

        case Element::CategoryElement:
        {
            elementObject.set(SerializeKey::Content,
                              WrapCollection<Element>()(element.content.elements().collection, WrapElementSourcemap));
            break;
        }

        default:
            break;
    }

    return elementObject;
}

sos::Object drafter::WrapBlueprintSourcemap(const SourceMap<Blueprint>& blueprint)
{
    sos::Object blueprintObject;

    // Metadata
    blueprintObject.set(SerializeKey::Metadata,
                        WrapCollection<Metadata>()(blueprint.metadata.collection, WrapSourcemap));

    // Name
    blueprintObject.set(SerializeKey::Name, WrapSourcemap(blueprint.name));

    // Description
    blueprintObject.set(SerializeKey::Description, WrapSourcemap(blueprint.description));

    // Resource Groups
    sos::Array resourceGroups;

    for (Collection<SourceMap<Element> >::const_iterator it = blueprint.content.elements().collection.begin();
         it != blueprint.content.elements().collection.end();
         ++it) {

        if (it->element == Element::CategoryElement &&
            it->category == Element::ResourceGroupCategory) {

            resourceGroups.push(WrapResourceGroupSourcemap(*it));
        }
    }

    blueprintObject.set(SerializeKey::ResourceGroups, resourceGroups);

    // Content
    blueprintObject.set(SerializeKey::Content,
                        WrapCollection<Element>()(blueprint.content.elements().collection, WrapElementSourcemap));
    return blueprintObject;
}
<commit_msg>* refactoring WrapTypeSectionsSourcemap<commit_after>//
//  SerializeSourcemap.cc
//  drafter
//
//  Created by Pavan Kumar Sunkara on 18/01/15.
//  Copyright (c) 2015 Apiary Inc. All rights reserved.
//

#include "SerializeSourcemap.h"

using namespace drafter;

using snowcrash::SourceMapBase;
using snowcrash::SourceMap;
using snowcrash::Collection;

using snowcrash::DataStructure;
using snowcrash::Asset;
using snowcrash::Payload;
using snowcrash::Header;
using snowcrash::Parameters;
using snowcrash::Parameter;
using snowcrash::Value;
using snowcrash::TransactionExample;
using snowcrash::Request;
using snowcrash::Response;
using snowcrash::Action;
using snowcrash::Resource;
using snowcrash::Element;
using snowcrash::Description;
using snowcrash::Blueprint;
using snowcrash::Metadata;

sos::Array WrapSourcemap(const SourceMapBase& value)
{
    sos::Array sourceMap;

    for (mdp::RangeSet<mdp::BytesRange>::const_iterator it = value.sourceMap.begin();
         it != value.sourceMap.end();
         ++it) {

        sos::Array sourceMapRow;

        sourceMapRow.push(sos::Number(it->location));
        sourceMapRow.push(sos::Number(it->length));

        sourceMap.push(sourceMapRow);
    }

    return sourceMap;
}

// Forward declarations
sos::Array WrapTypeSectionsSourcemap(const SourceMap<mson::TypeSections>& typeSections);
sos::Array WrapElementsSourcemap(const SourceMap<mson::Elements>& elements);

sos::Object WrapPropertyMemberSourcemap(const SourceMap<mson::PropertyMember>& propertyMember)
{
    sos::Object propertyMemberObject;

    // Name
    propertyMemberObject.set(SerializeKey::Name, WrapSourcemap(propertyMember.name));

    // Description
    propertyMemberObject.set(SerializeKey::Description, WrapSourcemap(propertyMember.description));

    // Value Definition
    propertyMemberObject.set(SerializeKey::ValueDefinition, WrapSourcemap(propertyMember.valueDefinition));

    // Type Sections
    propertyMemberObject.set(SerializeKey::Sections, WrapTypeSectionsSourcemap(propertyMember.sections));

    return propertyMemberObject;
}

sos::Object WrapValueMemberSourcemap(const SourceMap<mson::ValueMember>& valueMember)
{
    sos::Object valueMemberObject;

    // Description
    valueMemberObject.set(SerializeKey::Description, WrapSourcemap(valueMember.description));

    // Value Definition
    valueMemberObject.set(SerializeKey::ValueDefinition, WrapSourcemap(valueMember.valueDefinition));

    // Type Sections
    valueMemberObject.set(SerializeKey::Sections, WrapTypeSectionsSourcemap(valueMember.sections));

    return valueMemberObject;
}

sos::Array WrapMixinSourcemap(const SourceMap<mson::Mixin>& mixin)
{
    return WrapSourcemap(mixin);
}

sos::Base WrapElementSourcemapBase(const SourceMap<mson::Element>& element)
{
    if (!element.elements().collection.empty()) {
        // Same for oneOf
        return WrapElementsSourcemap(element.elements());     // return sos::Array
    }
    else if (!element.mixin.sourceMap.empty()) {
        return WrapMixinSourcemap(element.mixin);             // return sos::Array
    }
    else if (!element.value.empty()) {
        return WrapValueMemberSourcemap(element.value);       // return sos::Object
    }
    else if (!element.property.empty()) {
        return WrapPropertyMemberSourcemap(element.property); // return sos::Object
    }

    return sos::Null();                                       // return sos::Null
}

sos::Array WrapElementsSourcemap(const SourceMap<mson::Elements>& elements)
{
    return WrapCollection<mson::Element>()(elements.collection, WrapElementSourcemapBase);
}

sos::Array WrapTypeSectionSourcemap(const SourceMap<mson::TypeSection>& section)
{
    if (!section.description.sourceMap.empty()) {
        return WrapSourcemap(section.description);
    }
    else if (!section.value.sourceMap.empty()) {
        return WrapSourcemap(section.value);
    }
    else if (!section.elements().collection.empty()) {
        return WrapElementsSourcemap(section.elements());
    }
}

sos::Array WrapTypeSectionsSourcemap(const SourceMap<mson::TypeSections>& sections)
{
    return WrapCollection<mson::TypeSection>()(sections.collection, WrapTypeSectionSourcemap);
}

sos::Object WrapNamedTypeSourcemap(const SourceMap<mson::NamedType>& namedType)
{
    sos::Object namedTypeObject;

    // Name
    namedTypeObject.set(SerializeKey::Name, WrapSourcemap(namedType.name));

    // Type Definition
    namedTypeObject.set(SerializeKey::TypeDefinition, WrapSourcemap(namedType.typeDefinition));

    // Type Sections
    namedTypeObject.set(SerializeKey::Sections, WrapTypeSectionsSourcemap(namedType.sections));

    return namedTypeObject;
}

sos::Object WrapDataStructureSourcemap(const SourceMap<DataStructure>& dataStructure)
{
    sos::Object dataStructureObject;

    // Name
    dataStructureObject.set(SerializeKey::Name, WrapSourcemap(dataStructure.name));

    // Type Definition
    dataStructureObject.set(SerializeKey::TypeDefinition, WrapSourcemap(dataStructure.typeDefinition));

    // Type Sections
    dataStructureObject.set(SerializeKey::Sections, WrapTypeSectionsSourcemap(dataStructure.sections));

    return dataStructureObject;
}

sos::Object WrapAssetSourcemap(const SourceMap<Asset>& asset)
{
    sos::Object assetObject;

    // Content
    assetObject.set(SerializeKey::Content, WrapSourcemap(asset));

    return assetObject;
}

sos::Object WrapPayloadSourcemap(const SourceMap<Payload>& payload)
{
    sos::Object payloadObject;

    // Reference
    if (!payload.reference.sourceMap.empty()) {
        payloadObject.set(SerializeKey::Reference, WrapSourcemap(payload.reference));
    }

    // Name
    payloadObject.set(SerializeKey::Name, WrapSourcemap(payload.name));

    // Description
    payloadObject.set(SerializeKey::Description, WrapSourcemap(payload.description));

    // Headers
    payloadObject.set(SerializeKey::Headers,
                      WrapCollection<Header>()(payload.headers.collection, WrapSourcemap));

    // Body
    payloadObject.set(SerializeKey::Body, WrapSourcemap(payload.body));

    // Schema
    payloadObject.set(SerializeKey::Schema, WrapSourcemap(payload.schema));

    // Content
    sos::Array content;

    /// Attributes
    if (!payload.attributes.empty()) {
        content.push(WrapDataStructureSourcemap(payload.attributes));
    }

    /// Asset 'bodyExample'
    if (!payload.body.sourceMap.empty()) {
        content.push(WrapAssetSourcemap(payload.body));
    }

    /// Asset 'bodySchema'
    if (!payload.schema.sourceMap.empty()) {
        content.push(WrapAssetSourcemap(payload.schema));
    }

    payloadObject.set(SerializeKey::Content, content);

    return payloadObject;
}

sos::Array WrapParametersSourcemap(const SourceMap<Parameters>& parameters)
{
    sos::Array parametersArray;

    for (Collection<SourceMap<Parameter> >::const_iterator it = parameters.collection.begin();
         it != parameters.collection.end();
         ++it) {

        sos::Object parameter;

        // Name
        parameter.set(SerializeKey::Name, WrapSourcemap(it->name));

        // Description
        parameter.set(SerializeKey::Description, WrapSourcemap(it->description));

        // Type
        parameter.set(SerializeKey::Type, WrapSourcemap(it->type));

        // Use
        parameter.set(SerializeKey::Required, WrapSourcemap(it->use));

        // Example Value
        parameter.set(SerializeKey::Example, WrapSourcemap(it->exampleValue));

        // Default Value
        parameter.set(SerializeKey::Default, WrapSourcemap(it->defaultValue));

        // Values
        sos::Array values;

        for (Collection<SourceMap<Value> >::const_iterator valIt = it->values.collection.begin();
             valIt != it->values.collection.end();
             ++valIt) {

            sos::Object value;

            value.set(SerializeKey::Value, WrapSourcemap(*valIt));

            values.push(value);
        }

        parameter.set(SerializeKey::Values, values);
    }

    return parametersArray;
}

sos::Object WrapTransactionExampleSourcemap(const SourceMap<TransactionExample>& example)
{
    sos::Object exampleObject;

    // Name
    exampleObject.set(SerializeKey::Name, WrapSourcemap(example.name));

    // Description
    exampleObject.set(SerializeKey::Description, WrapSourcemap(example.description));

    // Requests
    exampleObject.set(SerializeKey::Requests,
                      WrapCollection<Request>()(example.requests.collection, WrapPayloadSourcemap));

    // Responses
    exampleObject.set(SerializeKey::Responses,
                      WrapCollection<Response>()(example.responses.collection, WrapPayloadSourcemap));

    return exampleObject;
}

sos::Object WrapActionSourcemap(const SourceMap<Action>& action)
{
    sos::Object actionObject;

    // Name
    actionObject.set(SerializeKey::Name, WrapSourcemap(action.name));

    // Description
    actionObject.set(SerializeKey::Description, WrapSourcemap(action.description));

    // HTTP Method
    actionObject.set(SerializeKey::Method, WrapSourcemap(action.method));

    // Parameters
    actionObject.set(SerializeKey::Parameters, WrapParametersSourcemap(action.parameters));

    // Transaction Examples
    actionObject.set(SerializeKey::Examples,
                     WrapCollection<TransactionExample>()(action.examples.collection, WrapTransactionExampleSourcemap));

    // Content
    sos::Array content;

    /// Attributes
    if (!action.attributes.empty()) {
        content.push(WrapDataStructureSourcemap(action.attributes));
    }

    actionObject.set(SerializeKey::Content, content);

    return actionObject;
}

sos::Object WrapResourceSourcemap(const SourceMap<Resource>& resource)
{
    sos::Object resourceObject;

    // Name
    resourceObject.set(SerializeKey::Name, WrapSourcemap(resource.name));

    // Description
    resourceObject.set(SerializeKey::Description, WrapSourcemap(resource.description));

    // URI Template
    resourceObject.set(SerializeKey::URITemplate, WrapSourcemap(resource.uriTemplate));

    // Model
    sos::Object model = (resource.model.name.sourceMap.empty() ? sos::Object() : WrapPayloadSourcemap(resource.model));
    resourceObject.set(SerializeKey::Model, model);

    // Parameters
    resourceObject.set(SerializeKey::Parameters, WrapParametersSourcemap(resource.parameters));

    // Actions
    resourceObject.set(SerializeKey::Actions,
                       WrapCollection<Action>()(resource.actions.collection, WrapActionSourcemap));

    // Content
    sos::Array content;

    /// Attributes
    if (!resource.attributes.empty()) {
        content.push(WrapDataStructureSourcemap(resource.attributes));
    }

    resourceObject.set(SerializeKey::Content, content);

    return resourceObject;
}

sos::Object WrapResourceGroupSourcemap(const SourceMap<Element>& resourceGroup)
{
    sos::Object resourceGroupObject;

    // Name
    resourceGroupObject.set(SerializeKey::Name, WrapSourcemap(resourceGroup.attributes.name));

    // Description & Resources
    SourceMap<Description> description;
    sos::Array resources;

    for (Collection<SourceMap<Element> >::const_iterator it = resourceGroup.content.elements().collection.begin();
         it != resourceGroup.content.elements().collection.end();
         ++it) {

        if (it->element == Element::ResourceElement) {
            resources.push(WrapResourceSourcemap(it->content.resource));
        }
        else if (it->element == Element::CopyElement) {
            description.sourceMap.append(it->content.copy.sourceMap);
        }
    }

    resourceGroupObject.set(SerializeKey::Description, WrapSourcemap(description));
    resourceGroupObject.set(SerializeKey::Resources, resources);

    return resourceGroupObject;
}

sos::Object WrapDataStructureContent(const SourceMap<DataStructure>& dataStructure)
{
    sos::Object dataStructureObject;

    // Source
    dataStructureObject.set(SerializeKey::Source, WrapNamedTypeSourcemap(dataStructure));

    return dataStructureObject;
}

sos::Object WrapElementSourcemap(const SourceMap<Element>& element)
{
    sos::Object elementObject;

    if (!element.attributes.name.sourceMap.empty()) {

        sos::Object attributes;

        attributes.set(SerializeKey::Name, WrapSourcemap(element.attributes.name));
        elementObject.set(SerializeKey::Attributes, attributes);
    }

    switch (element.element) {
        case Element::CopyElement:
        {
            elementObject.set(SerializeKey::Content, WrapSourcemap(element.content.copy));
            break;
        }

        case Element::DataStructureElement:
        {
            return WrapDataStructureSourcemap(element.content.dataStructure);
        }

        case Element::ResourceElement:
        {
            return WrapResourceSourcemap(element.content.resource);
        }

        case Element::CategoryElement:
        {
            elementObject.set(SerializeKey::Content,
                              WrapCollection<Element>()(element.content.elements().collection, WrapElementSourcemap));
            break;
        }

        default:
            break;
    }

    return elementObject;
}

sos::Object drafter::WrapBlueprintSourcemap(const SourceMap<Blueprint>& blueprint)
{
    sos::Object blueprintObject;

    // Metadata
    blueprintObject.set(SerializeKey::Metadata,
                        WrapCollection<Metadata>()(blueprint.metadata.collection, WrapSourcemap));

    // Name
    blueprintObject.set(SerializeKey::Name, WrapSourcemap(blueprint.name));

    // Description
    blueprintObject.set(SerializeKey::Description, WrapSourcemap(blueprint.description));

    // Resource Groups
    sos::Array resourceGroups;

    for (Collection<SourceMap<Element> >::const_iterator it = blueprint.content.elements().collection.begin();
         it != blueprint.content.elements().collection.end();
         ++it) {

        if (it->element == Element::CategoryElement &&
            it->category == Element::ResourceGroupCategory) {

            resourceGroups.push(WrapResourceGroupSourcemap(*it));
        }
    }

    blueprintObject.set(SerializeKey::ResourceGroups, resourceGroups);

    // Content
    blueprintObject.set(SerializeKey::Content,
                        WrapCollection<Element>()(blueprint.content.elements().collection, WrapElementSourcemap));
    return blueprintObject;
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/isteps/istep15/host_establish_ex_chiplet.C $          */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016                             */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

//From Hostboot Directory
////Error handling and traces
#include    <errl/errlentry.H>
#include    <errl/errluserdetails.H>
#include    <errl/errludtarget.H>
#include    <errl/errlmanager.H>
#include    <isteps/hwpisteperror.H>
#include    <initservice/isteps_trace.H>

//HWP Invoker
#include    <fapi2/plat_hwp_invoker.H>

//Targeting Support
#include    <targeting/common/utilFilter.H>
#include    <fapi2/target.H>

//From Import Directory (EKB Repository)
#include    <p9_update_ec_eq_state.H>

//Namespaces
using namespace ERRORLOG;
using namespace TARGETING;
using namespace fapi2;

namespace ISTEP_15
{
void* host_establish_ex_chiplet (void *io_pArgs)
{
    TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_establish_ex_chiplet entry" );
    ISTEP_ERROR::IStepError l_StepError;
    errlHndl_t l_errl = NULL;
    do {
        //Use targeting code to get a list of all processors
        TARGETING::TargetHandleList l_procChips;
        getAllChips( l_procChips, TARGETING::TYPE_PROC   );

        for (const auto & l_procChip: l_procChips)
        {
            const fapi2::Target<TARGET_TYPE_PROC_CHIP>
                l_fapi_cpu_target(l_procChip);
            // call p9_update_ec_eq_state.C HWP
            FAPI_INVOKE_HWP( l_errl,
                             p9_update_ec_eq_state,
                             l_fapi_cpu_target);

            if(l_errl)
            {
                ErrlUserDetailsTarget(l_procChip).addToLog(l_errl);
                l_StepError.addErrorDetails( l_errl );
                errlCommit( l_errl, HWPF_COMP_ID );
                TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_establish_ex_chiplet:: failed on proc with HUID : %d",TARGETING::get_huid(l_procChip)  );
            }
        }
    }while(0);

    // end task, returning any errorlogs to IStepDisp
    TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_establish_ex_chiplet exit" );
    return l_StepError.getErrorHandle();
}
};
<commit_msg>Skip establish ex chiplet step (15.3) during Axone for now<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/isteps/istep15/host_establish_ex_chiplet.C $          */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016                             */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

//From Hostboot Directory
////Error handling and traces
#include    <errl/errlentry.H>
#include    <errl/errluserdetails.H>
#include    <errl/errludtarget.H>
#include    <errl/errlmanager.H>
#include    <isteps/hwpisteperror.H>
#include    <initservice/isteps_trace.H>

//HWP Invoker
#include    <fapi2/plat_hwp_invoker.H>

//Targeting Support
#include    <targeting/common/utilFilter.H>
#include    <fapi2/target.H>

//From Import Directory (EKB Repository)
#include    <p9_update_ec_eq_state.H>

//Namespaces
using namespace ERRORLOG;
using namespace TARGETING;
using namespace fapi2;

namespace ISTEP_15
{
void* host_establish_ex_chiplet (void *io_pArgs)
{
    TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_establish_ex_chiplet entry" );
    ISTEP_ERROR::IStepError l_StepError;
    #ifndef CONFIG_AXONE_BRING_UP
    errlHndl_t l_errl = NULL;
    do {
        //Use targeting code to get a list of all processors
        TARGETING::TargetHandleList l_procChips;
        getAllChips( l_procChips, TARGETING::TYPE_PROC   );

        for (const auto & l_procChip: l_procChips)
        {
            const fapi2::Target<TARGET_TYPE_PROC_CHIP>
                l_fapi_cpu_target(l_procChip);
            // call p9_update_ec_eq_state.C HWP
            FAPI_INVOKE_HWP( l_errl,
                             p9_update_ec_eq_state,
                             l_fapi_cpu_target);

            if(l_errl)
            {
                ErrlUserDetailsTarget(l_procChip).addToLog(l_errl);
                l_StepError.addErrorDetails( l_errl );
                errlCommit( l_errl, HWPF_COMP_ID );
                TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_establish_ex_chiplet:: failed on proc with HUID : %d",TARGETING::get_huid(l_procChip)  );
            }
        }
    }while(0);
    #endif

    // end task, returning any errorlogs to IStepDisp
    TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_establish_ex_chiplet exit" );
    return l_StepError.getErrorHandle();
}
};
<|endoftext|>


<commit_before>#include <iostream>

#include <vector>

#include "rev.hpp"

int main(int, char*[])
{
  for (auto& i: gnr::rev({1, 2, 3, 4}))
  {
    std::cout << i << std::endl;
  }

  auto r(std::vector<int>{1, 2, 3, 4});

  for (auto& i: gnr::rev(r))
  {
    std::cout << i << std::endl;
    i = 0;
  }
}
<commit_msg>some fixes<commit_after>#include <iostream>

#include <vector>

#include "rev.hpp"

int main(int, char*[])
{
  for (auto& i: gnr::rev({1, 2, 3, 4}))
  {
    std::cout << i << std::endl;
  }

  std::vector<int> r{1, 2, 3, 4};

  for (auto& i: gnr::rev(r))
  {
    std::cout << i << std::endl;
    i = 0;
  }
}
<|endoftext|>


<commit_before>#ifndef GENERIC_REV_HPP
# define GENERIC_REV_HPP
# pragma once

#include <iterator>

#include <type_traits>

namespace gnr
{

namespace detail
{

template <typename T>
class rev_impl
{
  T ref_;

public:
  explicit rev_impl(T&& r) noexcept(noexcept(T(std::forward<T>(r)))) :
    ref_(std::forward<T>(r))
  {
  };

  auto begin() noexcept(noexcept(std::rbegin(ref_)))
  {
    return std::rbegin(ref_);
  }

  auto end() noexcept(noexcept(std::rend(ref_)))
  {
    return std::rend(ref_);
  }
};

}

template <typename T>
auto rev(T&& r) noexcept(noexcept(detail::rev_impl<T>(std::forward<T>(r))))
{
  return detail::rev_impl<T>(std::forward<T>(r));
}

}

#endif // GENERIC_REV_HPP
<commit_msg>some fixes<commit_after>#ifndef GENERIC_REV_HPP
# define GENERIC_REV_HPP
# pragma once

#include <iterator>

#include <type_traits>

namespace gnr
{

namespace detail
{

template <typename T>
class rev_impl
{
  T ref_;

public:
  explicit rev_impl(T&& r) noexcept(noexcept(T(std::forward<T>(r)))) :
    ref_(std::forward<T>(r))
  {
  }

  auto begin() noexcept(noexcept(std::rbegin(ref_)))
  {
    return std::rbegin(ref_);
  }

  auto end() noexcept(noexcept(std::rend(ref_)))
  {
    return std::rend(ref_);
  }
};

}

template <typename T>
auto rev(T&& r) noexcept(noexcept(detail::rev_impl<T>(std::forward<T>(r))))
{
  return detail::rev_impl<T>(std::forward<T>(r));
}

}

#endif // GENERIC_REV_HPP
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2020.  All rights reserved
 */
#include "../StroikaPreComp.h"

#include "../Debug/Demangle.h"
#include "../Execution/Exceptions.h"

#include "String_Constant.h"

#include "ToString.h"

using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;

/*
 ********************************************************************************
 ************************************* ToString *********************************
 ********************************************************************************
 */
namespace Stroika::Foundation::Characters {
    template <>
    String ToString (const exception_ptr& e)
    {
        static const String kExceptPefix_{L"Exception: "sv};
        static const String kUnknown_{L"Unknown Exception"sv};
        try {
            rethrow_exception (e);
        }
        catch (const Execution::ExceptionStringHelper& e) {
            //saying Exception: first produces 'Exception: HTTP exception: status 404 (URL not found)}' - redundant. Not sure about all cases, but try this way.
            //return kExceptPefix_ + e.As<String> ();
            return e.As<String> ();
        }
        catch (const exception& e) {
            return kExceptPefix_ + String::FromNarrowSDKString (e.what ());
        }
        catch (...) {
            // fall through
        }
        return kUnknown_;
    }
    template <>
    String ToString (const type_info& t)
    {
        //nb: demangle needed for gcc, but not msvc (but harmless there)
        return Debug::Demangle (String::FromNarrowSDKString (t.name ()));
    }
    template <>
    String ToString (const type_index& t)
    {
        //nb: demangle needed for gcc, but not msvc (but harmless there)
        return Debug::Demangle (String::FromNarrowSDKString (t.name ()));
    }

    String ToString (const char* t)
    {
        // No way to know the 'right' characterset in this case, but as this is mostly used for debugging, no biggie. The caller
        // can be more careful if he cares about charset. This should be safe, and mostly helpful
        return String::FromISOLatin1 (t);
    }

    template <>
    String ToString (const bool& t)
    {
        static const String kTrue_{L"true"sv};
        static const String kFalse{L"false"sv};
        return t ? kTrue_ : kFalse;
    }

    namespace {
        template <typename T>
        inline String num2Str_ (T t, std::ios_base::fmtflags flags)
        {
            static_assert (sizeof (t) <= sizeof (int));
            wchar_t buf[1024];
            switch (flags) {
                case std::ios_base::dec:
                    (void)::swprintf (buf, NEltsOf (buf), L"%d", t);
                    break;
                case std::ios_base::hex:
                    (void)::swprintf (buf, NEltsOf (buf), L"0x%x", t);
                    break;
                default:
                    AssertNotReached (); // @todo support octal
            }
            return buf;
        }
        template <typename T>
        inline String num2Strl_ (T t, std::ios_base::fmtflags flags)
        {
            wchar_t buf[1024];
            static_assert (sizeof (t) == sizeof (long int));
            switch (flags) {
                case std::ios_base::dec:
                    (void)::swprintf (buf, NEltsOf (buf), L"%ld", t);
                    break;
                case std::ios_base::hex:
                    (void)::swprintf (buf, NEltsOf (buf), L"0x%lx", t);
                    break;
                default:
                    AssertNotReached (); // @todo support octal
            }
            return buf;
        }
        template <typename T>
        inline String num2Strll_ (T t, std::ios_base::fmtflags flags)
        {
            wchar_t buf[1024];
            static_assert (sizeof (t) == sizeof (long long int));
            switch (flags) {
                case std::ios_base::dec:
                    (void)::swprintf (buf, NEltsOf (buf), L"%lld", t);
                    break;
                case std::ios_base::hex:
                    (void)::swprintf (buf, NEltsOf (buf), L"0x%llx", t);
                    break;
                default:
                    AssertNotReached (); // @todo support octal
            }
            return buf;
        }
    }

    template <>
    String ToString (const signed char t, std::ios_base::fmtflags flags)
    {
        return num2Str_ (t, flags);
    }
    template <>
    String ToString (const short int t, std::ios_base::fmtflags flags)
    {
        return num2Str_ (t, flags);
    }
    template <>
    String ToString (const int t, std::ios_base::fmtflags flags)
    {
        return num2Str_ (t, flags);
    }
    template <>
    String ToString (const long int t, std::ios_base::fmtflags flags)
    {
        return num2Strl_ (t, flags);
    }
    template <>
    String ToString (const long long int t, std::ios_base::fmtflags flags)
    {
        return num2Strll_ (t, flags);
    }
    template <>
    String ToString (const unsigned char t, std::ios_base::fmtflags flags)
    {
        return num2Str_ (t, flags);
    }
    template <>
    String ToString (const unsigned short t, std::ios_base::fmtflags flags)
    {
        return num2Str_ (t, flags);
    }
    template <>
    String ToString (const unsigned int t, std::ios_base::fmtflags flags)
    {
        return num2Str_ (t, flags);
    }
    template <>
    String ToString (const unsigned long t, std::ios_base::fmtflags flags)
    {
        return num2Strl_ (t, flags);
    }
    template <>
    String ToString (const unsigned long long t, std::ios_base::fmtflags flags)
    {
        return num2Strll_ (t, flags);
    }

    namespace Private_ {
        String ToString_ex_ (const std::exception& t)
        {
            if (auto p = dynamic_cast<const Execution::ExceptionStringHelper*> (&t)) {
                return p->As<String> ();
            }
            //saying Exception: first produces 'Exception: HTTP exception: status 404 (URL not found)}' - redundant. Not sure about all cases, but try this way.
            //return String_Constant {L"Exception: " } + String::FromNarrowSDKString (t.what ()) + String_Constant {L"}" };
            return String::FromNarrowSDKString (t.what ());
        }
    }
}
<commit_msg>ToString (integer-like-type) support for std::ios_base::oct argument<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2020.  All rights reserved
 */
#include "../StroikaPreComp.h"

#include "../Debug/Demangle.h"
#include "../Execution/Exceptions.h"

#include "String_Constant.h"

#include "ToString.h"

using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;

/*
 ********************************************************************************
 ************************************* ToString *********************************
 ********************************************************************************
 */
namespace Stroika::Foundation::Characters {
    template <>
    String ToString (const exception_ptr& e)
    {
        static const String kExceptPefix_{L"Exception: "sv};
        static const String kUnknown_{L"Unknown Exception"sv};
        try {
            rethrow_exception (e);
        }
        catch (const Execution::ExceptionStringHelper& e) {
            //saying Exception: first produces 'Exception: HTTP exception: status 404 (URL not found)}' - redundant. Not sure about all cases, but try this way.
            //return kExceptPefix_ + e.As<String> ();
            return e.As<String> ();
        }
        catch (const exception& e) {
            return kExceptPefix_ + String::FromNarrowSDKString (e.what ());
        }
        catch (...) {
            // fall through
        }
        return kUnknown_;
    }
    template <>
    String ToString (const type_info& t)
    {
        //nb: demangle needed for gcc, but not msvc (but harmless there)
        return Debug::Demangle (String::FromNarrowSDKString (t.name ()));
    }
    template <>
    String ToString (const type_index& t)
    {
        //nb: demangle needed for gcc, but not msvc (but harmless there)
        return Debug::Demangle (String::FromNarrowSDKString (t.name ()));
    }

    String ToString (const char* t)
    {
        // No way to know the 'right' characterset in this case, but as this is mostly used for debugging, no biggie. The caller
        // can be more careful if he cares about charset. This should be safe, and mostly helpful
        return String::FromISOLatin1 (t);
    }

    template <>
    String ToString (const bool& t)
    {
        static const String kTrue_{L"true"sv};
        static const String kFalse{L"false"sv};
        return t ? kTrue_ : kFalse;
    }

    namespace {
        template <typename T>
        inline String num2Str_ (T t, std::ios_base::fmtflags flags)
        {
            static_assert (sizeof (t) <= sizeof (int));
            wchar_t buf[1024];
            switch (flags) {
                case std::ios_base::oct:
                    (void)::swprintf (buf, NEltsOf (buf), L"%o", t);
                    break;
                case std::ios_base::dec:
                    (void)::swprintf (buf, NEltsOf (buf), L"%d", t);
                    break;
                case std::ios_base::hex:
                    (void)::swprintf (buf, NEltsOf (buf), L"0x%x", t);
                    break;
                default:
                    AssertNotReached (); // @todo support octal
            }
            return buf;
        }
        template <typename T>
        inline String num2Strl_ (T t, std::ios_base::fmtflags flags)
        {
            wchar_t buf[1024];
            static_assert (sizeof (t) == sizeof (long int));
            switch (flags) {
                case std::ios_base::oct:
                    (void)::swprintf (buf, NEltsOf (buf), L"%lo", t);
                    break;
                case std::ios_base::dec:
                    (void)::swprintf (buf, NEltsOf (buf), L"%ld", t);
                    break;
                case std::ios_base::hex:
                    (void)::swprintf (buf, NEltsOf (buf), L"0x%lx", t);
                    break;
                default:
                    AssertNotReached (); // @todo support octal
            }
            return buf;
        }
        template <typename T>
        inline String num2Strll_ (T t, std::ios_base::fmtflags flags)
        {
            wchar_t buf[1024];
            static_assert (sizeof (t) == sizeof (long long int));
            switch (flags) {
                case std::ios_base::oct:
                    (void)::swprintf (buf, NEltsOf (buf), L"%llo", t);
                    break;
                case std::ios_base::dec:
                    (void)::swprintf (buf, NEltsOf (buf), L"%lld", t);
                    break;
                case std::ios_base::hex:
                    (void)::swprintf (buf, NEltsOf (buf), L"0x%llx", t);
                    break;
                default:
                    AssertNotReached (); // @todo support octal
            }
            return buf;
        }
    }

    template <>
    String ToString (const signed char t, std::ios_base::fmtflags flags)
    {
        return num2Str_ (t, flags);
    }
    template <>
    String ToString (const short int t, std::ios_base::fmtflags flags)
    {
        return num2Str_ (t, flags);
    }
    template <>
    String ToString (const int t, std::ios_base::fmtflags flags)
    {
        return num2Str_ (t, flags);
    }
    template <>
    String ToString (const long int t, std::ios_base::fmtflags flags)
    {
        return num2Strl_ (t, flags);
    }
    template <>
    String ToString (const long long int t, std::ios_base::fmtflags flags)
    {
        return num2Strll_ (t, flags);
    }
    template <>
    String ToString (const unsigned char t, std::ios_base::fmtflags flags)
    {
        return num2Str_ (t, flags);
    }
    template <>
    String ToString (const unsigned short t, std::ios_base::fmtflags flags)
    {
        return num2Str_ (t, flags);
    }
    template <>
    String ToString (const unsigned int t, std::ios_base::fmtflags flags)
    {
        return num2Str_ (t, flags);
    }
    template <>
    String ToString (const unsigned long t, std::ios_base::fmtflags flags)
    {
        return num2Strl_ (t, flags);
    }
    template <>
    String ToString (const unsigned long long t, std::ios_base::fmtflags flags)
    {
        return num2Strll_ (t, flags);
    }

    namespace Private_ {
        String ToString_ex_ (const std::exception& t)
        {
            if (auto p = dynamic_cast<const Execution::ExceptionStringHelper*> (&t)) {
                return p->As<String> ();
            }
            //saying Exception: first produces 'Exception: HTTP exception: status 404 (URL not found)}' - redundant. Not sure about all cases, but try this way.
            //return String_Constant {L"Exception: " } + String::FromNarrowSDKString (t.what ()) + String_Constant {L"}" };
            return String::FromNarrowSDKString (t.what ());
        }
    }
}
<|endoftext|>


<commit_before>/*
  Q Light Controller
  efxpreviewarea.cpp

  Copyright (c) Heikki Junnila

  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 <QPaintEvent>
#include <QPainter>
#include <QDebug>
#include <QPen>

#include "efxpreviewarea.h"
#include "qlcmacros.h"
#include "gradient.h"

EFXPreviewArea::EFXPreviewArea(QWidget* parent)
    : QWidget(parent)
    , m_timer(this)
    , m_iter(0)
    , m_gradientBg(false)
    , m_bgAlpha(255)
{
    QPalette p = palette();
    p.setColor(QPalette::Window, p.color(QPalette::Base));
    setPalette(p);

    connect(&m_timer, SIGNAL(timeout()), this, SLOT(slotTimeout()));
}

EFXPreviewArea::~EFXPreviewArea()
{
}

void EFXPreviewArea::setPolygon(const QPolygonF& polygon)
{
    m_original = polygon;
    m_scaled = scale(m_original, size());
}

int EFXPreviewArea::polygonsCount() const
{
    return m_original.size();
}

void EFXPreviewArea::setFixturePolygons(const QVector<QPolygonF> &fixturePoints)
{
    m_originalFixturePoints.resize(fixturePoints.size());
    m_fixturePoints.resize(fixturePoints.size());

    for(int i = 0; i < m_fixturePoints.size(); ++i)
    {
        m_originalFixturePoints[i] = QPolygonF(fixturePoints[i]);
        m_fixturePoints[i] = scale(m_originalFixturePoints[i], size());
    }
}

void EFXPreviewArea::draw(int timerInterval)
{
    m_timer.stop();

    m_iter = 0;
    m_timer.start(timerInterval);
}

void EFXPreviewArea::slotTimeout()
{
    repaint();
}

QPolygonF EFXPreviewArea::scale(const QPolygonF& poly, const QSize& target)
{
    QPolygonF scaled;
    for (int i = 0; i < poly.size(); i++)
    {
        QPointF pt = poly.at(i);
        pt.setX((int) SCALE(qreal(pt.x()), qreal(0), qreal(255), qreal(0), qreal(target.width())));
        pt.setY((int) SCALE(qreal(pt.y()), qreal(0), qreal(255), qreal(0), qreal(target.height())));
        scaled << pt;
    }

    return scaled;
}

void EFXPreviewArea::resizeEvent(QResizeEvent* e)
{
    m_scaled = scale(m_original, e->size());

    for (int i = 0; i < m_fixturePoints.size(); ++i)
        m_fixturePoints[i] = scale(m_originalFixturePoints[i], e->size());

    QWidget::resizeEvent(e);
}

void EFXPreviewArea::paintEvent(QPaintEvent* e)
{
    QWidget::paintEvent(e);

    QPainter painter(this);
    QPen pen;
    QPointF point;
    QColor color = Qt::white;

    if (m_gradientBg)
        painter.drawImage(painter.window(), Gradient::getRGBGradient(256, 256));
    else
    {
        color.setAlpha(m_bgAlpha);
        painter.fillRect(rect(), color);
    }

    /* Crosshairs */
    color = palette().color(QPalette::Mid);
    painter.setPen(color);
    // Do division by two instead with a bitshift to prevent rounding
    painter.drawLine(width() >> 1, 0, width() >> 1, height());
    painter.drawLine(0, height() >> 1, width(), height() >> 1);

    if (m_iter < m_scaled.size())
        m_iter++;

    /* Plain points with text color */
    color = palette().color(QPalette::Text);
    pen.setColor(color);
    painter.setPen(pen);
    painter.drawPolygon(m_scaled);

    // Draw the points from the point array
    if (m_iter < m_scaled.size() && m_iter >= 0)
    {
        /*
        // draw origin
        color = color.lighter(100 + (m_points.size() / 100));
        pen.setColor(color);
        painter.setPen(pen);
        point = m_points.point(m_iter);
        painter.drawEllipse(point.x() - 4, point.y() - 4, 8, 8);
        */

        painter.setBrush(Qt::white);
        pen.setColor(Qt::black);

        // draw fixture positions

        // drawing from the end -- so that lower numbers are on top
        for (int i = m_fixturePoints.size() - 1; i >= 0; --i)
        {
            point = m_fixturePoints.at(i).at(m_iter);
            painter.drawEllipse(point, 8, 8);
            painter.drawText(point.x() - 4, point.y() + 5, QString::number(i+1));
        }
    }
    else
    {
        //m_timer.stop();

        //Change old behaviour from stop to restart
        restart();
    }
}

void EFXPreviewArea::restart ()
{
    m_iter = 0;
}

void EFXPreviewArea::showGradientBackground(bool enable)
{
    m_gradientBg = enable;
    repaint();
}

void EFXPreviewArea::setBackgroundAlpha(int alpha)
{
    m_bgAlpha = alpha;
}
<commit_msg>ui: fixed EFX preview area not respecting the requested speed<commit_after>/*
  Q Light Controller
  efxpreviewarea.cpp

  Copyright (c) Heikki Junnila

  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 <QPaintEvent>
#include <QPainter>
#include <QDebug>
#include <QPen>

#include "efxpreviewarea.h"
#include "qlcmacros.h"
#include "gradient.h"

EFXPreviewArea::EFXPreviewArea(QWidget* parent)
    : QWidget(parent)
    , m_timer(this)
    , m_iter(0)
    , m_gradientBg(false)
    , m_bgAlpha(255)
{
    QPalette p = palette();
    p.setColor(QPalette::Window, p.color(QPalette::Base));
    setPalette(p);

    connect(&m_timer, SIGNAL(timeout()), this, SLOT(slotTimeout()));
}

EFXPreviewArea::~EFXPreviewArea()
{
}

void EFXPreviewArea::setPolygon(const QPolygonF& polygon)
{
    m_original = polygon;
    m_scaled = scale(m_original, size());
}

int EFXPreviewArea::polygonsCount() const
{
    return m_original.size();
}

void EFXPreviewArea::setFixturePolygons(const QVector<QPolygonF> &fixturePoints)
{
    m_originalFixturePoints.resize(fixturePoints.size());
    m_fixturePoints.resize(fixturePoints.size());

    for(int i = 0; i < m_fixturePoints.size(); ++i)
    {
        m_originalFixturePoints[i] = QPolygonF(fixturePoints[i]);
        m_fixturePoints[i] = scale(m_originalFixturePoints[i], size());
    }
}

void EFXPreviewArea::draw(int timerInterval)
{
    m_timer.stop();

    m_iter = 0;
    m_timer.start(timerInterval);
}

void EFXPreviewArea::slotTimeout()
{
    if (m_iter < m_scaled.size())
        m_iter++;

    repaint();
}

QPolygonF EFXPreviewArea::scale(const QPolygonF& poly, const QSize& target)
{
    QPolygonF scaled;
    for (int i = 0; i < poly.size(); i++)
    {
        QPointF pt = poly.at(i);
        pt.setX((int) SCALE(qreal(pt.x()), qreal(0), qreal(255), qreal(0), qreal(target.width())));
        pt.setY((int) SCALE(qreal(pt.y()), qreal(0), qreal(255), qreal(0), qreal(target.height())));
        scaled << pt;
    }

    return scaled;
}

void EFXPreviewArea::resizeEvent(QResizeEvent* e)
{
    m_scaled = scale(m_original, e->size());

    for (int i = 0; i < m_fixturePoints.size(); ++i)
        m_fixturePoints[i] = scale(m_originalFixturePoints[i], e->size());

    QWidget::resizeEvent(e);
}

void EFXPreviewArea::paintEvent(QPaintEvent* e)
{
    QWidget::paintEvent(e);

    QPainter painter(this);
    QPen pen;
    QPointF point;
    QColor color = Qt::white;

    if (m_gradientBg)
        painter.drawImage(painter.window(), Gradient::getRGBGradient(256, 256));
    else
    {
        color.setAlpha(m_bgAlpha);
        painter.fillRect(rect(), color);
    }

    /* Crosshairs */
    color = palette().color(QPalette::Mid);
    painter.setPen(color);
    // Do division by two instead with a bitshift to prevent rounding
    painter.drawLine(width() >> 1, 0, width() >> 1, height());
    painter.drawLine(0, height() >> 1, width(), height() >> 1);

    /* Plain points with text color */
    color = palette().color(QPalette::Text);
    pen.setColor(color);
    painter.setPen(pen);
    painter.drawPolygon(m_scaled);

    // Draw the points from the point array
    if (m_iter < m_scaled.size() && m_iter >= 0)
    {
        painter.setBrush(Qt::white);
        pen.setColor(Qt::black);

        // drawing fixture positions from the end,
        // so that lower numbers are on top
        for (int i = m_fixturePoints.size() - 1; i >= 0; --i)
        {
            point = m_fixturePoints.at(i).at(m_iter);
            painter.drawEllipse(point, 8, 8);
            painter.drawText(point.x() - 4, point.y() + 5, QString::number(i+1));
        }
    }
    else
    {
        //Change old behaviour from stop to restart
        restart();
    }
}

void EFXPreviewArea::restart()
{
    m_iter = 0;
}

void EFXPreviewArea::showGradientBackground(bool enable)
{
    m_gradientBg = enable;
    repaint();
}

void EFXPreviewArea::setBackgroundAlpha(int alpha)
{
    m_bgAlpha = alpha;
}
<|endoftext|>


<commit_before>// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.

#include <algorithm>
#include "AudioDevice.hpp"
#include "math/MathUtils.hpp"

namespace ouzel
{
    namespace audio
    {
        AudioDevice::AudioDevice(Audio::Driver aDriver):
            driver(aDriver)
        {
        }

        AudioDevice::~AudioDevice()
        {
        }

        bool AudioDevice::init(bool)
        {
            return true;
        }

        bool AudioDevice::process()
        {
            executeAll();

            return true;
        }

        void AudioDevice::setRenderCommands(const std::vector<RenderCommand>& newRenderCommands)
        {
            std::lock_guard<std::mutex> renderQueueLock(renderQueueMutex);

            renderQueue = newRenderCommands;
        }

        bool AudioDevice::processRenderCommands(uint32_t frames, std::vector<float>& result)
        {
            std::vector<RenderCommand> renderCommands;

            {
                std::lock_guard<std::mutex> renderQueueLock(renderQueueMutex);

                renderCommands = renderQueue;
            }

            uint32_t buffer = currentBuffer++;
            if (currentBuffer > buffers.size()) buffers.resize(currentBuffer);

            for (const RenderCommand& renderCommand : renderCommands)
            {
                if (!processRenderCommand(renderCommand,
                                          frames,
                                          Vector3(), // listener position
                                          Quaternion(), // listener rotation
                                          1.0f, // pitch
                                          1.0f, // gain
                                          1.0f, // rolloff factor
                                          buffers[buffer])) return false;

                if (buffers[buffer].size() > buffers[buffer].size()) result.resize(buffers[buffer].size(), 0.0f);

                for (uint32_t i = 0; i < buffers[buffer].size() && i < result.size(); ++i)
                {
                    // mix the sound into the buffer
                    result[i] += buffers[buffer][i];
                }
            }

            return true;
        }

        bool AudioDevice::processRenderCommand(const RenderCommand& renderCommand,
                                               uint32_t frames,
                                               Vector3 listenerPosition,
                                               Quaternion listenerRotation,
                                               float pitch,
                                               float gain,
                                               float rolloffFactor,
                                               std::vector<float>& result)
        {
            uint32_t buffer = currentBuffer++;
            if (currentBuffer > buffers.size()) buffers.resize(currentBuffer);

            if (renderCommand.attributeCallback)
            {
                renderCommand.attributeCallback(listenerPosition,
                                                listenerRotation,
                                                pitch,
                                                gain,
                                                rolloffFactor);
            }

            for (const RenderCommand& command : renderCommand.renderCommands)
            {
                processRenderCommand(command,
                                     frames,
                                     listenerPosition,
                                     listenerRotation,
                                     pitch,
                                     gain,
                                     rolloffFactor,
                                     buffers[buffer]);

                if (buffers[buffer].size() > result.size()) result.resize(buffers[buffer].size(), 0.0f);

                for (uint32_t i = 0; i < buffers[buffer].size() && i < result.size(); ++i)
                {
                    // mix the sound into the buffer
                    result[i] += buffers[buffer][i];
                }
            }

            if (renderCommand.renderCallback)
            {
                if (!renderCommand.renderCallback(frames,
                                                  channels,
                                                  sampleRate,
                                                  listenerPosition,
                                                  listenerRotation,
                                                  pitch,
                                                  gain,
                                                  rolloffFactor,
                                                  result)) return false;
            }

            return true;
        }

        bool AudioDevice::getData(uint32_t frames, std::vector<uint8_t>& result)
        {
            currentBuffer = 0;
            uint32_t buffer = currentBuffer++;
            if (currentBuffer > buffers.size()) buffers.resize(currentBuffer);

            buffers[buffer].resize(frames * channels);
            std::fill(buffers[buffer].begin(), buffers[buffer].end(), 0.0f);

            if (!processRenderCommands(frames, buffers[buffer])) return false;

            for (float& f : buffers[buffer])
            {
                f = clamp(f, -1.0f, 1.0f);
            }

            switch (format)
            {
                case Audio::Format::SINT16:
                {
                    result.resize(frames * channels * sizeof(int16_t));
                    int16_t* resultPtr = reinterpret_cast<int16_t*>(result.data());

                    for (uint32_t i = 0; i < buffers[buffer].size(); ++i)
                    {
                        *resultPtr = static_cast<int16_t>(buffers[buffer][i] * 32767.0f);
                        ++resultPtr;
                    }
                    break;
                }
                case Audio::Format::FLOAT32:
                {
                    result.reserve(frames * channels * sizeof(float));
                    result.assign(reinterpret_cast<uint8_t*>(buffers[buffer].data()),
                                  reinterpret_cast<uint8_t*>(buffers[buffer].data()) + buffers[buffer].size() * sizeof(float));
                    break;
                }
            }

            return true;
        }

        void AudioDevice::executeOnAudioThread(const std::function<void(void)>& func)
        {
            std::lock_guard<std::mutex> lock(executeMutex);

            executeQueue.push(func);
        }

        void AudioDevice::executeAll()
        {
            std::function<void(void)> func;

            for (;;)
            {
                {
                    std::lock_guard<std::mutex> lock(executeMutex);

                    if (executeQueue.empty())
                    {
                        break;
                    }

                    func = std::move(executeQueue.front());
                    executeQueue.pop();
                }

                if (func)
                {
                    func();
                }
            }
        }
    } // namespace audio
} // namespace ouzel
<commit_msg>no message<commit_after>// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.

#include <algorithm>
#include "AudioDevice.hpp"
#include "math/MathUtils.hpp"

namespace ouzel
{
    namespace audio
    {
        AudioDevice::AudioDevice(Audio::Driver aDriver):
            driver(aDriver)
        {
            buffers.resize(1000);
        }

        AudioDevice::~AudioDevice()
        {
        }

        bool AudioDevice::init(bool)
        {
            return true;
        }

        bool AudioDevice::process()
        {
            executeAll();

            return true;
        }

        void AudioDevice::setRenderCommands(const std::vector<RenderCommand>& newRenderCommands)
        {
            std::lock_guard<std::mutex> renderQueueLock(renderQueueMutex);

            renderQueue = newRenderCommands;
        }

        bool AudioDevice::processRenderCommands(uint32_t frames, std::vector<float>& result)
        {
            std::vector<RenderCommand> renderCommands;

            {
                std::lock_guard<std::mutex> renderQueueLock(renderQueueMutex);

                renderCommands = renderQueue;
            }

            uint32_t buffer = currentBuffer++;
            if (currentBuffer > buffers.size()) return true; // out of buffers

            buffers[buffer].resize(frames * channels);
            std::fill(buffers[buffer].begin(), buffers[buffer].end(), 0.0f);

            for (const RenderCommand& renderCommand : renderCommands)
            {
                if (!processRenderCommand(renderCommand,
                                          frames,
                                          Vector3(), // listener position
                                          Quaternion(), // listener rotation
                                          1.0f, // pitch
                                          1.0f, // gain
                                          1.0f, // rolloff factor
                                          buffers[buffer])) return false;

                if (buffers[buffer].size() > buffers[buffer].size()) result.resize(buffers[buffer].size(), 0.0f);

                for (uint32_t i = 0; i < buffers[buffer].size() && i < result.size(); ++i)
                {
                    // mix the sound into the buffer
                    result[i] += buffers[buffer][i];
                }
            }

            return true;
        }

        bool AudioDevice::processRenderCommand(const RenderCommand& renderCommand,
                                               uint32_t frames,
                                               Vector3 listenerPosition,
                                               Quaternion listenerRotation,
                                               float pitch,
                                               float gain,
                                               float rolloffFactor,
                                               std::vector<float>& result)
        {
            uint32_t buffer = currentBuffer++;
            if (currentBuffer > buffers.size()) return true; // out of buffers

            buffers[buffer].resize(frames * channels);
            std::fill(buffers[buffer].begin(), buffers[buffer].end(), 0.0f);

            if (renderCommand.attributeCallback)
            {
                renderCommand.attributeCallback(listenerPosition,
                                                listenerRotation,
                                                pitch,
                                                gain,
                                                rolloffFactor);
            }

            for (const RenderCommand& command : renderCommand.renderCommands)
            {
                processRenderCommand(command,
                                     frames,
                                     listenerPosition,
                                     listenerRotation,
                                     pitch,
                                     gain,
                                     rolloffFactor,
                                     buffers[buffer]);

                if (buffers[buffer].size() > result.size()) result.resize(buffers[buffer].size());

                for (uint32_t i = 0; i < buffers[buffer].size() && i < result.size(); ++i)
                {
                    // mix the sound into the buffer
                    result[i] += buffers[buffer][i];
                }
            }

            if (renderCommand.renderCallback)
            {
                if (!renderCommand.renderCallback(frames,
                                                  channels,
                                                  sampleRate,
                                                  listenerPosition,
                                                  listenerRotation,
                                                  pitch,
                                                  gain,
                                                  rolloffFactor,
                                                  result)) return false;
            }

            return true;
        }

        bool AudioDevice::getData(uint32_t frames, std::vector<uint8_t>& result)
        {
            currentBuffer = 0;
            uint32_t buffer = currentBuffer++;
            if (currentBuffer > buffers.size()) return true; // out of buffers

            buffers[buffer].resize(frames * channels);
            std::fill(buffers[buffer].begin(), buffers[buffer].end(), 0.0f);

            if (!processRenderCommands(frames, buffers[buffer])) return false;

            for (float& f : buffers[buffer])
            {
                f = clamp(f, -1.0f, 1.0f);
            }

            switch (format)
            {
                case Audio::Format::SINT16:
                {
                    result.resize(frames * channels * sizeof(int16_t));
                    int16_t* resultPtr = reinterpret_cast<int16_t*>(result.data());

                    for (uint32_t i = 0; i < buffers[buffer].size(); ++i)
                    {
                        *resultPtr = static_cast<int16_t>(buffers[buffer][i] * 32767.0f);
                        ++resultPtr;
                    }
                    break;
                }
                case Audio::Format::FLOAT32:
                {
                    result.reserve(frames * channels * sizeof(float));
                    result.assign(reinterpret_cast<uint8_t*>(buffers[buffer].data()),
                                  reinterpret_cast<uint8_t*>(buffers[buffer].data()) + buffers[buffer].size() * sizeof(float));
                    break;
                }
            }

            return true;
        }

        void AudioDevice::executeOnAudioThread(const std::function<void(void)>& func)
        {
            std::lock_guard<std::mutex> lock(executeMutex);

            executeQueue.push(func);
        }

        void AudioDevice::executeAll()
        {
            std::function<void(void)> func;

            for (;;)
            {
                {
                    std::lock_guard<std::mutex> lock(executeMutex);

                    if (executeQueue.empty())
                    {
                        break;
                    }

                    func = std::move(executeQueue.front());
                    executeQueue.pop();
                }

                if (func)
                {
                    func();
                }
            }
        }
    } // namespace audio
} // namespace ouzel
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_DISCRETEFUNCTION_VISUALIZE_HH
#define DUNE_GDT_DISCRETEFUNCTION_VISUALIZE_HH

#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#elif defined(HAVE_CONFIG_H)
#include "config.h"
#endif

#include <memory>
#include <type_traits>

#include <dune/grid/io/file/vtk/function.hh>

namespace Dune {
namespace GDT {
namespace DiscreteFunction {

template <class SpaceImp>
class BasisVisualization : public Dune::VTKFunction<typename SpaceImp::GridPartType::GridViewType>
{
public:
  typedef SpaceImp SpaceType;
  typedef typename SpaceType::EntityType EntityType;
  typedef typename SpaceType::BaseFunctionSetType::DomainType DomainType;

private:
  typedef typename SpaceType::BaseFunctionSetType::RangeType RangeType;

public:
  BasisVisualization(const SpaceType& sp, const size_t ind, const std::string nm = "basis")
    : space_(sp)
    , index_(ind)
    , values_(space_.mapper().maxNumDofs(), RangeType(0))
    , name_(nm)
  {
    if (index_ >= space_.mapper().maxNumDofs())
      DUNE_THROW(Dune::RangeError,
                 "index has to be smaller than " << space_.mapper().maxNumDofs() << "(is " << index_ << ")!");
  }

  const SpaceType& space() const
  {
    return space_;
  }

  virtual std::string name() const
  {
    return name_;
  }

  /** \defgroup vtk ´´Methods to comply with the Dune::VTKFunction interface.'' */
  /* @{ */
  virtual int ncomps() const
  {
    return SpaceType::dimRange;
  }

  virtual double evaluate(int component, const EntityType& entity, const DomainType& x) const
  {
    const auto baseFunctionSet = space_.baseFunctionSet(entity);
    assert(component >= 0 && "Really?");
    if (component < baseFunctionSet.size()) {
      baseFunctionSet.evaluate(x, values_);
      assert(component < values_.size() && "This should not happen!");
      return values_[index_][component];
    } else if (component < space_.mapper().maxNumDofs())
      return 0.0;
    else
      DUNE_THROW(Dune::RangeError,
                 "component has to be smaller than " << space_.mapper().maxNumDofs() << "(is " << component << ")!");
  }
  /* @} */

private:
  const SpaceType& space_;
  const size_t index_;
  mutable std::vector<RangeType> values_;
  const std::string name_;
}; // class BasisVisualization

template <class SpaceImp, class VectorImp>
class VisualizationAdapter : public Dune::VTKFunction<typename SpaceImp::GridPartType::GridViewType>
{
public:
  typedef SpaceImp SpaceType;
  typedef VectorImp VectorType;

  typedef typename SpaceType::EntityType EntityType;

  typedef typename SpaceType::BaseFunctionSetType::DomainType DomainType;
  typedef typename SpaceType::BaseFunctionSetType::RangeType RangeType;

  VisualizationAdapter(const SpaceType& sp, const VectorType& vec, const std::string nm = "discrete_function")
    : space_(sp)
    , name_(nm)
    , vector_(vec)
    , indices_(space_.mapper().maxNumDofs(), 0)
    , basis_values_(space_.mapper().maxNumDofs(), RangeType(0))
  {
    assert(vector_.size() == space_.mapper().size() && "Given vector has wrong size!");
  }

  const SpaceType& space() const
  {
    return space_;
  }

  virtual std::string name() const
  {
    return name_;
  }

  /** \defgroup vtk ´´Methods to comply with the Dune::VTKFunction interface.'' */
  /* @{ */
  virtual int ncomps() const
  {
    return SpaceType::dimRange;
  }

  virtual double evaluate(int component, const EntityType& entity, const DomainType& x) const
  {
    assert(component >= 0 && "Really?");
    RangeType value(0);
    assert(component < int(value.size()) && "Really?");
    const auto baseFunctionSet = space_.baseFunctionSet(entity);
    space_.mapper().globalIndices(entity, indices_);
    baseFunctionSet.evaluate(x, basis_values_);
    for (size_t ii = 0; ii < baseFunctionSet.size(); ++ii) {
      basis_values_[ii] *= vector_.get(indices_[ii]);
      value += basis_values_[ii];
    }
    return value[component];
  }
  /* @} */

private:
  const SpaceType& space_;
  const std::string name_;
  const VectorType& vector_;
  mutable Dune::DynamicVector<size_t> indices_;
  mutable std::vector<RangeType> basis_values_;
}; // class VisualizationAdapter

} // namespace DiscreteFunction
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_DISCRETEFUNCTION_VISUALIZE_HH
<commit_msg>[discretefunction.visualize] replaced assertions by exceptions<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_DISCRETEFUNCTION_VISUALIZE_HH
#define DUNE_GDT_DISCRETEFUNCTION_VISUALIZE_HH

#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#elif defined(HAVE_CONFIG_H)
#include "config.h"
#endif

#include <memory>
#include <type_traits>

#include <dune/common/fvector.hh>
#include <dune/common/dynvector.hh>

#include <dune/grid/io/file/vtk/function.hh>

namespace Dune {
namespace GDT {
namespace DiscreteFunction {

template <class SpaceImp>
class BasisVisualization : public Dune::VTKFunction<typename SpaceImp::GridPartType::GridViewType>
{
public:
  typedef SpaceImp SpaceType;
  typedef typename SpaceType::EntityType EntityType;
  typedef typename SpaceType::BaseFunctionSetType::DomainType DomainType;

private:
  typedef typename SpaceType::BaseFunctionSetType::RangeType RangeType;

public:
  BasisVisualization(const SpaceType& sp, const size_t ind, const std::string nm = "basis")
    : space_(sp)
    , index_(ind)
    , values_(space_.mapper().maxNumDofs(), RangeType(0))
    , name_(nm)
  {
    if (index_ >= space_.mapper().maxNumDofs())
      DUNE_THROW(Dune::RangeError,
                 "index has to be smaller than " << space_.mapper().maxNumDofs() << "(is " << index_ << ")!");
  }

  const SpaceType& space() const
  {
    return space_;
  }

  virtual std::string name() const
  {
    return name_;
  }

  /** \defgroup vtk ´´Methods to comply with the Dune::VTKFunction interface.'' */
  /* @{ */
  virtual int ncomps() const
  {
    return SpaceType::dimRange;
  }

  virtual double evaluate(int component, const EntityType& entity, const DomainType& x) const
  {
    const auto baseFunctionSet = space_.baseFunctionSet(entity);
    if (component < 0)
      DUNE_THROW(Dune::RangeError, "component must not be negative (is " << component << ")!");
    if (component < baseFunctionSet.size()) {
      baseFunctionSet.evaluate(x, values_);
      assert(component < values_.size() && "This should not happen!");
      return values_[index_][component];
    } else if (component < space_.mapper().maxNumDofs())
      return 0.0;
    else
      DUNE_THROW(Dune::RangeError,
                 "component has to be smaller than " << space_.mapper().maxNumDofs() << "(is " << component << ")!");
  }
  /* @} */

private:
  const SpaceType& space_;
  const size_t index_;
  mutable std::vector<RangeType> values_;
  const std::string name_;
}; // class BasisVisualization

template <class SpaceImp, class VectorImp>
class VisualizationAdapter : public Dune::VTKFunction<typename SpaceImp::GridPartType::GridViewType>
{
public:
  typedef SpaceImp SpaceType;
  typedef VectorImp VectorType;

  typedef typename SpaceType::EntityType EntityType;

  typedef typename SpaceType::BaseFunctionSetType::DomainType DomainType;
  typedef typename SpaceType::BaseFunctionSetType::RangeType RangeType;

  VisualizationAdapter(const SpaceType& sp, const VectorType& vec, const std::string nm = "discrete_function")
    : space_(sp)
    , name_(nm)
    , vector_(vec)
    , indices_(space_.mapper().maxNumDofs(), 0)
    , basis_values_(space_.mapper().maxNumDofs(), RangeType(0))
  {
    if (vector_.size() != space_.mapper().size())
      DUNE_PYMOR_THROW(Pymor::Exception::sizes_do_not_match,
                       "The sice of vec (" << vec.size() << ") does not match the size of the space ("
                                           << space_.mapper().size()
                                           << ")!");
  }

  const SpaceType& space() const
  {
    return space_;
  }

  virtual std::string name() const
  {
    return name_;
  }

  /** \defgroup vtk ´´Methods to comply with the Dune::VTKFunction interface.'' */
  /* @{ */
  virtual int ncomps() const
  {
    return SpaceType::dimRange;
  }

  virtual double evaluate(int component, const EntityType& entity, const DomainType& xx) const
  {
    if (component < 0)
      DUNE_THROW(Dune::RangeError, "component must not be negative (is " << component << ")!");
    RangeType value(0);
    if (component >= ncomps())
      DUNE_THROW(Dune::RangeError,
                 "component has to be smaller than ncomps() = " << ncomps() << " (is " << component << ")!");
    const auto baseFunctionSet = space_.baseFunctionSet(entity);
    space_.mapper().globalIndices(entity, indices_);
    baseFunctionSet.evaluate(xx, basis_values_);
    for (size_t ii = 0; ii < baseFunctionSet.size(); ++ii) {
      basis_values_[ii] *= vector_.get(indices_[ii]);
      value += basis_values_[ii];
    }
    return value[component];
  }
  /* @} */

private:
  const SpaceType& space_;
  const std::string name_;
  const VectorType& vector_;
  mutable Dune::DynamicVector<size_t> indices_;
  mutable std::vector<RangeType> basis_values_;
}; // class VisualizationAdapter

} // namespace DiscreteFunction
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_DISCRETEFUNCTION_VISUALIZE_HH
<|endoftext|>


<commit_before>
#ifndef DUNE_GRID_PART_INTERSECTION_WRAPPER_HH
#define DUNE_GRID_PART_INTERSECTION_WRAPPER_HH

// dune-geometry
#include <dune/geometry/type.hh>

// dune-grid
#include <dune/grid/common/intersection.hh>

namespace Dune {

namespace grid {

namespace Part {

namespace Intersection {

namespace Wrapper {

template< class IntersectionIteratorImp, class WrappedIntersectionImp >
class FakeDomainBoundary
{
public:
  typedef IntersectionIteratorImp IntersectionIteratorType;

  typedef WrappedIntersectionImp WrappedIntersectionType;

  typedef FakeDomainBoundary< IntersectionIteratorType, WrappedIntersectionType > ThisType;

  static const int dimension = WrappedIntersectionType::dimension;

  static const int dimensionworld = WrappedIntersectionType::dimensionworld;

  typedef typename WrappedIntersectionType::Entity Entity;

  typedef typename WrappedIntersectionType::EntityPointer EntityPointer;

  typedef typename WrappedIntersectionType::Geometry Geometry;

  typedef typename WrappedIntersectionType::LocalCoordinate LocalCoordinate;

  typedef typename WrappedIntersectionType::GlobalCoordinate GlobalCoordinate;

  typedef typename WrappedIntersectionType::LocalGeometry LocalGeometry;

//  typedef Dune::Intersection<const GridImp, Dune::SIntersectionIterator> Intersection;

  typedef typename WrappedIntersectionType::ctype ctype;

  FakeDomainBoundary(const IntersectionIteratorType& intersectionIterator)
    : intersectionIterator_(intersectionIterator),
      passThrough_(true)
  {
  }

//  void bind(Dune::shared_ptr< const WrappedIntersectionType > wrappedIntersection)
//  {
//    wrappedIntersection_ = wrappedIntersection;
//    bound_ = true;
//  }

  bool boundary() const
  {
    //if (passThrough_)
      return intersectionIterator_.getBaseIntersection().boundary();
  }

  int boundaryId() const
  {
    //if (passThrough_)
      return intersectionIterator_.getBaseIntersection().boundaryId();
  }

  size_t boundarySegmentIndex() const
  {
    //if (passThrough_)
      return intersectionIterator_.getBaseIntersection().boundarySegmentIndex();
  }

  bool neighbor() const
  {
    //if (passThrough_)
      return intersectionIterator_.getBaseIntersection().neighbor();
  }

  EntityPointer inside() const
  {
    //if (passThrough_)
      return intersectionIterator_.getBaseIntersection().inside();
  }

  EntityPointer outside() const
  {
    //if (passThrough_)
      return intersectionIterator_.getBaseIntersection().outside();
  }

  bool conforming() const
  {
    //if (passThrough_)
      return intersectionIterator_.getBaseIntersection().conforming();
  }

  LocalGeometry geometryInInside() const
  {
    //if (passThrough_)
      return intersectionIterator_.getBaseIntersection().geometryInInside();
  }

  LocalGeometry geometryInOutside() const
  {
    //if (passThrough_)
      return intersectionIterator_.getBaseIntersection().geometryInOutside();
  }

  Geometry geometry() const
  {
    //if (passThrough_)
      return intersectionIterator_.getBaseIntersection().geometry();
  }

  Dune::GeometryType type() const
  {
    //if (passThrough_)
      return intersectionIterator_.getBaseIntersection().type();
  }

  int indexInInside() const
  {
    //if (passThrough_)
      return intersectionIterator_.getBaseIntersection().indexInInside();
  }

  int indexInOutside() const
  {
    //if (passThrough_)
      return intersectionIterator_.getBaseIntersection().indexInOutside();
  }

  GlobalCoordinate outerNormal(const LocalCoordinate& local) const
  {
    //if (passThrough_)
      return intersectionIterator_.getBaseIntersection().outerNormal(local);
  }

  GlobalCoordinate integrationOuterNormal(const LocalCoordinate& local) const
  {
    //if (passThrough_)
      return intersectionIterator_.getBaseIntersection().integrationOuterNormal(local);
  }

  GlobalCoordinate unitOuterNormal(const LocalCoordinate& local) const
  {
    //if (passThrough_)
      return intersectionIterator_.getBaseIntersection().unitOuterNormal(local);
  }

  GlobalCoordinate centerUnitOuterNormal() const
  {
    //if (passThrough_)
      return intersectionIterator_.getBaseIntersection().centerUnitOuterNormal();
  }

private:
  const IntersectionIteratorType& intersectionIterator_;
  bool passThrough_;
}; // class FakeDomainBoundary

} // namespace Wrapper

} // namespace Intersection

} // namespace Part

} // namespace grid

} // namespace Dune

#endif // DUNE_GRID_PART_INTERSECTION_WRAPPER_HH
<commit_msg>[grid.part.intersection.wrapper] finished so far<commit_after>
#ifndef DUNE_GRID_PART_INTERSECTION_WRAPPER_HH
#define DUNE_GRID_PART_INTERSECTION_WRAPPER_HH

// dune-geometry
#include <dune/geometry/type.hh>

// dune-grid
#include <dune/grid/common/intersection.hh>

namespace Dune {

namespace grid {

namespace Part {

namespace Intersection {

namespace Wrapper {

template< class IntersectionIteratorImp, class WrappedIntersectionImp >
class FakeDomainBoundary
{
public:
  typedef IntersectionIteratorImp IntersectionIteratorType;

  typedef WrappedIntersectionImp WrappedIntersectionType;

  typedef FakeDomainBoundary< IntersectionIteratorType, WrappedIntersectionType > ThisType;

  static const int dimension = WrappedIntersectionType::dimension;

  static const int dimensionworld = WrappedIntersectionType::dimensionworld;

  typedef typename WrappedIntersectionType::Entity Entity;

  typedef typename WrappedIntersectionType::EntityPointer EntityPointer;

  typedef typename WrappedIntersectionType::Geometry Geometry;

  typedef typename WrappedIntersectionType::LocalCoordinate LocalCoordinate;

  typedef typename WrappedIntersectionType::GlobalCoordinate GlobalCoordinate;

  typedef typename WrappedIntersectionType::LocalGeometry LocalGeometry;

//  typedef Dune::Intersection<const GridImp, Dune::SIntersectionIterator> Intersection;

  typedef typename WrappedIntersectionType::ctype ctype;

  FakeDomainBoundary(const IntersectionIteratorType& intersectionIterator)
    : intersectionIterator_(intersectionIterator),
      passThrough_(true),
      boundaryId_(-1)
  {
  }

  void setPassThrough(const bool passThrough)
  {
    passThrough_ = passThrough;
  }

  void setBoundaryId(const int boundaryId)
  {
    boundaryId_ = boundaryId;
  }

  bool neighbor() const
  {
    if (passThrough_)
      return intersectionIterator_.getBaseIntersection().neighbor();
    else
      return false;
  }

  bool boundary() const
  {
    if (passThrough_)
      return intersectionIterator_.getBaseIntersection().boundary();
    else
      return true;
  }

  int boundaryId() const
  {
    if (passThrough_)
      return intersectionIterator_.getBaseIntersection().boundaryId();
    else
      return boundaryId_;
  }

  size_t boundarySegmentIndex() const
  {
    return intersectionIterator_.getBaseIntersection().boundarySegmentIndex();
  }

  EntityPointer inside() const
  {
    return intersectionIterator_.getBaseIntersection().inside();
  }

  EntityPointer outside() const
  {
    return intersectionIterator_.getBaseIntersection().outside();
  }

  bool conforming() const
  {
    return intersectionIterator_.getBaseIntersection().conforming();
  }

  LocalGeometry geometryInInside() const
  {
    return intersectionIterator_.getBaseIntersection().geometryInInside();
  }

  LocalGeometry geometryInOutside() const
  {
    return intersectionIterator_.getBaseIntersection().geometryInOutside();
  }

  Geometry geometry() const
  {
    return intersectionIterator_.getBaseIntersection().geometry();
  }

  Dune::GeometryType type() const
  {
    return intersectionIterator_.getBaseIntersection().type();
  }

  int indexInInside() const
  {
    return intersectionIterator_.getBaseIntersection().indexInInside();
  }

  int indexInOutside() const
  {
    return intersectionIterator_.getBaseIntersection().indexInOutside();
  }

  GlobalCoordinate outerNormal(const LocalCoordinate& local) const
  {
    return intersectionIterator_.getBaseIntersection().outerNormal(local);
  }

  GlobalCoordinate integrationOuterNormal(const LocalCoordinate& local) const
  {
    return intersectionIterator_.getBaseIntersection().integrationOuterNormal(local);
  }

  GlobalCoordinate unitOuterNormal(const LocalCoordinate& local) const
  {
    return intersectionIterator_.getBaseIntersection().unitOuterNormal(local);
  }

  GlobalCoordinate centerUnitOuterNormal() const
  {
    return intersectionIterator_.getBaseIntersection().centerUnitOuterNormal();
  }

private:
  const IntersectionIteratorType& intersectionIterator_;
  bool passThrough_;
  int boundaryId_;
}; // class FakeDomainBoundary

} // namespace Wrapper

} // namespace Intersection

} // namespace Part

} // namespace grid

} // namespace Dune

#endif // DUNE_GRID_PART_INTERSECTION_WRAPPER_HH
<|endoftext|>